Guest User

Untitled

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