Guest User

Untitled

a guest
Mar 11th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. require 'digest/sha1'
  2.  
  3. class User < ActiveRecord::Base
  4.  
  5. attr_accessor :password
  6.  
  7. has_many :events, :dependent => :destroy
  8. has_many :registrations, :dependent => :destroy
  9. has_many :activities, :through => :registrations, :source => :event
  10.  
  11. validates_presence_of :login
  12. validates_length_of :login, :within => 3..40
  13. validates_uniqueness_of :login, :case_sensitive => false
  14. validates_format_of :login, :with => /^[\w\.-]+$/i
  15.  
  16. validates_presence_of :email
  17. validates_format_of :email, :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i
  18. validates_presence_of :password, :if => :password_required?
  19. validates_length_of :password, :within => 4..40, :if => :password_required?
  20. validates_confirmation_of :password, :if => :password_required?
  21.  
  22. before_save :encrypt_new_password
  23.  
  24. def self.authenticate(login, password)
  25. user = find_by_login(login)
  26. return user if user && user.authenticated?(password)
  27. end
  28.  
  29. def authenticated?(password)
  30. hashed_password == encrypt(password)
  31. end
  32.  
  33. protected
  34.  
  35. def encrypt_new_password
  36. return if password.blank?
  37. self.hashed_password = encrypt(password)
  38. end
  39.  
  40. def password_required?
  41. hashed_password.blank? || !password.blank?
  42. end
  43.  
  44. def encrypt(string)
  45. Digest::SHA1.hexdigest(string)
  46. end
  47.  
  48. end
Add Comment
Please, Sign In to add comment