【问题标题】:Using Pundit for authorizing controllers使用 Pundit 授权控制器
【发布时间】:2015-07-07 02:55:49
【问题描述】:

我正在学习使用 Pundit 进行授权。但我看到它的方式是授权资源而不是页面。如果用户无权使用 pundit 访问该页面,我希望将用户重定向到未经授权的页面。

例如

class OnlyAdminCanVisitController < ApplicationController
    before_filter :admin_authenticate

停止非管理员角色用户。

另外,我想处理像以下这样的虚构场景(考虑到有 4 个角色,管理员、经理、员工、局外人。下面的设计显然很糟糕)

    class AdminManagerCanVisitController < ApplicationController
        before_filter :admin_or_manager_authenticate

    class AdminEmployeeCanVisitController < ApplicationController
        before_filter :admin_or_employee_authenticate

   class AdminOutsiderCanVisitController < ApplicationController
        before_filter :admin_or_outsider_authenticate

    class AdminManagerEmployeeCanVisitController < ApplicationController
        before_filter :admin_or_manager_employee_authenticate

我有 4 个角色,想为这些控制器编写权威策略,允许任意组合授权。

如果权威人士旨在解决这个问题,请告诉我。

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 pundit


    【解决方案1】:

    实际上页面和资源之间并没有太大的区别。因此,您可以通过从您的 application_controller.rb 抢救被拒绝的授权来解决您的问题:

    class ApplicationController < ActionController::Base
      include Pundit
    
      rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
    
      protected
    
      def admin_authenticate
        authorize current_user, :admin?
      end
    
      private
    
      def user_not_authorized(exception)
        # Redirect to whatever page you want if not authorized
      end
    end
    

    然后您需要定义您的策略。我通常在application_policy.rb (https://github.com/elabs/pundit#policies) 中创建一个admin? 方法,因此它也会在我的其他策略中传播:

    class ApplicationPolicy
      def admin?
        # Logic to ensure the user is an admin
      end
    end
    
    class UserPolicy < ApplicationPolicy
    end
    

    然后在你的其他控制器中,就像你做的那样:

    class OnlyAdminCanVisitController < ApplicationController
      before_action :admin_authenticate
    end
    

    【讨论】:

    • 谢谢..它解决了我一半的问题。另一半是如果我有 4 个角色有 4 个!授权组合,例如 4 个中有 2 个是合格的,或者 4 个中有 3 个是合格的,并且我不能对这些组合中的每一个都具有身份验证功能...如果我错过了什么,请告诉我..
    • 好的。您能否使用与角色相关的代码更新您的帖子,以便更清楚地看到问题。这将取决于您如何设计组合用户/角色谢谢
    • 策略规则适用于用户对象。您是如何在模型/数据库级别设计角色的?
    • Role 是一张表,通过 user_roles 表与 User 有 many_to_many 关系
    • 那么这很简单。在您的策略文件(UserPolicyApplicationPolicy)中,根据需要创建许多规则(如 admin?)。要在控制器中保持 DRY,您可以使用 concern 或包装实用程序函数来处理要检查的角色。我的示例基于一个角色,但同样可以应用于多个角色。
    猜你喜欢
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多