Forum: Ruby on Rails Catch authentication result from a model in a controller

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ca2e3e3f873fed864da130efb194e199?d=identicon&s=25 Ana Barrueta (Guest)
on 2006-04-21 20:10
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, ;)
C31c7255fa4488dfc5d766403b497a36?d=identicon&s=25 Jim Morris (wolfmanjm)
on 2006-04-22 23:09
(Received via mailing list)
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
This topic is locked and can not be replied to.