Forum: Ruby on Rails Protecting controllers - looking for a DRY solution

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F3dc06f587d1ff4c7366b102bfda9204?d=identicon&s=25 David Mitchell (Guest)
on 2006-02-08 06:32
(Received via mailing list)
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.
5d15c6821f3c3054c04b85471824ba7c?d=identicon&s=25 Kevin Olbrich (Guest)
on 2006-02-08 06:38
(Received via mailing list)
On Wednesday, February 08, 2006, at 4:30 PM, David Mitchell 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
3d333b0012928f3dd5a6861cb09ad683?d=identicon&s=25 Kris Leech (Guest)
on 2006-02-08 13:15
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.
This topic is locked and can not be replied to.