Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. require 'digest'
  2. class User < ActiveRecord::Base
  3. attr_accessor :password
  4.  
  5. validates :email, :uniqueness => true,
  6. :length => { :within => 5..50 },
  7. :format => { :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i }
  8. validates :password, :confirmation => true,
  9. :length => { :within => 4..20 },
  10. :presence => true,
  11. :if => :password_required?
  12.  
  13. has_one :profile
  14. has_many :articles, :order => 'created_at DESC, title ASC', :dependent => :nullify
  15. has_many :replies, :through => :articles, :source => :comments
  16.  
  17. before_save :encrypt_new_password
  18.  
  19. def self.authenticate(email, password)
  20. user = find_by_email(email)
  21. return user if user && user.authenticated?(password)
  22. end
  23.  
  24. def authenticated?(password)
  25. self.hashed_pasword == ecrypt(password)
  26. end
  27.  
  28. protected
  29. def encrypt_new_password
  30. return if password.blank?
  31. self.hashed_password = encrypt(password)
  32. end
  33.  
  34. def password_required?
  35. hashed_password.blank? || password.present?
  36. end
  37.  
  38. def encrypt(string)
  39. Digest::SHA1.hexdigest(string)
  40. end
  41. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement