]> git.openstreetmap.org Git - rails.git/blob - app/models/client_application.rb
Simplify "report a problem" control
[rails.git] / app / models / client_application.rb
1 require "oauth"
2
3 class ClientApplication < ActiveRecord::Base
4   belongs_to :user
5   has_many :tokens, :class_name => "OauthToken", :dependent => :delete_all
6   has_many :access_tokens
7   has_many :oauth2_verifiers
8   has_many :oauth_tokens
9
10   validates :key, :presence => true, :uniqueness => true
11   validates :name, :url, :secret, :presence => true
12   validates :url, :format => %r{\Ahttp(s?)://(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(/|/([\w#!:.?+=&%@!\-/]))?}i
13   validates :support_url, :callback_url, :allow_blank => true, :format => %r{\Ahttp(s?)://(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(/|/([\w#!:.?+=&%@!\-/]))?}i
14
15   before_validation :generate_keys, :on => :create
16
17   attr_accessor :token_callback_url
18
19   def self.find_token(token_key)
20     token = OauthToken.find_by_token(token_key, :include => :client_application)
21     token if token && token.authorized?
22   end
23
24   def self.verify_request(request, options = {}, &block)
25     signature = OAuth::Signature.build(request, options, &block)
26     return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
27     value = signature.verify
28     value
29   rescue OAuth::Signature::UnknownSignatureMethod
30     false
31   end
32
33   def self.all_permissions
34     PERMISSIONS
35   end
36
37   def oauth_server
38     @oauth_server ||= OAuth::Server.new("http://" + SERVER_URL)
39   end
40
41   def credentials
42     @oauth_client ||= OAuth::Consumer.new(key, secret)
43   end
44
45   def create_request_token(params = {})
46     params = { :client_application => self, :callback_url => token_callback_url }
47     permissions.each do |p|
48       params[p] = true
49     end
50     RequestToken.create(params)
51   end
52
53   def access_token_for_user(user)
54     unless token = access_tokens.valid.find_by(:user_id => user)
55       params = { :user => user }
56
57       permissions.each do |p|
58         params[p] = true
59       end
60
61       token = access_tokens.create(params)
62     end
63
64     token
65   end
66
67   # the permissions that this client would like from the user
68   def permissions
69     ClientApplication.all_permissions.select { |p| self[p] }
70   end
71
72   protected
73
74   # this is the set of permissions that the client can ask for. clients
75   # have to say up-front what permissions they want and when users sign up they
76   # can agree or not agree to each of them.
77   PERMISSIONS = [:allow_read_prefs, :allow_write_prefs, :allow_write_diary,
78                  :allow_write_api, :allow_read_gpx, :allow_write_gpx,
79                  :allow_write_notes]
80
81   def generate_keys
82     self.key = OAuth::Helper.generate_key(40)[0, 40]
83     self.secret = OAuth::Helper.generate_key(40)[0, 40]
84   end
85 end