2

How do I can retrieve all user policies and scopes using Pundit Gem? I need to return a json object with all user policies to check permissions in Frontend javascript templates.

Using CanCanCan gem, I can do something like this:

class Ability
  include CanCan::Ability

  # ....

  def to_list
    rules.map do |rule|
      object = { actions: rule.actions, subject: rule.subjects.map{ |s| s.is_a?(Symbol) ? s : s.name } }
      object[:conditions] = rule.conditions unless rule.conditions.blank?
      object[:inverted] = true unless rule.base_behavior
      object
    end
  end
end

Is possible to do the same with Pundit?

plcosta
  • 345
  • 4
  • 9

1 Answers1

6

I have the same requirement, I got the following code working per investigation:

def index
    classes = [Admin, BusNumber, Ticket, :ticket_statistics]     

    permissions = { }                             

    classes.each do |clazz|                       
        policy =  Pundit.policy(current_admin, clazz)      
        policy.public_methods(false).sort.each do |m|      
            result = policy.send m                    
            permissions["#{clazz}.#{m}"] = result     
        end
    end 

    render json: permissions
end  

the current_admin is the method to get the current login user, the code gives the following result

{
    "Admin.create?": true,
    "Admin.disable?": true,
    "Admin.enable?": true,
    "Admin.index?": true,
    "Admin.show?": true,
    "Admin.update?": true,
    "BusNumber.create?": true,
    "BusNumber.destroy?": true,
    "BusNumber.index?": true,
    "BusNumber.update?": true,
    "Ticket.index?": true,
    "Ticket.refund_by_admin?": true,
    "Ticket.show?": true,
    "ticket_statistics.overall?": true
}
James Wang
  • 144
  • 5