/models/account.rb

https://github.com/mathieul/videos · Ruby · 53 lines · 36 code · 8 blank · 9 comment · 4 complexity · 1acb6f3139dc816fac08fd281a1d2725 MD5 · raw file

  1. class Account
  2. include Mongoid::Document
  3. attr_accessor :password, :password_confirmation
  4. # Fields
  5. field :name, :type => String
  6. field :surname, :type => String
  7. field :email, :type => String
  8. field :crypted_password, :type => String
  9. field :role, :type => String
  10. # Validations
  11. validates_presence_of :email, :role
  12. validates_presence_of :password, :if => :password_required
  13. validates_presence_of :password_confirmation, :if => :password_required
  14. validates_length_of :password, :within => 4..40, :if => :password_required
  15. validates_confirmation_of :password, :if => :password_required
  16. validates_length_of :email, :within => 3..100
  17. validates_uniqueness_of :email, :case_sensitive => false
  18. validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  19. validates_format_of :role, :with => /[A-Za-z]/
  20. # Callbacks
  21. before_save :encrypt_password, :if => :password_required
  22. ##
  23. # This method is for authentication purpose
  24. #
  25. def self.authenticate(email, password)
  26. account = first(:conditions => { :email => email }) if email.present?
  27. account && account.has_password?(password) ? account : nil
  28. end
  29. ##
  30. # This method is used by AuthenticationHelper
  31. #
  32. def self.find_by_id(id)
  33. find(id) rescue nil
  34. end
  35. def has_password?(password)
  36. ::BCrypt::Password.new(crypted_password) == password
  37. end
  38. private
  39. def encrypt_password
  40. self.crypted_password = ::BCrypt::Password.create(self.password)
  41. end
  42. def password_required
  43. crypted_password.blank? || self.password.present?
  44. end
  45. end