The best way to do permissions checks in controllers.

I am trying to implement a primitive permission system in my web application and I want to know what you all think is the best way to check permissions in my controllers. When I started writing the application, I initially thought it would be nice to use before_filter, and my code looked something like this:

before_filter :authenticate, :only => [:new, :create, :show, :edit, :update, :destroy, :delete] before_filter :check_league_existence before_filter :check_league_relation_existence, :except => [:new, :create, :index] before_filter :check_ownership, :only => [:delete, :destroy] before_filter :check_user_joinability, :only => [:new, :create] before_filter :require_moderator, :only => [:edit, :update] 

With my filters it looks something like this:

 def check_league_relation_existence raise ActiveRecord::RecordNotFound.new('Not Found') unless current_league_relation && current_league.league_relations.include?(current_league_relation) end def check_ownership raise ActionController::RoutingError.new('You do not own this league relation. Permission Denied.') unless current_league_relation.user == current_user || current_user_league_relation.moderator? end 

Now this system works to some extent, but it has a number of problems. Two of them: 1) It is difficult to understand what is happening because there are so many filters, and 2) I do not know how to write functional tests for this, because errors are always selected when testing unauthorized access. Does anyone have any suggestions on a better way to check permissions?

+4
source share
1 answer

Personally, I think the best way is to use one of the existing authorization systems. This will save you a lot of time and headaches. Take a look at the Ruby Toolbox:

Rails Authorization

As you said, otherwise your code really becomes messy. It is also very difficult to add additional roles with additional permissions later. For example, if you add an administrator role that overrides certain checks.

I have had success with declarative_authorization , but also cancan seems like a very good solution.

Here are some good screencasts for both frameworks:

PS: authentication frameworks may interest you.

+7
source

All Articles