2 class User < ActiveRecord::Base
5 # Virtual attribute for the unencrypted password
6 attr_accessor :password
7 attr_accessor :current_user
9 validates_presence_of :login, :email
10 validates_presence_of :password, :if => :password_required?
11 validates_presence_of :password_confirmation, :if => :password_required?
12 validates_length_of :password, :within => 4..40, :if => :password_required?
13 validates_confirmation_of :password, :if => :password_required?
14 validates_length_of :login, :within => 3..40
15 validates_length_of :email, :within => 3..100
16 validates_uniqueness_of :login, :email, :case_sensitive => false
17 before_save :encrypt_password
20 [ firstname, lastname].join(" ")
23 # Authenticates a user by their login name and unencrypted password. Returns the user or nil.
24 def self.authenticate(login, password)
25 u = find_by_login(login) # need to get the salt
26 u && u.authenticated?(password) ? u : nil
29 # Encrypts some data with the salt.
30 def self.encrypt(password, salt)
31 Digest::SHA1.hexdigest("--#{salt}--#{password}--")
34 # Encrypts the password with the user salt
36 self.class.encrypt(password, salt)
39 def authenticated?(password)
40 crypted_password == encrypt(password)
44 remember_token_expires_at && Time.now.utc < remember_token_expires_at
47 # These create and unset the fields required for remembering users between browser closes
49 self.remember_token_expires_at = 2.weeks.from_now.utc
50 self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
55 self.remember_token_expires_at = nil
56 self.remember_token = nil
63 return if password.blank?
64 self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
65 self.crypted_password = encrypt(password)
68 def password_required?
69 crypted_password.blank? || !password.blank?