]> projects.mako.cc - selectricity-live/blob - app/models/user.rb
Correct a bunch of the testcases. Poor copy-and-paste led to description => nil where...
[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   attr_accessor :current_user
8   
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
18
19   def name
20      [ firstname, lastname].join(" ")
21   end
22
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
27   end
28
29   # Encrypts some data with the salt.
30   def self.encrypt(password, salt)
31     Digest::SHA1.hexdigest("--#{salt}--#{password}--")
32   end
33
34   # Encrypts the password with the user salt
35   def encrypt(password)
36     self.class.encrypt(password, salt)
37   end
38
39   def authenticated?(password)
40     crypted_password == encrypt(password)
41   end
42
43   def remember_token?
44     remember_token_expires_at && Time.now.utc < remember_token_expires_at 
45   end
46
47   # These create and unset the fields required for remembering users between browser closes
48   def remember_me
49     self.remember_token_expires_at = 2.weeks.from_now.utc
50     self.remember_token            = encrypt("#{email}--#{remember_token_expires_at}")
51     save(false)
52   end
53
54   def forget_me
55     self.remember_token_expires_at = nil
56     self.remember_token            = nil
57     save(false)
58   end
59
60   protected
61     # before filter 
62     def encrypt_password
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)
66     end
67     
68     def password_required?
69       crypted_password.blank? || !password.blank?
70     end
71 end

Benjamin Mako Hill || Want to submit a patch?