Guest User

Untitled

a guest
Mar 6th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. require 'digest/sha1'
  2.  
  3. class User < ActiveRecord::Base
  4. validates_presence_of :username
  5. validates_uniqueness_of :username
  6.  
  7. attr_accessor :password_confirmation
  8. validates_confirmation_of :password
  9.  
  10. def validate
  11. errors.add_to_base("Missing password") if hashed_password.blank?
  12. end
  13.  
  14. def self.authenticate(username, password)
  15. user = self.find_by_username(username)
  16. if user
  17. expected_password = encrypted_password(password, user.salt)
  18. if user.hashed_password != expected_password
  19. user = nil
  20. end
  21. end
  22. user
  23. end
  24.  
  25. # 'password' is a virtual attribute
  26.  
  27. def password
  28. @password
  29. end
  30.  
  31. def password=(pwd)
  32. @password = pwd
  33. return if pwd.blank?
  34. create_new_salt
  35. self.hashed_password = User.encrypted_password(self.password, self.salt)
  36. end
  37.  
  38. private
  39.  
  40. def self.encrypted_password(password, salt)
  41. string_to_hash = password + "wibble" + salt # 'wibble' makes it harder to guess
  42. Digest::SHA1.hexdigest(string_to_hash)
  43. end
  44.  
  45. def create_new_salt
  46. self.salt = self.object_id.to_s + rand.to_s
  47. end
  48. end
Add Comment
Please, Sign In to add comment