2016-01-24 59 views
1

我加入一些認證爲我的Rails API唯一的應用程序,像這樣在我application_controller.rb:如何使用`authenticate_or_request_with_http_token`方法

def is_admin 
    authenticate_or_request_with_http_token do |token, options| 
    if User.find_by(:auth_token => token) 
     value = true 
    else 
     value = false 
    end 
    end 
end 

而且在我的控制器:

admin = is_admin 
if admin 
    @voices = Voice.all.map do |voice| 
    voice.format 
    end 
else 
    @voices = 'Something else' 
end 

當我登錄時,一切正常預期,但是當我沒有登錄,我得到以下錯誤:Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

雖然沒有登錄,我期待着ge 「其他」的迴應,然後我會繼續處理它。

任何想法爲什麼會發生這種情況?

+0

好'價值'甚至沒有使用。你可以用'User.exists?(auth_token:token)'替換'authenticate_or_request_with_http_token'方法的主體。至於你的問題的其餘部分 - 檢查軌道日誌('tail -f logs/development.log')它會向你顯示第一次渲染的位置。 – max

+0

我已經更改'authenticate_or_request_with_http_token'內的塊,並且按照您的建議正常工作。問題是我無法在'development.log'上找到第一個渲染調用。每次被調用時,它似乎都來自我的Controller(我正在使用的那個Controller),它只發生在我使用'authenticate_or_request_with_http_token'時。假設我手動設置了「admin = false」的值而不是「admin = is_admin」,我沒有收到錯誤消息。 – WagnerMatosUK

+0

說實話,我要找的所有東西都是識別請求是否被授權的一種方法。然後相應地修改響應。你有什麼建議可以做到這一點? – WagnerMatosUK

回答

2

authenticate_or_request_with_http_token意在用於在動作之前運行的before_action過濾器。或者有明確的回報。

如果你只是想檢查一個用戶是否存在,你會使用authenticate_with_http_token這不會發送回應。

# app/helpers/authorization_helper.rb 
module AuthorizationHelper 
    # returns true/false 
    # sets @current_user if the request is authenticated 
    def authenticate! 
    return true if @current_user # avoid re-querying the DB 
    authenticate_with_http_token do |token, options| 
     @current_user = User.find_by(:auth_token => token) 
    end 
    end 

    def is_admin? 
    authenticate! 
    end 
end 

# app/controllers/api_controller.rb 
# or whatever controller you use as a base 
class ApplicationController < ActionController::API 
    include AuthorizationHelper 
end 

# in your controller 
def index 
    if is_admin? 
    @voices = Voice.all.map do |voice| 
    voice.format 
    else 
    @voices = 'Something else' 
    end 
end 
+0

這正是我所期待的。謝謝! – WagnerMatosUK