Guest User

Untitled

a guest
Mar 5th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2. # make sure we have the required fields when saving
  3. validates_presence_of :username, :password, :password_confirmation
  4. validates_uniqueness_of :password, :minimum => 5, :message => "Passwords should be at least 5 characters"
  5. attr_accessor :password_confirmation
  6. validates_confirmation_of :password
  7.  
  8. # lookup the user and check the password
  9. # set the user to nil of the password doesn't match
  10. def self(username, password)
  11. user = User.find(:first, :conditions => ['username = ?', username])
  12. if user
  13. expected_password = encrypt_password(password, user.password_salt)
  14. if user.password_hash != expected_password
  15. user = nil
  16. end
  17. end
  18. end
  19.  
  20. # normally for virtual attributes we just need to declare: attr_accessor: [fieldname]
  21. # to create the getter and setter since password has extra logic in the setter, we have
  22. # to create them by hand.
  23.  
  24. #password getter
  25. def password
  26. @password
  27. end
  28.  
  29. #password setter
  30. def password=(pwd)
  31. @password = pwd
  32. create_new_salt self.password_hash = User.encrypted_password(self.password, self.password_salt)
  33. end
  34.  
  35. # make sure weh have at least one user in the database
  36. def safe_delete
  37. transaction do
  38. destroy if User.count.zero?
  39. raise "Can't delete last user"
  40. end
  41. end
  42. end
  43.  
  44. private
  45. def create_new_salt
  46. self.password_salt = [Array.new(6){rand(256).chr}.join].pack(ÓmÓ).chomp
  47. end
  48.  
  49. def self.encrypted_password(password, salt)
  50. string_to_hash = password + salt
  51. Digest::SHA1.hexdigest(string_to_hash)
  52. end
  53. end
Add Comment
Please, Sign In to add comment