Skip to content

Instantly share code, notes, and snippets.

@Kukunin
Last active November 24, 2022 12:31
Show Gist options
  • Save Kukunin/19e4cd9061ca698d132aa9818a2f743b to your computer and use it in GitHub Desktop.
Save Kukunin/19e4cd9061ca698d132aa9818a2f743b to your computer and use it in GitHub Desktop.
Ruby Grape API authorization with Pundit example, without any extra gems
class MyGrapeAPI < Grape::API
helpers Pundit
after { verify_authorized }
helpers do
def current_user
nil # your authentication mechanism
end
end
resources :users do
desc "Retrieves information about given user"
params do
requires :id, type: String, desc: 'User ID'
end
get ':id' do
user = User.find(params[:id])
authorize user, :show?
present user, with: Entities::User
end
end
end
@glaucocustodio
Copy link

I created an authorization helper:

# api/app_helpers/authorization_kit.rb
module AppHelpers
  module AuthorizationKit
    def self.included(mod)
      mod.after { verify_authorized }
      mod.helpers Pundit
    end
  end
end

Then I just include it:

class UserAPI < Grape::API
  include AppHelpers::AuthorizationKit

  resources :users do
    # ..
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment