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. #  encrypted_password :string(255)
  11. #  salt               :string(255)
  12. #
  13.  
  14. class User < ActiveRecord::Base
  15.     attr_accessor :password
  16.     attr_accessible :name, :email, :password, :password_confirmation
  17.    
  18.     email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  19.    
  20.     #Validation rules for data entry
  21.     validates :name,    :presence   => true,
  22.                         :length     => { :maximum => 50 }
  23.                        
  24.     validates :email,   :presence   => true,
  25.                         :format     => { :with => email_regex },
  26.                         :uniqueness => { :case_sensitive => false }
  27.                        
  28.     validates :password,    :presence       => true,
  29.                             :confirmation   => true,
  30.                             :length         => { :within => 6..40 }
  31.                            
  32.     before_save :encrypt_password
  33.    
  34.     #Does the submitted password match the stored password?
  35.     def has_password?(submitted_password)
  36.         encrypted_password == encrypt(submitted_password)
  37.     end
  38.    
  39.     #Does submitted email/password match stored email/password?
  40.     def self.authenticate(email, submitted_password)
  41.         user = find_by_email(email)
  42.         return nil if user.nil?
  43.         return user if user.has_password?(submitted_password)
  44.     end
  45.    
  46.     def self.authenticate_with_salt(email, submitted_password)
  47.         user = find_by_id(id)
  48.         (user && user.salt == cookie.salt) ? user : nil
  49.     end
  50.    
  51.     private
  52.         def encrypt_password
  53.             self.salt = make_salt if new_record?
  54.             self.encrypted_password = encrypt(password)
  55.         end
  56.  
  57.         def encrypt(string)
  58.             secure_hash("#{salt}--#{string}")
  59.         end
  60.        
  61.         def make_salt
  62.             secure_hash("#{Time.now.utc}--#{password}")
  63.         end
  64.  
  65.         def secure_hash(string)
  66.             Digest::SHA2.hexdigest(string)
  67.         end
  68. end
  69.  
  70.