Protecting controllers - looking for a DRY solution

Hello everyone,

I’ve got several different user roles (i.e. admin, user, guest, …)
and have set up a bunch of controllers for each user role.

I’m trying to set up some sort of validation that the user accessing
e.g. the admin/subjects controller has the ‘admin’ role. The brute
force way to do this would be something like:

  • for each controller, put in

before_filter :validate_user
def validate_user
if session[:user].role != ‘admin’
flash[:notice] = “You don’t have permission to access this”
redirect_to :controller => session[:user].role, :action => ‘home’
end
end

However, I don’t want to put this code in almost verbatim into about
35 controllers if I can avoid it.

Is there some way I can put this logic in one spot and then call it
from all controllers? In particular, I need to be able to determine
the role the user should have is ‘admin’ when he’s accessing the e.g.
‘admin/subjects’ or ‘admin/content’ controllers - the required role
will ALWAYS be prefix of the controller.

Thanks in advance

Dave M.

On Wednesday, February 08, 2006, at 4:30 PM, David M. wrote:

Hello everyone,

I’ve got several different user roles (i.e. admin, user, guest, …)
and have set up a bunch of controllers for each user role.

I’m trying to set up some sort of validation that the user accessing
e.g. the admin/subjects controller has the ‘admin’ role. The brute
force way to do this would be something like:

  • for each controller, put in

Take a look at the user_engine plugin. It does exactly what you are
looking for.

_Kevin

Here is an aprox/speudo way of doing it:

You need to create a table called something like permissions with all
the controller/action combo’s in your application in it and link it to
the roles - ie. role has_many permissions.

Load the permissions for the user in to the session at login

Put a method called autherise in application controller that is called
from a before_filter in the controllers you want to protect.

In the autherise method use (I think) request.controller and
request.action which contain the current controller and action to do a
find on the permissions in the session.

Kris.