1 # Selectricity: Voting Machinery for the Masses
2 # Copyright (C) 2007, 2008 Benjamin Mako Hill <mako@atdot.cc>
3 # Copyright (C) 2007 Massachusetts Institute of Technology
5 # This program is free software. Please see the COPYING file for
9 class User < ActiveRecord::Base
12 # Virtual attribute for the unencrypted password
13 attr_accessor :password
14 attr_accessor :current_user
16 validates_presence_of :email
17 validates_presence_of :password, :if => :password_required?
18 validates_presence_of :password_confirmation, :if => :password_required?
19 validates_length_of :password, :within => 4..40, :if => :password_required?
20 validates_confirmation_of :password, :if => :password_required?
21 validates_length_of :login, :within => 3..40
22 validates_uniqueness_of :login, :email, :case_sensitive => false
23 before_save :encrypt_password
26 [ firstname, lastname].join(" ")
30 self[:email] = new_email
33 # Authenticates a user by their login name and unencrypted password. Returns the user or nil.
34 def self.authenticate(login, password)
35 u = find_by_login(login) # need to get the salt
36 u && u.authenticated?(password) ? u : nil
39 # Encrypts some data with the salt.
40 def self.encrypt(password, salt)
41 Digest::SHA1.hexdigest("--#{salt}--#{password}--")
44 # Encrypts the password with the user salt
46 self.class.encrypt(password, salt)
49 def authenticated?(password)
50 crypted_password == encrypt(password)
54 remember_token_expires_at && Time.now.utc < remember_token_expires_at
57 # These create and unset the fields required for remembering users between browser closes
59 self.remember_token_expires_at = 2.weeks.from_now.utc
60 self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
65 self.remember_token_expires_at = nil
66 self.remember_token = nil
73 return if password.blank?
74 self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
75 self.crypted_password = encrypt(password)
78 def password_required?
79 crypted_password.blank? || !password.blank?
82 # E-mail regex, moderate complexity
83 # Stolen from http://www.regular-expressions.info/email.html
84 errors.add(:email, "is not valid") unless email =~
85 /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
86 errors.add(:login, "should not begin or end with spaces") if login and login.strip!
87 errors.add(:login, "should contain only letters, numbers, and spaces") unless login =~ /^[A-Za-z0-9 ]*$/