/app/models/user.rb

https://github.com/mikkor88/sample_app · Ruby · 64 lines · 40 code · 12 blank · 12 comment · 4 complexity · e919cbed587c5701d18499549cea2e29 MD5 · raw file

  1. # == Schema Information
  2. #
  3. # Table name: users
  4. #
  5. # id :integer not null, primary key
  6. # name :string(255)
  7. # email :string(255)
  8. # created_at :datetime
  9. # updated_at :datetime
  10. #
  11. require 'digest'
  12. class User < ActiveRecord::Base
  13. attr_accessor :password
  14. attr_accessible :name, :email, :password, :password_confirmation
  15. email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  16. validates :name, :presence => true,
  17. :length => { :maximum => 50 }
  18. validates :email, :presence => true,
  19. :format => { :with => email_regex },
  20. :uniqueness => { :case_sensitive => false }
  21. # Automatically create the virtual attribute 'password_confirmation'.
  22. validates :password, :presence => true,
  23. :confirmation => true,
  24. :length => { :within => 6..40 }
  25. before_save :encrypt_password
  26. # return true if the user's password matches the submitted password
  27. def has_password?(submitted_password)
  28. encrypted_password == encrypt(submitted_password)
  29. end
  30. def self.authenticate(email, submitted_password)
  31. user = find_by_email(email)
  32. user && user.has_password?(submitted_password) ? user : nil
  33. end
  34. def self.authenticate_with_salt(id, cookie_salt)
  35. user = find_by_id(id)
  36. (user && user.salt == cookie_salt) ? user: nil
  37. end
  38. private
  39. def encrypt_password
  40. self.salt = make_salt unless has_password?(password)
  41. self.encrypted_password = encrypt(password)
  42. end
  43. def encrypt(string)
  44. secure_hash("#{salt}--#{string}")
  45. end
  46. def make_salt
  47. secure_hash("#{Time.now.utc}--#{password}")
  48. end
  49. def secure_hash(string)
  50. Digest::SHA2.hexdigest(string)
  51. end
  52. end