#START:hooks
require "digest/sha1"

#START:attr
#START:validate
class User < ActiveRecord::Base

  attr_accessor :password
#END:attr

  attr_accessible :name, :password

#END:hooks
  validates_uniqueness_of :name
  validates_presence_of   :name, :password
#END:validate

  # Return the User with the given name and
  # plain-text password
#START:login
  def self.login(name, password)
    hashed_password = hash_password(password || "")
    find(:first,
         :conditions => ["name = ? and hashed_password = ?", 
                          name, hashed_password])
  end
#END:login

  # Log in if the name and password (after hashing)
  # match the database, or if the name matches
  # an entry in the database with no password
#START:login
  def try_to_login
    User.login(self.name, self.password)
  end
#END:login

#START:hooks
  def before_create
    self.hashed_password = User.hash_password(self.password)
  end

  def after_create
    @password = nil
  end
#END:hooks

#START:hooks
  private

  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end
end
#END:hooks
