]> git.openstreetmap.org Git - rails.git/blob - app/models/client_application.rb
Only Potlatch 1 needs a token to be created
[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   validates_format_of :url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i
10   validates_format_of :support_url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
11   validates_format_of :callback_url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
12
13   attr_accessor :token_callback_url
14   
15   def self.find_token(token_key)
16     token = OauthToken.find_by_token(token_key, :include => :client_application)
17     if token && token.authorized?
18       token
19     else
20       nil
21     end
22   end
23
24   def self.verify_request(request, options = {}, &block)
25     begin
26       signature = OAuth::Signature.build(request, options, &block)
27       logger.info "Signature Base String: #{signature.signature_base_string}"
28       logger.info "Consumer: #{signature.send :consumer_key}"
29       logger.info "Token: #{signature.send :token}"
30       return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
31       value = signature.verify
32       logger.info "Signature verification returned: #{value.to_s}"
33       value
34     rescue OAuth::Signature::UnknownSignatureMethod => e
35       logger.info "ERROR"+e.to_s
36       false
37     end
38   end
39   
40   def self.all_permissions
41     PERMISSIONS
42   end
43
44   def oauth_server
45     @oauth_server ||= OAuth::Server.new("http://" + SERVER_URL)
46   end
47   
48   def credentials
49     @oauth_client ||= OAuth::Consumer.new(key, secret)
50   end
51     
52   def create_request_token
53     RequestToken.create :client_application => self, :callback_url => self.token_callback_url
54   end
55
56   # the permissions that this client would like from the user
57   def permissions
58     ClientApplication.all_permissions.select { |p| self[p] }
59   end
60
61 protected
62   
63   # this is the set of permissions that the client can ask for. clients
64   # have to say up-front what permissions they want and when users sign up they
65   # can agree or not agree to each of them.
66   PERMISSIONS = [:allow_read_prefs, :allow_write_prefs, :allow_write_diary,
67                  :allow_write_api, :allow_read_gpx, :allow_write_gpx ]
68
69   def generate_keys
70     oauth_client = oauth_server.generate_consumer_credentials
71     self.key = oauth_client.key
72     self.secret = oauth_client.secret
73   end
74 end