user.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. #---
  10. # Excerpted from "Agile Web Development with Rails, 4rd Ed.",
  11. # published by The Pragmatic Bookshelf.
  12. # Copyrights apply to this code. It may not be used to create training material,
  13. # courses, books, articles, and the like. Contact us if you are in doubt.
  14. # We make no guarantees that this code is fit for any purpose.
  15. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  16. #---
  17. require 'digest/sha2'
  18. class User < ActiveRecord::Base
  19. validates :name, :presence => true, :uniqueness => true
  20. validates :password, :confirmation => true
  21. attr_accessor :password_confirmation
  22. attr_reader :password
  23. validate :password_must_be_present
  24. def User.authenticate(name, password)
  25. if user = find_by_name(name)
  26. if user.hashed_password == encrypt_password(password, user.salt)
  27. user
  28. end
  29. end
  30. end
  31. def User.encrypt_password(password, salt)
  32. Digest::SHA2.hexdigest(password + "wibble" + salt)
  33. end
  34. # 'password' is a virtual attribute
  35. def password=(password)
  36. @password = password
  37. if password.present?
  38. generate_salt
  39. self.hashed_password = self.class.encrypt_password(password, salt)
  40. end
  41. end
  42. after_destroy :ensure_an_admin_remains
  43. def ensure_an_admin_remains
  44. if User.count.zero?
  45. raise "Can't delete last user"
  46. end
  47. end
  48. private
  49. def password_must_be_present
  50. errors.add(:password, "Missing password") unless hashed_password.present?
  51. end
  52. def generate_salt
  53. self.salt = self.object_id.to_s + rand.to_s
  54. end
  55. end