Forum: Ruby on Rails Handling a failed login - doesn't seem to work.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
F9c02fab52a98e7f1a6f28048ae8af88?d=identicon&s=25 macfizz (Guest)
on 2007-03-18 17:09
(Received via mailing list)
Hi all,

I'm having a problem with a piece of code that should be handling a
failed login attempt.

I have created a before filter in a controller called
StoryController, that should only be applied for the new method:

before_filter :login_required, :only => new

login_required is defined in my ApplicationController:

   def login_required
     # if logged_in is true, then just exit
     return true if logged_in?
     # otherwise, store the user's request url so we can come back later
     session[:return_to] = request.request_uri
     # redirect the user back to the login page and return false
     redirect_to :controller => "/account", :action => "login" and
return false

and logged_in is also defined, as a helper method, in my

   def logged_in?
     ! @current_user.blank?
   helper_method :logged_in?

Finally, @current_user is set in the ApplicationController too, with
the help of another before filter called fetch_logged_in_user:

   before_filter :fetch_logged_in_user
   def fetch_logged_in_user
     # if there is no current user, just exit the method and return
     return if session[:user_id].blank?
     # otherwise fetch a User object with an id that is equal to the
id stored in the session container
     # and assign it to the @current _user instance variable
     @current_user = User.find_by_id(session[:user_id])

Anyway, this all seems to make a certain amount of sense to me.
@current_user is being set for every page load: a further check for
the current logged-in user is made when someone attempts to create a
new story, and if there is no logged-in user then the application
redirects to a login page. If I read things correctly, since the
filter returns false then the current controller method (new) should
just exit, so no story should get created. Sadly, that is not what
happens in practice. Instead, the story submission works regardless
of whether or not there is a logged-in user. The only difference is
that if a user has logged in then their user_id is stored in the
story table, and otherwise a NULL is stored in the relevant column.

It appears to me that the login_required filter is not being applied,
but I cannot understand why it is not. Can anyone help enlighten me?
BTW I am not a hugely experienced Rails programmer and this code is
from a book (Build your own RoR Web Applications by Patrick Lenz):
I've checked my code against the book and the code archive.

Any help much appreciated.
This topic is locked and can not be replied to.