PageRenderTime 46ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/app/models/user.rb

https://github.com/jpowell1218/rails_3_sample_app
Ruby | 66 lines | 41 code | 15 blank | 10 comment | 5 complexity | e8e8ed23397c33b7af62bc1778dd4591 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. require 'digest'
  11. class User < ActiveRecord::Base
  12. attr_accessor :password
  13. attr_accessible :name, :email, :password, :password_confirmation
  14. email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  15. validates :name, :presence => true,
  16. :length => { :maximum => 50 }
  17. validates :email, :presence => true,
  18. :format => { :with => email_regex },
  19. :uniqueness => { :case_sensitive => false }
  20. # Automatically create the virtual attribute 'password_confirmation'.
  21. validates :password, :presence => true,
  22. :confirmation => true,
  23. :length => { :within => 6..40 }
  24. before_save :encrypt_password
  25. def has_password?(submitted_password)
  26. encrypted_password == encrypt(submitted_password)
  27. end
  28. def self.authenticate(email, submitted_password)
  29. user = find_by_email(email)
  30. return nil if user.nil?
  31. return user if user.has_password?(submitted_password)
  32. end
  33. def self.authenticate_with_salt(id, cookie_salt)
  34. user = find_by_id(id)
  35. (user && user.salt == cookie_salt) ? user : nil
  36. end
  37. private
  38. def encrypt_password
  39. self.salt = make_salt unless has_password?(password)
  40. self.encrypted_password = encrypt(password)
  41. end
  42. def encrypt(string)
  43. secure_hash("#{salt}--#{string}")
  44. end
  45. def make_salt
  46. secure_hash("#{Time.now.utc}--#{password}")
  47. end
  48. def secure_hash(string)
  49. Digest::SHA2.hexdigest(string)
  50. end
  51. end