2014-02-09 13:44:09 +00:00
|
|
|
class ApiToken < ActiveRecord::Base
|
2014-02-12 16:41:06 +00:00
|
|
|
|
|
|
|
ApiTokenTakenError = Class.new(StandardError)
|
|
|
|
|
2012-03-04 17:14:58 +00:00
|
|
|
belongs_to :user
|
|
|
|
|
2014-02-12 16:41:06 +00:00
|
|
|
validates :user, :token, presence: true
|
2015-04-04 17:57:34 +00:00
|
|
|
validates :token, uniqueness: true, format: { with: /\A[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\z/ }
|
2014-02-12 16:41:06 +00:00
|
|
|
|
2015-04-02 09:45:39 +00:00
|
|
|
scope :active, -> { where(revoked_at: nil) }
|
|
|
|
scope :revoked, -> { where('revoked_at IS NOT NULL') }
|
|
|
|
|
2014-02-12 16:41:06 +00:00
|
|
|
def self.for_token(token)
|
2015-04-03 16:48:37 +00:00
|
|
|
where(token: token).first
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.create_with_tmp_user!(token, username)
|
|
|
|
transaction do
|
|
|
|
ApiToken.create!(
|
|
|
|
token: token,
|
|
|
|
user: User.create!(temporary_username: username.presence),
|
|
|
|
)
|
|
|
|
end
|
2014-02-12 16:41:06 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def reassign_to(target_user)
|
|
|
|
return if target_user == user
|
|
|
|
raise ApiTokenTakenError if taken?
|
|
|
|
|
|
|
|
user.merge_to(target_user)
|
|
|
|
end
|
|
|
|
|
2015-04-02 09:45:39 +00:00
|
|
|
def revoke!
|
|
|
|
update!(revoked_at: Time.now)
|
|
|
|
end
|
|
|
|
|
2014-02-12 16:41:06 +00:00
|
|
|
private
|
|
|
|
|
|
|
|
def taken?
|
2014-10-05 15:47:42 +00:00
|
|
|
user.confirmed?
|
2014-02-12 16:41:06 +00:00
|
|
|
end
|
|
|
|
|
2012-03-04 17:14:58 +00:00
|
|
|
end
|