3 class ClientApplication < ActiveRecord::Base
5 has_many :tokens, :class_name => "OauthToken"
6 has_many :access_tokens
8 validates_presence_of :name, :url, :key, :secret
9 validates_uniqueness_of :key
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][a-z0-9.+-]*:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
14 before_validation :generate_keys, :on => :create
16 attr_accessor :token_callback_url
18 def self.find_token(token_key)
19 token = OauthToken.find_by_token(token_key, :include => :client_application)
20 if token && token.authorized?
27 def self.verify_request(request, options = {}, &block)
29 signature = OAuth::Signature.build(request, options, &block)
30 logger.info "Signature Base String: #{signature.signature_base_string}"
31 logger.info "Consumer: #{signature.send :consumer_key}"
32 logger.info "Token: #{signature.send :token}"
33 return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
34 value = signature.verify
35 logger.info "Signature verification returned: #{value.to_s}"
37 rescue OAuth::Signature::UnknownSignatureMethod => e
38 logger.info "ERROR"+e.to_s
43 def self.all_permissions
48 @oauth_server ||= OAuth::Server.new("http://" + SERVER_URL)
52 @oauth_client ||= OAuth::Consumer.new(key, secret)
55 def create_request_token
56 RequestToken.create :client_application => self, :callback_url => self.token_callback_url
59 def access_token_for_user(user)
60 unless token = access_tokens.valid.where(:user_id => user).first
61 params = { :user => user }
63 permissions.each do |p|
67 token = access_tokens.create(params)
73 # the permissions that this client would like from the user
75 ClientApplication.all_permissions.select { |p| self[p] }
80 # this is the set of permissions that the client can ask for. clients
81 # have to say up-front what permissions they want and when users sign up they
82 # can agree or not agree to each of them.
83 PERMISSIONS = [:allow_read_prefs, :allow_write_prefs, :allow_write_diary,
84 :allow_write_api, :allow_read_gpx, :allow_write_gpx ]
87 oauth_client = oauth_server.generate_consumer_credentials
88 self.key = oauth_client.key
89 self.secret = oauth_client.secret