2011-08-11 01:35:41 +00:00
|
|
|
require 'sha1'
|
|
|
|
|
|
|
|
|
2011-08-10 01:38:51 +00:00
|
|
|
class User < ActiveRecord::Base
|
2011-08-11 01:35:41 +00:00
|
|
|
attr_accessor :password
|
|
|
|
attr_protected :hashed_password
|
2011-08-10 02:03:10 +00:00
|
|
|
validates_uniqueness_of :username
|
2011-08-11 01:35:41 +00:00
|
|
|
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
|
2011-08-10 01:40:23 +00:00
|
|
|
|
|
|
|
def self.authenticate(user_info)
|
2011-08-11 01:35:41 +00:00
|
|
|
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
|
2011-08-10 01:40:23 +00:00
|
|
|
end
|
2011-08-10 01:38:51 +00:00
|
|
|
end
|