]> git.openstreetmap.org Git - rails.git/blob - config/initializers/oauth.rb
Merge remote-tracking branch 'upstream/pull/4717'
[rails.git] / config / initializers / oauth.rb
1 require "oauth/controllers/provider_controller"
2 require "oauth/helper"
3 require "oauth/rack/oauth_filter"
4
5 Rails.configuration.middleware.use OAuth::Rack::OAuthFilter
6
7 module OAuth
8   module Helper
9     def escape(value)
10       value.to_s.gsub(OAuth::RESERVED_CHARACTERS) do |c|
11         c.bytes.map do |b|
12           format("%%%02X", b)
13         end.join
14       end.force_encoding(Encoding::US_ASCII)
15     end
16
17     def unescape(value)
18       value.to_s.gsub(/%\h{2}/) do |c|
19         c[1..].to_i(16).chr
20       end.force_encoding(Encoding::UTF_8)
21     end
22   end
23
24   module RequestProxy
25     class RackRequest
26       def method
27         request.request_method
28       end
29     end
30   end
31 end
32
33 module OpenStreetMap
34   module ProviderController
35     def self.prepended(mod)
36       super
37       mod.singleton_class.prepend(OpenStreetMap::ProviderController::ClassMethods)
38     end
39
40     def render(options = {})
41       text = options.delete(:text)
42       if text
43         super(options.merge(:plain => text))
44       elsif options.delete(:nothing)
45         status = options.delete(:status) || :ok
46         head status, options
47       else
48         super(options)
49       end
50     end
51
52     module ClassMethods
53       def included(controller)
54         controller.class_eval do
55           def self.before_filter(...)
56             before_action(...)
57           end
58
59           def self.skip_before_filter(...)
60             skip_before_action(...)
61           end
62         end
63
64         super(controller)
65       end
66     end
67   end
68
69   module OAuthFilter
70     def oauth1_verify(request, options = {}, &block)
71       signature = OAuth::Signature.build(request, options, &block)
72       return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
73
74       value = signature.verify
75       if request.ssl? && !value
76         http_request = request.dup
77         http_request.define_singleton_method(:scheme) { "http" }
78         http_request.define_singleton_method(:port) { 80 }
79         signature = OAuth::Signature.build(http_request, options, &block)
80         value = signature.verify
81       end
82       value
83     rescue OAuth::Signature::UnknownSignatureMethod
84       false
85     end
86   end
87 end
88
89 OAuth::Controllers::ProviderController.prepend(OpenStreetMap::ProviderController)
90 OAuth::Rack::OAuthFilter.prepend(OpenStreetMap::OAuthFilter)