Guest User

Untitled

a guest
Feb 19th, 2018
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. # Schema as of June 12, 2006 15:45 (schema version 7)
  2. #
  3. # Table name: users
  4. #
  5. # id :integer(11) not null, primary key
  6. # name :string(255)
  7. # hashed_password :string(255)
  8. # salt :string(255)
  9. #
  10. require 'digest/sha1'
  11. class User < ActiveRecord::Base
  12. validates_presence_of :name,
  13. :password,
  14. :password_confirmation
  15. validates_uniqueness_of :name
  16. validates_length_of :password,
  17. :minimum => 5,
  18. :message => "should be at least 5 characters long"
  19. attr_accessor :password_confirmation
  20. validates_confirmation_of :password
  21. # ...
  22. def self.authenticate(name, password)
  23. user = self.find_by_name(name)
  24. if user
  25. expected_password = encrypted_password(password, user.salt)
  26. if user.hashed_password != expected_password
  27. user = nil
  28. end
  29. end
  30. user
  31. end
  32. # 'password' is a virtual attribute
  33. def password
  34. @password
  35. end
  36. def password=(pwd)
  37. @password = pwd
  38. create_new_salt
  39. self.hashed_password = User.encrypted_password(self.password, self.salt)
  40. end
  41. def safe_delete
  42. transaction do
  43. destroy
  44. if User.count.zero?
  45. raise "Can't delete last user"
  46. end
  47. end
  48. end
  49. private
  50. def create_new_salt
  51. self.salt = self.object_id.to_s + rand.to_s
  52. end
  53. def self.encrypted_password(password, salt)
  54. string_to_hash = password + "wibble" + salt
  55. Digest::SHA1.hexdigest(string_to_hash)
  56. end
  57. end
Add Comment
Please, Sign In to add comment