如何使用authenticate_or_request_with_http_token方法

Wag*_*sUK 4 authentication ruby-on-rails

我在我的仅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
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

admin = is_admin
if admin
  @voices = Voice.all.map do |voice| 
    voice.format
  end
else
  @voices = 'Something else'
end
Run Code Online (Sandbox Code Playgroud)

当我登录时,一切都按预期工作,但是,当我未登录时,出现以下错误: 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".

在未登录的同时,我希望得到“其他”响应,然后我将继续进行相应处理。

任何想法为什么会这样?

max*_*max 6

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
Run Code Online (Sandbox Code Playgroud)