Handling a failed login - doesn't seem to work.

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:

#code before_filter :login_required, :only => new #code

login_required is defined in my ApplicationController:

#code    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    end #code

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

#code    def logged_in?      ! @current_user.blank?    end    helper_method :logged_in? #code

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

#code    before_filter :fetch_logged_in_user    protected    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])    end #code

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.