views:

27

answers:

2

I'm working with Ruby on Rails 2.3.8 and I want users to login before accesing any content from the website.

I've written the following in the application_controller

before_filter :login_required

When the app starts, I'm getting an error in the browser (not even from the application itself) saying it failed to redirect the page. And I see in the URL that says http://localhost:3000/session/new but it won't work.

Then, I've tried to place that filter in another controller, for example in dashboard_controller, which is the home page, and it worked fine (but it just works for this controller only, and I want it to filter in the entire app).

I then started thinking, and I actually think that the filter is being executed before the entry for one of these two lines are created in routes file:

map.login    '/login',    :controller => 'sessions', :action => 'new'
map.signup   '/signup',   :controller => 'users',    :action => 'new'

Any help will be appreciated.

+3  A: 

I assume you're redirecting without excluding the controller action that you don't want to redirect from. That is, your before filter is being triggered from the login page.

If so, skip the before_filter in your session controller

skip_before_filter :login_required, :only => [:login, :create]
mark
This worked! I understand the problem now. It was like a circular redirect, so the browser didn't know what to do with it. I ended up writing the following at the sessions_controller: skip_before_filter :login_required
Brian Roisentul
yep, infinite redirections, browsers don't like them :)
tybro0103
A: 

You don't want to filter every request, only the ones requiring a logged in user. So put the before_filter in each controller where it is required instead of in ApplicationController. Yes, this means there will be some duplication (Oh, the horror!), but the intent of the code will be clearer.

zetetic
I'm new to rails, but couldn't you create another base controller class that inherits from ApplicationController that has the before_filter code it in and then inherit from the new base controller for those areas of the site that require a login? You could call it SecuredController or something like that. Would that work?
someoneinomaha
Yes, you can create your own "polymorphic" controller classes. In practice I don't think this is done very often, because the actions tend to be distinct enough that there isn't a big win. But YMMV. In the OP's case, it's only one line of code being duplicated -- do you really need another class just to DRY that up?
zetetic
More info about polymorphic controllers for those interested: http://www.pathf.com/blogs/2008/07/drying-up-rails-controllers-polymorphic-and-super-controllers/
zetetic
The client wants to have logged users for all of the funcitonalities until BETA is released. That's why I wrote it in the app controller.
Brian Roisentul