12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- class Token < ApplicationRecord
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- TYPES = {
- password_reset: 'pw_reset',
- account_confirmation: 'confirm',
- api_authentication: 'api'
- }
- validates :token, uniqueness: true, presence: true
- validates :user, presence: true
- belongs_to :user
- before_validation :generate_token, if: "self.token.blank?"
- before_validation :generate_expiry, on: :create
- private
- def generate_token
- candidate = nil
- loop do
- candidate = SecureRandom::urlsafe_base64 32
- break candidate unless Token.exists?(token: candidate)
- end
- self.token = candidate
- end
-
- def generate_expiry
- case self.tokentype
- when TYPES[:password_reset]
- self.expires = 1.days.since
- when TYPES[:account_confirmation]
- self.expires = 7.days.since
- end
- end
- end
|