Guest User

Untitled

a guest
Mar 15th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2. attr_accessor :password
  3. attr_accessible :name, :email, :password, :password_confirmation
  4.  
  5. email_regex = /\A[\w+\-.]+@[a-zA-Z\d\-.]+\.[a-z]+\z/i
  6.  
  7. validates :name, :presence => true,
  8. :length => { :maximum => 50 }
  9.  
  10. validates :email, :presence => true,
  11. :format => { :with=> email_regex },
  12. :uniqueness => { :case_sensitive => false }
  13.  
  14. validates :password, :presence => true,
  15. :confirmation => true,
  16. :length => { :within => 6..40 }
  17.  
  18. before_save :encrypt_password
  19.  
  20. # Return true if the user's password matches the submitted password.
  21. def has_password?(submitted_password)
  22. # Compare encrypted_password with the encrypted version of
  23. # submitted_password.
  24. encrypted_password == encrypt(submitted_password)
  25.  
  26. end
  27.  
  28.  
  29. def self.authenticate(email, submitted_password)
  30. user = find_by_email(email)
  31. return nil if user.nil?
  32. return user if user.has_password?(submitted_password)
  33. end
  34.  
  35. private
  36.  
  37. def encrypt_password
  38. self.salt = make_salt unless has_password?(password)
  39. self.encrypted_password = encrypt(password)
  40. end
  41.  
  42. def encrypt(string)
  43. secure_hash("#{salt}--#{string}")
  44. end
  45.  
  46. def make_salt
  47. secure_hash("#{Time.now.utc}--#{password}")
  48. end
  49.  
  50. def secure_hash(string)
  51. Digest::SHA2.hexdigest(string)
  52. end
  53.  
  54. end
Add Comment
Please, Sign In to add comment