如何使用`authenticate_or_request_with_http_token`方法

时间:2016-01-24 11:59:11

标签: ruby-on-rails authentication

我在我的app_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

在我的控制器中:

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".

虽然没有登录,但我希望得到“其他东西”。响应,然后我会继续并相应地处理它。

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

您还可以附加执行此操作,或者作为max答案的一个选项。

id

在这种情况下,您无需在每个需要身份验证的请求中添加if语句。