user.rb 2.6 KB

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