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

I am using the Grape gem to create an API for my application. Everything worked fine until I added http authentication to my api, which is built into Appe Grape.

Here is the code 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 can’t access any methods or objects inside the http_basic block, including the request, env, anything in the helper methods and even an error!

Having a look at the code, this makes no sense.

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

+4
source share
1 answer

Grape stores your http_basic block as proc in its hash setting. The build_endpoint method in Grape::API collects all this:

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

Your helpers are currently unavailable. (See https://github.com/intridea/grape/blob/master/lib/grape/api.rb#L258 )

You can try to implement this without helpers using the class method in your User model as follows:

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

If User also unavailable, use your own base auth using Rack::Builder , as in the line above.

+6
source

Source: https://habr.com/ru/post/1369085/


All Articles