123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- 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
|