2011-08-26 57 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