Chris Farmer
Chris Farmer

Reputation: 25415

Can I use Devise controller helper methods in a Grape API?

I have a grape-based API whose only clients are browser-based users who are already authenticated to my app through Devise. I was hoping to be able to take advantage of some of the devise controller helper methods like current_user, and also to return a 403 if there is no current authenticated user. Is there a reasonable way to do this?

I naively tried just importing the controller helper methods:

class API < Grape::API
  prefix 'api'
  format :json

  include Devise::Controllers::Helpers

  get 'hello' do
    # would like to be able to use current_user here
    { result: 'hello' }
  end
end

current_user and the other helper methods remain unavailable and throw undefined local variable or method 'current_user'.

Is there a way to take advantage of the authentication that devise has already done here and use that within my grape api methods?

Upvotes: 1

Views: 729

Answers (1)

dharmesh
dharmesh

Reputation: 462

Did you try this gem? grape_devise - https://github.com/justinm/grape_devise

I had similar requirement of using devise helper methods, But i was using devise_token_auth instead of devise for api authentication. Used this Gem https://github.com/mcordell/grape_devise_token_auth for devise helpers in grape endpoints.

Please share answers if you have already found the solution.

Upvotes: -1

Related Questions