2016-01-24 65 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