1

I'm using Pundit in some Rails API controllers and wonder how it will work/escaped outside of it, for example in Rake tasks. I haven't played around with it yet. Can we skip the authorization in a Rake task? In this case, it will be run as ActiveJob with Sidekiq and there will be no User instance in the context. Any ideas?

belgoros
  • 3,590
  • 7
  • 38
  • 76

2 Answers2

0

Using belgoro's example policy above, it is possible to create an instance of the policy and check against it. E.g.:

if ShopPolicy.new(current_user, shop).update?
  shop.update!(...)
end

The trick here is knowing what user it is running under. Unless you prompt for it, there probably is know way of knowing who is running the rake task.

Joel B
  • 801
  • 1
  • 11
  • 30
-1

I've just tried it out. It seemed to work as usual. Here is my simple ShopPolicy:

class ShopPolicy < ApplicationPolicy
  def update?
    user.admin?
  end
end

I have a created a simple rake task as follows:

namespace :batch do
  desc 'Update a shop without Pundit'
  task update_shop_fax: :environment do
    shop = Shop.find_by(identifier: 12345)
    shop.update!(fax: '0800-123456789')
    puts 'Done'
  end
end

Then I run it as rails batch:update_shop_fax. And it worked, the fax value was updated.

belgoros
  • 3,590
  • 7
  • 38
  • 76