przbadu
przbadu

Reputation: 6049

Pundit policy_scope with Grape api

I am building API endpoints with Grape.

I have below scope:

class JourneyPolicy < ApplicationPolicy

  def create?
    user && user.identt_id == record
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope.where(user_id: user.id).latest
    end
  end
end

And now, I want to use this policy_scope in my grape resource, we can use policy_scope(Journey) in rails controller, but I can't make it working with grape endpoint:

class Journeys < Grape::API
  resources :journeys do
    get do
      @journeys = policy_scope(Journey)
      present @journeys, with: Entities::Journey
    end
  end
end

This is not working, and I am getting NoMethodError for policy_scope.

I would like to use that grape policy and any help would be appreciated :)

NOTE:

I have below code which is working in grape endpoint to authorize resources like:

error!("Unauthorized Access!", 401) unless JourneyPolicy.new(journey, uid).create?

Thanks

Upvotes: 2

Views: 1438

Answers (2)

Tadas Sasnauskas
Tadas Sasnauskas

Reputation: 2313

policy_scope in Rails application using Pundit comes from Pundit::Authorization module. As long as your Grape API controller has current_user method you should be able to simply include Pundit::Authorization into your base Grape API controller.

Alternatively you can also look up scopes the "manual" way:

Pundit.policy_scope!(current_user, Journey)

Upvotes: 0

przbadu
przbadu

Reputation: 6049

This might not be the best solution, but I created a helper method in grape manually named policy_scope like:

  def policy_scope(user, scope)
    policy = "#{scope}Policy::Scope".constantize
    policy.new(user, scope).resolve
  end

Now, I can call policy_scope helper from my grape resources like:

policy_scope(current_user, Journey)

and it is working for me

Thanks

Upvotes: 0

Related Questions