我加入一些认证为我的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 “其他”的回应,然后我会继续处理它。
任何想法为什么会发生这种情况?
好'价值'甚至没有使用。你可以用'User.exists?(auth_token:token)'替换'authenticate_or_request_with_http_token'方法的主体。至于你的问题的其余部分 - 检查轨道日志('tail -f logs/development.log')它会向你显示第一次渲染的位置。 – max
我已经更改'authenticate_or_request_with_http_token'内的块,并且按照您的建议正常工作。问题是我无法在'development.log'上找到第一个渲染调用。每次被调用时,它似乎都来自我的Controller(我正在使用的那个Controller),它只发生在我使用'authenticate_or_request_with_http_token'时。假设我手动设置了“admin = false”的值而不是“admin = is_admin”,我没有收到错误消息。 – WagnerMatosUK
说实话,我要找的所有东西都是识别请求是否被授权的一种方法。然后相应地修改响应。你有什么建议可以做到这一点? – WagnerMatosUK