gpt4 book ai didi

ruby-on-rails - 如何使用 `authenticate_or_request_with_http_token`方法

转载 作者:行者123 更新时间:2023-12-04 22:15:28 25 4
gpt4 key购买 nike

我在我的 application_controller.rb 中像这样在我的 Rails API 应用程序中添加了一些身份验证:

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

在我的 Controller 中:
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".
虽然没有登录,但我希望得到“其他”的回应,然后我会继续并相应地处理它。

任何想法为什么会发生这种情况?

最佳答案

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

关于ruby-on-rails - 如何使用 `authenticate_or_request_with_http_token`方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34975478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com