Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{grape} authorization

I'm attempting to create a restful, json api in ruby - so I'm using grape (https://github.com/intridea/grape) inside of Rack. I'm not using Rails for this project, so cancan, sorcery, etc... don't seem to be the best options. Plus, I'd hate to mix in a bunch of imperative logic into grape's declarative DSL.

While grape has built in authentication support, I do not see anything about authorization. It seems like this would be a common enough use case that this road would have been traveled before, but after some pretty thorough digging in google and the grape codebase itself I have turned up nothing.

Has anyone implemented something like this for their project in grape? What did you use?

like image 381
Josh Avatar asked Feb 19 '13 19:02

Josh


1 Answers

This may be a little too late, but anyway. I'd recommend you use Pundit for authorization, it's deadly simple. To use it in your Grape API endpoints, you would need to include Pundit helpers:

class API < Grape::API
  format :json

  helpers Pundit
  helpers do
    def current_user
      resource_owner
    end
  end

  mount FoosAPI
end

Now in you API endpoints, you should be able to use authorize foo, action? as you would always do in Rails controllers:

class FoosAPI < Grape::API
  get ':id' do
    foo = Foo.find(params[:id])
    authorize foo, :show?
    present foo, with: FooEntity
  end
end

Hope it helps!

like image 57
fengye87 Avatar answered Oct 20 '22 13:10

fengye87