]> projects.mako.cc - selectricity-live/blob - app/models/user.rb
removed save line that was causing the new elections to fail
[selectricity-live] / app / models / user.rb
1 require 'digest/sha1'
2 class User < ActiveRecord::Base
3   has_many :elections
4
5   # Virtual attribute for the unencrypted password
6   attr_accessor :password
7
8   validates_presence_of     :login, :email
9   validates_presence_of     :password,                   :if => :password_required?
10   validates_presence_of     :password_confirmation,      :if => :password_required?
11   validates_length_of       :password, :within => 4..40, :if => :password_required?
12   validates_confirmation_of :password,                   :if => :password_required?
13   validates_length_of       :login,    :within => 3..40
14   validates_length_of       :email,    :within => 3..100
15   validates_uniqueness_of   :login, :email, :case_sensitive => false
16   before_save :encrypt_password
17
18   def name
19      [ firstname, lastname].join(" ")
20   end
21
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
26   end
27
28   # Encrypts some data with the salt.
29   def self.encrypt(password, salt)
30     Digest::SHA1.hexdigest("--#{salt}--#{password}--")
31   end
32
33   # Encrypts the password with the user salt
34   def encrypt(password)
35     self.class.encrypt(password, salt)
36   end
37
38   def authenticated?(password)
39     crypted_password == encrypt(password)
40   end
41
42   def remember_token?
43     remember_token_expires_at && Time.now.utc < remember_token_expires_at 
44   end
45
46   # These create and unset the fields required for remembering users between browser closes
47   def remember_me
48     self.remember_token_expires_at = 2.weeks.from_now.utc
49     self.remember_token            = encrypt("#{email}--#{remember_token_expires_at}")
50     save(false)
51   end
52
53   def forget_me
54     self.remember_token_expires_at = nil
55     self.remember_token            = nil
56     save(false)
57   end
58
59   protected
60     # before filter 
61     def encrypt_password
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)
65     end
66     
67     def password_required?
68       crypted_password.blank? || !password.blank?
69     end
70 end

Benjamin Mako Hill || Want to submit a patch?