2011-08-26 59 views
4

我正在使用Grape gem为我的应用程序创建一个API。一切工作都很好,直到我将http基本身份验证添加到内置于Grape API中的api中。无法访问http_basic块内的任何Grape :: API方法/对象

下面是代码,我有:

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 

看来我无法访问http_basic块内的任何方法或对象包括请求,ENV,佣工方法中任何东西,甚至没有错误! 。

看代码,这是没有意义的。

有没有人遇到过这个?有没有人有任何使用Grape API和http基本认证的例子?网络上的例子并不是真实世界的例子。

回答

6

葡萄存储您http_basic块在其设置的哈希PROC。在Grape::APIbuild_endpoint方法组装所有这样的:

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

你的助手不可用在这一点上。 (见https://github.com/intridea/grape/blob/master/lib/grape/api.rb#L258

你可以尝试实现这个没有帮手,在您的User模型中使用一个类的方法是这样的:

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

如果User也无法使用,通过实现自己的基本身份验证使用Rack::Builder就像上面一行一样。

+1

但是,你如何获得认证用户(又名'current_user')? –

+0

医生什么问题也是我的问题。 。 。我想设置一个变量可访问来自http_basic块的API调用,但是这听起来可能不起作用,因为http_basic块最终会在Grape的API类之外创建它。 – brokenbeatnik