Catch authentication result from a model in a controller

Im still following the authorization recipe from the book, now all works
fine but im getting trouble in how handle the model authorization
result, if the user and pass are correct, it goes to a welcome
screen(admin.rhtml) but if wrong the model prints a message in an ugly
exception like page “usr and pass not correct”, i want to redirect the
user to the login screen(login_form.rhtml) again with a message telling
him that the auth failed, here are my code:

#model-----------------------------------------------------

require ‘digest/sha2’
class User < ActiveRecord::Base
validates_uniqueness_of :username

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

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 “user or password wrong”
end
user
end

end

#controller---------------------------------------------

class AdminController < ApplicationController
before_filter :check_authentication, :except => [:signin_form, :signin]
def index
render “admin”

end
def check_authentication
unless session[:user]
session[:intended_action] = action_name
redirect_to :action => “signin_form”
end
end
def signin_form
render “login_form”
end
def signin
session[:user] = User.authenticate(params[:username],
params[:password]).id
redirect_to :action => session[:signin_form]
end

def signout
session[:user] = nil
redirect_to :action => “signin_form”
end

…the real application’ s actions would be here.

end

that´s it, :wink:

You could do this…

def signin
begin
session[:user] = User.authenticate(params[:username],
params[:password]).id
flash[:notice] = “Logged in successfully”
redirect_to :action => session[:signin_form]
rescue
flash[:warning] = ‘Login unsuccessful’
redirect_to :action => “signin_form”
end
end