user.rb 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. class User < ApplicationRecord
  2. attr_accessor :remember_token
  3. validates :name, presence: true, length: { maximum: 255 }
  4. VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  5. validates :email, presence: true, length: { maximum: 255 },
  6. format: { with: VALID_EMAIL_REGEX },
  7. uniqueness: { case_sensitive: false }
  8. before_save { email.downcase! }
  9. validates :login, presence: true, length: { maximum: 50 },
  10. format: { with: /\A[a-zA-Z0-9_]+\Z/ },
  11. uniqueness: { case_sensitive: false }
  12. has_secure_password
  13. validates :password, presence: true, length: { minimum: 6 },
  14. if: lambda { new_record? || !password.blank? ||
  15. !password_confirmation.blank? }
  16. enum gender: [ :unspecified, :male, :female, :other ]
  17. VALID_PHONE_REGEX = /[0-9a-z\-+() .]*/i
  18. validates :phone, length: { maximum: 255 },
  19. format: { with: VALID_PHONE_REGEX }
  20. validates :birth_date, presence: true
  21. mount_uploader :picture, PictureUploader
  22. validate :picture_size
  23. # Returns the hash digest of the given string.
  24. def User.digest(string)
  25. cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
  26. BCrypt::Engine.cost
  27. BCrypt::Password.create(string, cost: cost)
  28. end
  29. # Returns a random token.
  30. def User.new_token
  31. SecureRandom.urlsafe_base64
  32. end
  33. def remember
  34. self.remember_token = User.new_token
  35. update_attribute(:remember_digest, User.digest(remember_token))
  36. end
  37. # Returns true if the given token matches the digest.
  38. def authenticated?(attribute, token)
  39. digest = send("#{attribute}_digest")
  40. return false if digest.nil?
  41. BCrypt::Password.new(digest).is_password?(token)
  42. end
  43. # Forgets a user.
  44. def forget
  45. update_attribute(:remember_digest, nil)
  46. end
  47. private
  48. def picture_size
  49. if picture.size > 5.megabytes
  50. errors.add(:picture, "should be less than 5MB")
  51. end
  52. end
  53. end