1 # == Schema Information
3 # Table name: client_applications
5 # id :integer not null, primary key
13 # created_at :datetime
14 # updated_at :datetime
15 # allow_read_prefs :boolean default(FALSE), not null
16 # allow_write_prefs :boolean default(FALSE), not null
17 # allow_write_diary :boolean default(FALSE), not null
18 # allow_write_api :boolean default(FALSE), not null
19 # allow_read_gpx :boolean default(FALSE), not null
20 # allow_write_gpx :boolean default(FALSE), not null
21 # allow_write_notes :boolean default(FALSE), not null
25 # index_client_applications_on_key (key) UNIQUE
26 # index_client_applications_on_user_id (user_id)
30 # client_applications_user_id_fkey (user_id => users.id)
33 class ClientApplication < ApplicationRecord
35 has_many :tokens, :class_name => "OauthToken", :dependent => :delete_all
36 has_many :access_tokens
37 has_many :oauth2_verifiers
38 has_many :oauth_tokens
40 validates :key, :presence => true, :uniqueness => true
41 validates :name, :url, :secret, :presence => true
42 validates :url, :format => /\A#{URI::DEFAULT_PARSER.make_regexp(%w[http https])}\z/
43 validates :support_url, :allow_blank => true, :format => /\A#{URI::DEFAULT_PARSER.make_regexp(%w[http https])}\z/
44 validates :callback_url, :allow_blank => true, :format => /\A#{URI::DEFAULT_PARSER.make_regexp}\z/
46 before_validation :generate_keys, :on => :create
48 attr_accessor :token_callback_url
50 def self.find_token(token_key)
51 token = OauthToken.includes(:client_application).find_by(:token => token_key)
52 token if token&.authorized?
55 def self.verify_request(request, options = {}, &block)
56 signature = OAuth::Signature.build(request, options, &block)
57 return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
60 rescue OAuth::Signature::UnknownSignatureMethod
64 def self.all_permissions
69 @oauth_server ||= OAuth::Server.new("https://" + Settings.server_url)
73 @credentials ||= OAuth::Consumer.new(key, secret)
76 def create_request_token(_params = {})
77 params = { :client_application => self, :callback_url => token_callback_url }
78 permissions.each do |p|
81 RequestToken.create(params)
84 def access_token_for_user(user)
85 unless token = access_tokens.valid.find_by(:user_id => user)
86 params = { :user => user }
88 permissions.each do |p|
92 token = access_tokens.create(params)
98 # the permissions that this client would like from the user
100 ClientApplication.all_permissions.select { |p| self[p] }
105 # this is the set of permissions that the client can ask for. clients
106 # have to say up-front what permissions they want and when users sign up they
107 # can agree or not agree to each of them.
108 PERMISSIONS = [:allow_read_prefs, :allow_write_prefs, :allow_write_diary, :allow_write_api, :allow_read_gpx, :allow_write_gpx, :allow_write_notes].freeze
111 self.key = OAuth::Helper.generate_key(40)[0, 40]
112 self.secret = OAuth::Helper.generate_key(40)[0, 40]