Guest User

Untitled

a guest
May 28th, 2018
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 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. EmailRegex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  7. validates_presence_of :name , :email
  8. validates_length_of :name, :maximum => 50
  9. validates_format_of :email, :with => EmailRegex
  10. validates_uniqueness_of :email, :case_sensitive => false
  11.  
  12. #Automatically create the virtual attribute 'password confirmation'.
  13. validates_confirmation_of :password
  14.  
  15. #Password validations.
  16. validates_presence_of :password
  17. validates_length_of :password, :within => 6..40
  18.  
  19. before_save :encrypt_password
  20.  
  21. def has_password?(submitted_password)
  22. encrypted_password == encrypt(submitted_password)
  23. end
  24.  
  25. def remember_me!
  26. self.remember_token = encrypt("#{salt}--#{id}--#{Time.now.utc}")
  27. save_without_validation
  28. end
  29.  
  30. def self.authenticate(email, submitted_password)
  31. user = find_by_email(email)
  32. return nil if user.nil?
  33. return user if user.has_password?(submitted_password)
  34. end
  35.  
  36. private
  37. def encrypt_password
  38. unless password.nil?
  39. self.salt = make_salt
  40. self.encrypted_password = encrypt(password)
  41. end
  42. end
  43.  
  44. def encrypt(string)
  45. secure_hash("#{salt}#{string}")
  46. end
  47.  
  48. def make_salt
  49. secure_hash("#{Time.now.utc}#{password}")
  50. end
  51.  
  52. def secure_hash(string)
  53. Digest::SHA2.hexdigest(string)
  54. end
  55.  
  56. end
Add Comment
Please, Sign In to add comment