1edfc41574e30af577d4836ca7708b1d80e478ec
[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     if User.count.zero?
40       raise "Can't delete last user"
41     end
42   end
43
44
45   private
46
47
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)
53   end
54
55   def create_new_salt
56     self.salt = self.object_id.to_s + rand.to_s
57   end
58
59 end