Ограничить доступ пользователя к роли через URL с помощью pundit - PullRequest
0 голосов
/ 25 февраля 2020

Я работаю над ролями и разрешениями в моем приложении. Для этого я использую gem pundit. В соответствии с требованием роль client_admin может просматривать пользователей из раскрывающегося списка столбца test_by, как указано в приведенном ниже файле представления, но не должна иметь доступа к странице пользователей / индекса.

app / views / project_issues / _form.slim:

.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 /icies / 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. Можем ли мы добавить какую-либо область или метод? Пожалуйста, помогите.

1 Ответ

1 голос
/ 27 февраля 2020

Я пишу этот ответ, основываясь на том факте, что мои предположения на основе комментариев верны.

Определите область действия в своей политике.

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

Вы можете «получить доступ» к своей области действия в своих контроллерах следующим образом:

users_controller.rb

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

  ...
end
...