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(" ")
29 # Authenticates a user by their login name and unencrypted password. Returns the user or nil.
30 def self.authenticate(login, password)
31 u = find_by_login(login) # need to get the salt
32 u && u.authenticated?(password) ? u : nil
35 # Encrypts some data with the salt.
36 def self.encrypt(password, salt)
37 Digest::SHA1.hexdigest("--#{salt}--#{password}--")
40 # Encrypts the password with the user salt
42 self.class.encrypt(password, salt)
45 def authenticated?(password)
46 crypted_password == encrypt(password)
50 remember_token_expires_at && Time.now.utc < remember_token_expires_at
53 # These create and unset the fields required for remembering users between browser closes
55 self.remember_token_expires_at = 2.weeks.from_now.utc
56 self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
61 self.remember_token_expires_at = nil
62 self.remember_token = nil
69 return if password.blank?
70 self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
71 self.crypted_password = encrypt(password)
74 def password_required?
75 crypted_password.blank? || !password.blank?
78 # E-mail regex, moderate complexity
79 # Stolen from http://www.regular-expressions.info/email.html
80 errors.add(:email, "is not valid") unless email =~
81 /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
82 errors.add(:login, "should not begin or end with spaces") if login and login.strip!
83 errors.add(:login, "should contain only letters, numbers, and spaces") unless login =~ /^[A-Za-z0-9 ]*$/