#---
# Excerpted from "Rails Recipes"
# We make no guarantees that this code is fit for any purpose. 
# Visit http://www.pragmaticprogrammer.com/titles/fr_rr for more book information.
#---

require 'digest/sha2'
class User < ActiveRecord::Base
  def password=(pass)
    salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password_salt, self.password_hash =
      salt, Digest::SHA256.hexdigest(pass + salt)
  end
    
  validates_uniqueness_of :username  
  
  def self.authenticate(username, password)
    user = User.find(:first, :conditions => ['username = ?', username])
    if user.blank? || 
      Digest::SHA256.hexdigest(password + user.password_salt) != user.password_hash
      raise "Błędna nazwa użytkownika lub hasło" 
    end
    user
  end
end

