Как аутентифицировать токен доступа в рельсах? - PullRequest
0 голосов
/ 23 мая 2018

У меня есть этот код в моем 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.Как я могу отобразить сообщение о недействительном токене доступа, если токен доступа пользователя отсутствует в моей базе данных, и вернуть данные пользователя, если они есть?* но я получаю ошибку.

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

1 Ответ

0 голосов
/ 23 мая 2018

почему бы вам не вызвать ошибку при недопустимом доступе, а затем спасти ошибку и вывести соответствующий ответ.например:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...