9e50c73ac3d49be380fc43bf9bbe70b449678216
[cs356-p2-videostore.git] / app / models / user.rb
1 require 'digest/sha1'
2
3 class User < ActiveRecord::Base
4   validates_presence_of :name
5   validates_uniqueness_of :name
6
7   validates_length_of :password, :minimum => 6
8
9   attr_accessor :password_confirmation
10   validates_confirmation_of :password
11
12   def validate
13     errors.add_to_base("Missing password") if hashed_password.blank?
14   end
15
16   def self.authenticate(name, password)
17     user = self.find_by_name(name)
18     if user
19       expected_password = encrypted_password(password, user.salt)
20       if user.hashed_password != expected_password
21         user = nil
22       end
23     end
24     user
25   end
26
27   # 'password' is a virtual attribute
28   def password
29     @password
30   end
31
32   def password=(pwd)
33     @password = pwd
34     create_new_salt
35     self.hashed_password = User.encrypted_password(self.password, self.salt)
36   end
37
38   def after_destroy
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"
43     end
44   end
45
46
47   private
48
49
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)
55   end
56
57   def create_new_salt
58     self.salt = self.object_id.to_s + rand.to_s
59   end
60
61 end