]> git.openstreetmap.org Git - rails.git/blob - app/models/oauth_token.rb
Merge remote-tracking branch 'upstream/pull/1693'
[rails.git] / app / models / oauth_token.rb
1 # == Schema Information
2 #
3 # Table name: oauth_tokens
4 #
5 #  id                    :integer          not null, primary key
6 #  user_id               :integer
7 #  type                  :string(20)
8 #  client_application_id :integer
9 #  token                 :string(50)
10 #  secret                :string(50)
11 #  authorized_at         :datetime
12 #  invalidated_at        :datetime
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 #  callback_url          :string
22 #  verifier              :string(20)
23 #  scope                 :string
24 #  valid_to              :datetime
25 #  allow_write_notes     :boolean          default(FALSE), not null
26 #
27 # Indexes
28 #
29 #  index_oauth_tokens_on_token    (token) UNIQUE
30 #  index_oauth_tokens_on_user_id  (user_id)
31 #
32 # Foreign Keys
33 #
34 #  oauth_tokens_client_application_id_fkey  (client_application_id => client_applications.id)
35 #  oauth_tokens_user_id_fkey                (user_id => users.id)
36 #
37
38 class OauthToken < ActiveRecord::Base
39   belongs_to :client_application
40   belongs_to :user
41
42   scope :authorized, -> { where("authorized_at IS NOT NULL and invalidated_at IS NULL") }
43
44   validates :token, :presence => true, :uniqueness => true
45   validates :user, :associated => true
46   validates :client_application, :presence => true
47
48   before_validation :generate_keys, :on => :create
49
50   def invalidated?
51     invalidated_at != nil
52   end
53
54   def invalidate!
55     update_attributes(:invalidated_at => Time.now)
56   end
57
58   def authorized?
59     !authorized_at.nil? && !invalidated?
60   end
61
62   def to_query
63     "oauth_token=#{token}&oauth_token_secret=#{secret}"
64   end
65
66   protected
67
68   def generate_keys
69     self.token = OAuth::Helper.generate_key(40)[0, 40]
70     self.secret = OAuth::Helper.generate_key(40)[0, 40]
71   end
72 end