user.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. has_many :messages
  24. has_many :conversation_participations, dependent: :destroy
  25. has_many :conversations, through: :conversation_participations
  26. # Returns the hash digest of the given string.
  27. def User.digest(string)
  28. cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
  29. BCrypt::Engine.cost
  30. BCrypt::Password.create(string, cost: cost)
  31. end
  32. # Returns a random token.
  33. def User.new_token
  34. SecureRandom.urlsafe_base64
  35. end
  36. def remember
  37. self.remember_token = User.new_token
  38. update_attribute(:remember_digest, User.digest(remember_token))
  39. end
  40. # Returns true if the given token matches the digest.
  41. def authenticated?(attribute, token)
  42. digest = send("#{attribute}_digest")
  43. return false if digest.nil?
  44. BCrypt::Password.new(digest).is_password?(token)
  45. end
  46. # Forgets a user.
  47. def forget
  48. update_attribute(:remember_digest, nil)
  49. end
  50. private
  51. def picture_size
  52. if picture.size > 5.megabytes
  53. errors.add(:picture, "should be less than 5MB")
  54. end
  55. end
  56. end