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)
40 raise "Can't delete last user"
48 def self.encrypted_password(password, salt)
49 # According to the RoR book, 'wibble' makes it harder to guess, which
50 # I seriously doubt given my background in crypto
51 string_to_hash = password + 'wibble' + salt
52 Digest::SHA1.hexdigest(string_to_hash)
56 self.salt = self.object_id.to_s + rand.to_s