Rails - Pundit - how to check for current_admin_user?

送分小仙女□ 提交于 2021-01-29 06:36:56

问题


I am using Pundit for authorization for my User model.

My goal is to extend this to use my AdminUser model, specifically for my admin namespace.

By default, Pundit checks for a "user" or "current_user". How can I change this to check for a "admin_user" or "current_admin_user", based on Devise?

policies/admin/admin_policy.rb (Closed system, currently looks for User instead of AdminUser)

class Admin::AdminPolicy
  attr_reader :user, :record

  def initialize(user, record)
    # Must be logged in
    raise Pundit::NotAuthorizedError, "You must be logged in to perform this action" unless user
    @user = user
    @record = record
  end

  def index?
    false
  end

  def show?
    false
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      raise Pundit::NotAuthorizedError, "You must be logged in to perform this action" unless user
      @user = user
      @scope = scope
    end

    def resolve
      scope.all
    end
  end
end

policies/admin/home_policy.rb (Example sub-policy of the Admin namespace)

class Admin::HomePolicy < Admin::AdminPolicy

  def index?
    user.present?
  end

end

回答1:


I think you need to define the method pundit_user on your controllers to customize it https://github.com/varvet/pundit#customize-pundit-user

def pundit_user
  current_admin_user
end


来源:https://stackoverflow.com/questions/52013736/rails-pundit-how-to-check-for-current-admin-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!