如何在rails中验证访问令牌?

时间:2018-05-23 18:14:01

标签: ruby-on-rails

我的ApplicationController中有这段代码

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  def authenticate!
    # unless current_user

    if current_user
      current_user
    else
      render json: { 'error' => {'message' => 'Invalid access token', 'code' => 301 } }
      return
    end
  end

  def current_user
    return @current_user if @current_user.present?
    user = User.find_by(access_token: params.delete(:token))
    if user.present?
      @current_user = user
    else
      false
    end
  end
end

我用

验证用户身份
class Api::V1::RegisterController < ApplicationController
  layout nil
  skip_before_action :verify_authenticity_token
 def get_user
    authenticate!
    render json: {'hello' => 'hi'}
  end
end
它引发了Double Render的错误。 如果我的数据库中不存在用户的访问令牌并返回用户详细信息(如果存在),如何呈现无效的访问令牌消息?

EDIT1:我尝试了@ andrew21

提供的代码
class ApplicationController < ActionController::Base
  class UnauthorizedAccess < StandardError; end


    rescue_from UnauthroizedAccess, with: render_invalid_access


  protect_from_forgery with: :exception

  def authenticate!
    raise UnauthorizedAccess, 'invalid access token' unless current_user
  end

  def render_invalid_access
    render json: { 'error' => {'message' => 'Invalid access token', 'code' => 301 } }
  end
end

但是我收到了错误。

undefined local variable or method `render_invalid_access' for ApplicationController:Class

1 个答案:

答案 0 :(得分:1)

为什么不在无效访问时引发错误,然后挽救错误并呈现相应的响应。 e.g:

class ApplicationController < ActionController::Base
  class UnauthorizedAccess < StandardError; end

  protect_from_forgery with: :exception

  rescue_from UnauthorizedAccess, with: :render_invalid_access

  def authenticate!
    raise UnauthorizedAccess, 'invalid access token' unless current_user
  end

  def render_invalid_access
    render json: { 'error' => {'message' => 'Invalid access token', 'code' => 301 } }
  end
end