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 :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_uniqueness_of :login, :email, :case_sensitive => false
16 before_save :encrypt_password
19 [ firstname, lastname].join(" ")
22 # Authenticates a user by their login name and unencrypted password. Returns the user or nil.
23 def self.authenticate(login, password)
24 u = find_by_login(login) # need to get the salt
25 u && u.authenticated?(password) ? u : nil
28 # Encrypts some data with the salt.
29 def self.encrypt(password, salt)
30 Digest::SHA1.hexdigest("--#{salt}--#{password}--")
33 # Encrypts the password with the user salt
35 self.class.encrypt(password, salt)
38 def authenticated?(password)
39 crypted_password == encrypt(password)
43 remember_token_expires_at && Time.now.utc < remember_token_expires_at
46 # These create and unset the fields required for remembering users between browser closes
48 self.remember_token_expires_at = 2.weeks.from_now.utc
49 self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
54 self.remember_token_expires_at = nil
55 self.remember_token = nil
62 return if password.blank?
63 self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
64 self.crypted_password = encrypt(password)
67 def password_required?
68 crypted_password.blank? || !password.blank?
71 # E-mail regex, moderate complexity
72 # Stolen from http://www.regular-expressions.info/email.html
73 errors.add(:email, "is not valid") unless email =~
74 /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
75 errors.add(:login, "should not begin or end with spaces") if login and login.strip!
76 errors.add(:login, "should contain only letters, numbers, and spaces") unless login =~ /^[A-Za-z0-9 ]*$/