0

I am working on roles and permissions in my application. For this I am using pundit gem. As per the requirement the client_admin role can view users from tested_by column drop down as listed in the below view file but should not be able to access users/ index page.

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/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

As per the above code the users can still be accessed to index page via url. Can we add any scope or method? Please help.

user3189916
  • 758
  • 1
  • 7
  • 26
  • Please provide some more Information. Did you authorize the index action in your users controller? Is yes, maybe there is something wrong with your tole check for users. Thank you. – Alexander Rühle Feb 26 '20 at 08:58
  • Yes @AlexanderRühle, `authorize User` is added in users_controller index action. – user3189916 Feb 26 '20 at 13:52
  • Can we add any scope for the policy? – user3189916 Feb 26 '20 at 14:11
  • I still don't get your Problem, do you want to restrict the complete access to the unsers index action or do you want to filter the presented users list based on your roles? I'll write an Answer for the later case. Maybe it helps. – Alexander Rühle Feb 27 '20 at 09:43

1 Answers1

1

I am writing this answer based on the fact that my assumption from the comments is correct.

Define a scope in your policy.

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

You can "access" your scope in your controllers like so:

users_controller.rb

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

  ...
end