From a25c05ecf680dfe59536e3295426b4870e4df275 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Wed, 10 Aug 2011 21:35:41 -0400 Subject: [PATCH] modifying user model to match what is wanted in 15.9, plus trashing foray into using new-style db: tasks to do awesomeness (sigh) --- cookbook/015/hodgepodge/app/models/user.rb | 30 +++++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/cookbook/015/hodgepodge/app/models/user.rb b/cookbook/015/hodgepodge/app/models/user.rb index f474fea..bae339d 100644 --- a/cookbook/015/hodgepodge/app/models/user.rb +++ b/cookbook/015/hodgepodge/app/models/user.rb @@ -1,10 +1,32 @@ +require 'sha1' + + class User < ActiveRecord::Base + attr_accessor :password + attr_protected :hashed_password validates_uniqueness_of :username - validates_confirmation_of :password, :on => :create - validates_length_of :password, :within => 5..40 + validates_confirmation_of :password, :if => lambda { |user| + user.new_record? or not user.password.blank? } + validates_length_of :password, :within => 5..40, :if => lambda { |user| + user.new_record? or not user.password.blank? } + + def self.hashed(str) + SHA1.new(str).to_s + end def self.authenticate(user_info) - find_by_username_and_password(user_info[:username], - user_info[:password]) + user = find_by_username(user_info[:username]) + if user && user.hashed_password == hashed(user_info[:password]) + return user + end + end + + private + before_save :update_password + + def update_password + if not password.blank? + self.hashed_password = self.class.hashed(password) + end end end