在控制器中进行权限检查的最佳方法. [英] Best way to do permissions checks in controllers.

查看:30
本文介绍了在控制器中进行权限检查的最佳方法.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 Web 应用程序中实现一个原始权限系统,我想知道你们都认为在我的控制器中检查权限的最佳方法是什么.当我开始编写应用程序时,我原本认为使用 before_filter 是个好主意,结果我的代码看起来像这样:

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

现在这个系统在某种程度上确实有效,但它有很多问题.其中最大的两个是:1)很难理解发生了什么,因为有这么多过滤器,2)我不知道如何为此编写功能测试,因为在未经授权的测试时总是会发现错误使用权.有人对检查权限的更好方法有什么建议吗?

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?

推荐答案

我个人认为最好的方法是使用现有的授权框架之一.它会为您节省很多时间和麻烦.看看 Ruby 工具箱:

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 授权

正如你所说,否则你的代码真的会变得一团糟.此外,以后添加具有额外权限的额外角色也非常困难.例如,如果您添加管理员角色,该角色会覆盖某些检查.

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.

我在 declarative_authorization 方面取得了成功,但 cancan 似乎也是一个很好的解决方案.

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

以下是两个框架的优秀截屏视频:

Here are good screencasts for both frameworks:

PS:身份验证框架您也可能会感兴趣.

PS: The authentication frameworks might interest you, too.

这篇关于在控制器中进行权限检查的最佳方法.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆