ruby-on-rails – 在控制器中执行权限检查的最佳方法.
发布时间:2020-12-17 02:42:03 所属栏目:百科 来源:网络整理
导读:我正在尝试在我的网络应用程序中实现原始权限系统,我想知道你们都认为检查控制器权限的最佳方法.当我开始编写应用程序时,我原本以为使用before_filter是个好主意,我的代码最终看起来像这样: before_filter :authenticate,:only = [:new,:create,:show,:edit
我正在尝试在我的网络应用程序中实现原始权限系统,我想知道你们都认为检查控制器权限的最佳方法.当我开始编写应用程序时,我原本以为使用before_filter是个好主意,我的代码最终看起来像这样:
before_filter :authenticate,:only => [:new,:create,:show,:edit,:update,:destroy,:delete] before_filter :check_league_existence before_filter :check_league_relation_existence,:except => [:new,:index] before_filter :check_ownership,:only => [:delete,:destroy] before_filter :check_user_joinability,:create] before_filter :require_moderator,:only => [:edit,:update] 我的过滤器看起来像这样: 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)我不知道如何为此编写功能测试,因为在测试未授权时总是会收到错误访问.有没有人有更好的方法来检查权限? 解决方法
我个人认为最好的方法是使用现有的授权框架之一.它会为你节省很多时间和头痛.看看Ruby工具箱:
Rails Authorization 如你所说,否则你的代码真的变得混乱.此外,以后添加具有其他权限的其他角色非常困难.例如,如果添加管理员角色,则会覆盖某些检查. 我在declarative_authorization上取得了成功,但cancan似乎也是一个非常好的解决方案. 以下是两个框架的良好截屏视图: > Declarative Authorization PS:authentication frameworks也可能对你感兴趣. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |