我在Rails API中添加了一些身份验证,类似于我的application_controller.rb中的应用程序:
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".
虽然没有登录,但我希望得到‘其他东西’的回应,然后我会继续并相应地处理它。
知道为什么会发生这种事吗?
发布于 2016-01-24 22:40:10
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
发布于 2019-04-03 07:56:34
此外,您还可以这样做,或者更确切地说,是max的答案的一个选项。
# app/controllers/application_controller.rb
class ApplicationController
def authorization!
authenticate_with_http_token do |token, options|
@current_user = User.find_by(:auth_token => token)
end
unless @user.present?
# You could return anything you want if the response if it's unauthorized. in this
# case I'll just return a json object
return render json: {
status: 300,
message: "Unauthorized access in the API"
}, status: 401
end
end
end
# in your controller just add a before_action method
before_action :authorization
def index
@voices = Voice.all.map do |voice|
voice.format
end
在这种情况下,您不需要在每个需要身份验证的请求中添加一个if语句。
https://stackoverflow.com/questions/34975478
复制相似问题