/app/models/user.rb

https://github.com/mcgournj/sample_app · Ruby · 66 lines · 44 code · 19 blank · 3 comment · 6 complexity · 94e88c387a7717279f9b4509a1833337 MD5 · raw file

  1. class User < ActiveRecord::Base
  2. attr_accessor :password
  3. attr_accessible(:name, :email, :password, :password_confirmation)
  4. has_many :microposts, :dependent => :destroy
  5. email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  6. validates :name, :presence => true,
  7. :length => { :maximum => 50 }
  8. validates :email, :presence => true,
  9. :format => { :with => email_regex},
  10. :uniqueness => { :case_sensitive => false }
  11. #Automatically create the virtual attribure 'password_confirmation'.
  12. validates :password, :presence => true,
  13. :confirmation => true,
  14. :length => { :within => 6..20 }
  15. before_save :encrypt_password
  16. #return true if the user's password matches the submitted password.
  17. def has_password?(submitted_password)
  18. encrypted_password == encrypt(submitted_password)
  19. end
  20. def self.authenticate(email, submitted_password)
  21. user = find_by_email(email)
  22. return nil if user.nil?
  23. return user if user.has_password?(submitted_password)
  24. end
  25. def self.authenticate_with_salt(id, cookie_salt)
  26. user = find_by_id(id)
  27. (user && user.salt == cookie_salt) ? user : nil
  28. end
  29. def feed
  30. # This is a preliminary - filled out in chapter 12.
  31. Micropost.where("user_id = ?", id)
  32. end
  33. private
  34. def encrypt_password
  35. self.salt = make_salt if new_record?
  36. self.encrypted_password = encrypt(password)
  37. end
  38. def encrypt(string)
  39. secure_hash("#{salt}--#{string}")
  40. end
  41. def make_salt
  42. secure_hash("#{Time.now.utc}--#{password}")
  43. end
  44. def secure_hash(string)
  45. Digest::SHA2.hexdigest(string)
  46. end
  47. end