require "digest/sha1"

class User < ActiveRecord::Base

  # The plain-text password, which is not stored
  # in the database
  attr_accessor :password

  # We never allow the hashed password to be
  # set from a form
  attr_accessible :name, :password

  validates_uniqueness_of :name
  validates_presence_of   :name, :password


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

  # 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
  def try_to_login
    User.login(self.name, self.password)
  end

  def before_create
    self.hashed_password = User.hash_password(self.password)
  end



  # Don't delete 'dave' from the database
  #START:before_destroy
  before_destroy :dont_destroy_dave

  def dont_destroy_dave
    raise "Can't destroy dave" if self.name == 'dave'
  end
  #END:before_destroy


  def after_create
    @password = nil
  end

  private

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

