使用 Pundit 授权控制器
Using Pundit for authorizing controllers
我正在学习使用 Pundit 进行授权。但我认为它是对资源而不是页面的授权。如果 he/she 未被授权使用 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 个角色,想为这些控制器编写允许任意组合授权的专家策略。
请告诉我专家是否旨在解决此问题。
谢谢
页面和资源实际上没有太大区别。因此,您可以通过从 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
我正在学习使用 Pundit 进行授权。但我认为它是对资源而不是页面的授权。如果 he/she 未被授权使用 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 个角色,想为这些控制器编写允许任意组合授权的专家策略。
请告诉我专家是否旨在解决此问题。
谢谢
页面和资源实际上没有太大区别。因此,您可以通过从 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