]> git.openstreetmap.org Git - rails.git/blob - app/models/client_application.rb
Merge 16110:16487 from trunk.
[rails.git] / app / models / client_application.rb
1 require 'oauth'
2 class ClientApplication < ActiveRecord::Base
3   belongs_to :user
4   has_many :tokens, :class_name => "OauthToken"
5   validates_presence_of :name, :url, :key, :secret
6   validates_uniqueness_of :key
7   before_validation_on_create :generate_keys
8   
9   def self.find_token(token_key)
10     token = OauthToken.find_by_token(token_key, :include => :client_application)
11     if token && token.authorized?
12       logger.info "Loaded #{token.token} which was authorized by (user_id=#{token.user_id}) on the #{token.authorized_at}"
13       token
14     else
15       nil
16     end
17   end
18   
19   def self.verify_request(request, options = {}, &block)
20     begin
21       signature = OAuth::Signature.build(request, options, &block)
22       logger.info "Signature Base String: #{signature.signature_base_string}"
23       logger.info "Consumer: #{signature.send :consumer_key}"
24       logger.info "Token: #{signature.send :token}"
25       return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
26       value = signature.verify
27       logger.info "Signature verification returned: #{value.to_s}"
28       value
29     rescue OAuth::Signature::UnknownSignatureMethod => e
30       logger.info "ERROR"+e.to_s
31       false
32     end
33   end
34   
35   def self.all_permissions
36     PERMISSIONS
37   end
38
39   def oauth_server
40     @oauth_server ||= OAuth::Server.new("http://" + SERVER_URL)
41   end
42   
43   def credentials
44     @oauth_client ||= OAuth::Consumer.new(key, secret)
45   end
46     
47   def create_request_token
48     RequestToken.create :client_application => self
49   end
50
51   # the permissions that this client would like from the user
52   def permissions
53     ClientApplication.all_permissions.select { |p| self[p] }
54   end
55
56 protected
57   
58   # this is the set of permissions that the client can ask for. clients
59   # have to say up-front what permissions they want and when users sign up they
60   # can agree or not agree to each of them.
61   PERMISSIONS = [:allow_read_prefs, :allow_write_prefs, :allow_write_diary,
62                  :allow_write_api, :allow_read_gpx, :allow_write_gpx ]
63
64   def generate_keys
65     @oauth_client = oauth_server.generate_consumer_credentials
66     self.key = @oauth_client.key
67     self.secret = @oauth_client.secret
68   end
69 end