Sprankelprachtig aan/afmeldsysteem

token.rb 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. class Token < ApplicationRecord
  2. # A Token contains some information that can be used as an alternative way to
  3. # authenticate a user, typically instead of a username/password combination.
  4. #
  5. # At least the following types of tokens will exist:
  6. # - Account confirmation tokens, sent to the user when their account is
  7. # created (to verify their email address)
  8. # - Password reset tokens
  9. # - API authentication tokens
  10. #
  11. # @!attribute token
  12. # @return [String]
  13. # a unique token, that allows the holder to perform some action.
  14. #
  15. # @!attribute expires
  16. # @return [DateTime]
  17. # when the token will expire (and will no longer be usable). May be nil
  18. # for no expiry.
  19. #
  20. # @!attribute tokentype
  21. # @return [String]
  22. # what action the token allows the holder to perform. Use the hash
  23. # Token::TYPES instead of comparing directly!
  24. #
  25. # @!attribute user
  26. # @return [User]
  27. # what user the token allows the holder to authenticate as.
  28. TYPES = {
  29. password_reset: 'pw_reset',
  30. account_confirmation: 'confirm',
  31. api_authentication: 'api'
  32. }.freeze
  33. validates :token, uniqueness: true, presence: true
  34. validates :user, presence: true
  35. belongs_to :user
  36. before_validation :generate_token, if: "self.token.blank?"
  37. before_validation :generate_expiry, on: :create
  38. private
  39. def generate_token
  40. candidate = nil
  41. loop do
  42. candidate = SecureRandom.urlsafe_base64 32
  43. break candidate unless Token.exists?(token: candidate)
  44. end
  45. self.token = candidate
  46. end
  47. # Defines the default expiry for the expiring tokens.
  48. def generate_expiry
  49. case tokentype
  50. when TYPES[:password_reset]
  51. self.expires = 1.day.since
  52. when TYPES[:account_confirmation]
  53. self.expires = 7.days.since
  54. end
  55. end
  56. end