views:

65

answers:

2

When user is logged in we store its user id in the session.

session[:user_id] = user.id

now on all other links in our site, we want the user redirected if session[:user_id] == nil

The way I think it would be done is that it will be done in each of the methods of controller.

def show_customers
   if session[:user_id] == nil
     redirect_to (:controller => "authentication", :action => "login")
   #code related to show_customers goes here
end

but this will need to be done in every method of every controller.

Is there a more sane Rails'y way to do this?

+3  A: 

Use a before_filter to validate the session is valid, and if you dont want to put it in every controller, put it in your application_controller (since all controllers inherit from it). You can also easily exclude/restrict the actions its called for by overriding the method in your controllers.

Browsera
Or create an Admin controller and inherit the 'protected controllers' from this controller. (And ofcourse put the before_filter and methods in the Admin Controller)
Veger