开发者

Best way to do permissions checks in controllers.

开发者 https://www.devze.com 2023-03-29 02:59 出处:网络
I\'m trying to implement a primitive permissions system in my web app, and I want to know what you all think the best way to check permissions in my controllers. When I started writing the app, I orig

I'm trying to implement a primitive permissions system in my web app, and I want to know what you all think the best way to check permissions in my controllers. When I started writing the app, I originally thought it would be a good idea to use a before_filter, and my code ended up looking 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 looking 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 does work to some degree, but it has a number of problems. The two biggest of which are: 1) It is hard to understand what is going on because there are so many filters, and 2) I do not know how to write functional tests for this, because the errors are always picked up when testing unauthorized access. Does anyone have any suggestions as to a better way to check permissions?


Personally I think the best way is to use one of the existing authorization frameworks. It'll save you much time and headaches. Have a look at the Ruby Toolbox:

Rails Authorization

As you said, otherwise your code really gets messy. Also it is very hard to later add additional roles with additional permissions. For example if you add an administrator role, which overrides certain checks.

I've had success with declarative_authorization, but also cancan seems to a very good solution.

Here are good screencasts for both frameworks:

  • Declarative Authorization
  • Authorization with CanCan

PS: The authentication frameworks might interest you, too.

0

精彩评论

暂无评论...
验证码 换一张
取 消