user.rb 2.5 KB

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