使用 pundit 限制用户角色通过 url 访问

Restrict user role from accessing through url using pundit

我正在处理我的应用程序中的角色和权限。为此,我使用专家 gem。根据要求,client_admin 角色可以从下面视图文件中列出的 tested_by 列下拉列表中查看用户,但不能访问用户/索引页面。

app/views/project_issues/_form.苗条:

.padded.user-config
  - unless @project_issue.errors.empty?
    .alert.alert-danger
      = @project_issue.errors.full_messages.join('. ') + '.'

  = simple_form_for @project_issue do |f|
    = f.input :reference_number
    = f.input :tested_by,
      as: :select2,
      path: users_path(format: :json, roles: [:super_admin, :client_admin]),
      prompt: 'Select a User',
      attribute_method: :tested_by

app/policies/project_issue_policy.rb:

def new?
  user.is?(:super_admin, :client_admin)
end

app/models/project_issue.rb:

class ProjectIssue < ApplicationRecord
  belongs_to :tested_by, class_name: 'User'
end

user_policy.rb:

def index?
  user.is?(:sales_user, :sales_manager, :super_admin, :client_admin)
end

根据上面的代码,用户仍然可以通过 url 访问索引页面。我们可以添加任何范围或方法吗?请帮忙。

我写这个答案是基于我对评论的假设是正确的。

在您的策略中定义一个范围。

user_policy.rb

class UserPolicy < ApplicationPolicy
  def index?
    user.is?(:sales_user, :sales_manager, :super_admin, :client_admin)
  end

  ...

  class Scope < Scope
    def resolve
      if user.is?(:client_admin)
        User.where.not(tested_by_id: nil) # Or something like that.
      elsif user.is?(:sales_user, :sales_manager, :super_admin)
        User.where(tested_by_id: nil) # Iam still not sure on what you differentiate your users ;).
      else
        User.none
      end
    end
  end
end

您可以 "access" 您的控制器中的作用域,如下所示:

users_controller.rb

class UsersController < ApplicationController
  def index
    authorize User
    @users = policy_scope(User)
  end

  ...
end