2 class ClientApplication < ActiveRecord::Base
4 has_many :tokens, :class_name => "OauthToken"
5 has_many :access_tokens
6 validates_presence_of :name, :url, :key, :secret
7 validates_uniqueness_of :key
8 before_validation_on_create :generate_keys
10 validates_format_of :url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i
11 validates_format_of :support_url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
12 validates_format_of :callback_url, :with => /\A([a-z]){1}([\w0-9\.\+\-])*:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
14 attr_accessor :token_callback_url
16 def self.find_token(token_key)
17 token = OauthToken.find_by_token(token_key, :include => :client_application)
18 if token && token.authorized?
25 def self.verify_request(request, options = {}, &block)
27 signature = OAuth::Signature.build(request, options, &block)
28 logger.info "Signature Base String: #{signature.signature_base_string}"
29 logger.info "Consumer: #{signature.send :consumer_key}"
30 logger.info "Token: #{signature.send :token}"
31 return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
32 value = signature.verify
33 logger.info "Signature verification returned: #{value.to_s}"
35 rescue OAuth::Signature::UnknownSignatureMethod => e
36 logger.info "ERROR"+e.to_s
41 def self.all_permissions
46 @oauth_server ||= OAuth::Server.new("http://" + SERVER_URL)
50 @oauth_client ||= OAuth::Consumer.new(key, secret)
53 def create_request_token
54 RequestToken.create :client_application => self, :callback_url => self.token_callback_url
57 def access_token_for_user(user)
58 unless token = access_tokens.find(:first, :conditions => { :user_id => user.id, :invalidated_at => nil })
59 params = { :user => user }
61 permissions.each do |p|
65 token = access_tokens.create(params)
71 # the permissions that this client would like from the user
73 ClientApplication.all_permissions.select { |p| self[p] }
78 # this is the set of permissions that the client can ask for. clients
79 # have to say up-front what permissions they want and when users sign up they
80 # can agree or not agree to each of them.
81 PERMISSIONS = [:allow_read_prefs, :allow_write_prefs, :allow_write_diary,
82 :allow_write_api, :allow_read_gpx, :allow_write_gpx ]
85 oauth_client = oauth_server.generate_consumer_credentials
86 self.key = oauth_client.key
87 self.secret = oauth_client.secret