开发者

Unable to access any Grape::API methods / objects inside http_basic block

I am using the Grape gem to create an API for my application. Everything is working good until I added http basic authentication to my api which is built into the Grape api.

Here is the code that I have:

require 'grape'

module MyApp
  class API < Grape::API
    prefix 'api'
    version 'v1'

    helpers do
      def current_user
        @current_user ||= User.authenticate(env)
      end

      def authenticate!
        error!('401 Unauthorized', 401) unless current_user
      end
    end

    resources :projects do

      http_basic do |u,p|
        authenticate!                    #=> Results in undefined method `authenticate!' for MyApp::API:Class (NoMethodError)
开发者_如何转开发        error! "401 Unauthorized", 401
        !current_user.nil?
      end
    end
  end
end

It seems that I cannot access any methods or objects inside the http_basic block including the request, env, anything within the helpers methods, and not even error!.

Looking at the code, this does not make sense.

Has anyone come across this before? Does anyone have any examples of using Grape API with http basic authentication? The examples on the web are not real world examples.


Grape stores your http_basic block as a proc in its settings hash. The build_endpoint method in Grape::API assembles all that to this:

Rack::Builder.new.use Rack::Auth::Basic, "API Authorization", &your_block

Your helpers are not available at this point. (See https://github.com/intridea/grape/blob/master/lib/grape/api.rb#L258)

You could try to implement this without helpers, by using a class method in your User model like this:

http_basic do |user, password|
  User.authenticate(user, password)
end

If User also isn't available, implement your own basic auth by using Rack::Builder like in the line above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜