Guest User

Untitled

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