2013-06-25 08:00:20 +01:00
|
|
|
class Token < ActiveRecord::Base
|
2014-01-21 04:51:49 +00:00
|
|
|
belongs_to :subject, polymorphic: true, touch: true
|
|
|
|
belongs_to :creator, class_name: 'User'
|
|
|
|
belongs_to :updater, class_name: 'User'
|
2013-06-25 08:00:20 +01:00
|
|
|
|
2014-01-21 04:51:49 +00:00
|
|
|
validates :creator_id, :subject_id, :subject_type, presence: true
|
2014-03-11 07:39:25 +00:00
|
|
|
validates :authentication_token, presence: true, uniqueness: { case_sensitive: true }
|
2014-11-28 16:19:06 +00:00
|
|
|
validates :description, length: { maximum: 1000 }
|
2013-06-25 08:00:20 +01:00
|
|
|
|
2014-03-11 07:39:25 +00:00
|
|
|
default_scope { order(created_at: :desc) }
|
|
|
|
scope :by_active, -> { where(status: 'active') }
|
2013-06-25 08:00:20 +01:00
|
|
|
|
2014-01-21 04:51:49 +00:00
|
|
|
before_validation :generate_token, on: :create
|
2013-06-25 08:00:20 +01:00
|
|
|
|
2014-01-21 04:51:49 +00:00
|
|
|
state_machine :status, initial: :active do
|
2013-06-25 08:00:20 +01:00
|
|
|
event :block do
|
|
|
|
transition [:active, :blocked] => :blocked
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
def generate_token
|
|
|
|
self.authentication_token = loop do
|
2013-06-25 09:10:45 +01:00
|
|
|
token = SecureRandom.urlsafe_base64(32)
|
2014-01-21 04:51:49 +00:00
|
|
|
break token unless Token.where(authentication_token: token).exists?
|
2013-06-25 08:00:20 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|