3 class User < ActiveRecord::Base
4 validates_presence_of :name
5 validates_uniqueness_of :name
7 validates_length_of :password, :minimum => 6
9 attr_accessor :password_confirmation
10 validates_confirmation_of :password
13 errors.add_to_base("Missing password") if hashed_password.blank?
16 def self.authenticate(name, password)
17 user = self.find_by_name(name)
19 expected_password = encrypted_password(password, user.salt)
20 if user.hashed_password != expected_password
27 # 'password' is a virtual attribute
35 self.hashed_password = User.encrypted_password(self.password, self.salt)
39 # We can't delete all of the managers, nor all of the users
40 managers = User.find_all_by_manager(true)
41 if managers.length.zero? or User.count.zero?
42 raise "Can't delete last manager"
50 def self.encrypted_password(password, salt)
51 # According to the RoR book, 'wibble' makes it harder to guess, which
52 # I seriously doubt given my background in crypto
53 string_to_hash = password + 'wibble' + salt
54 Digest::SHA1.hexdigest(string_to_hash)
58 self.salt = self.object_id.to_s + rand.to_s