Skip to content

Rendering Json Results in JWT::DecodeError #162

@louisscruz

Description

@louisscruz

Steps to reproduce

Perform any request that should render JSON in my controllers.

Expected behavior

The controllers should render JSON.

Actual behavior

For instance, when I make a call to create a session through my sessions_controller, I get the following error:

JWT::DecodeError (Nil JSON web token):

lib/json_web_token.rb:11:in `decode'
app/helpers/sessions_helper.rb:15:in `current_user'
app/controllers/api/sessions_controller.rb:13:in `create'

For some reason the current_user method of my sessions_helper is being called, and I have no idea why.

sessions_helper.rb

require 'json_web_token'

module SessionsHelper
  def create_session(user)
    session[:user_id] = user.id
  end

  def current_user
    puts caller
    auth_token = request.headers["Authorization"]
    if auth_token
      auth_token = auth_token.split(" ").last
      begin
        decoded_token = JsonWebToken.decode auth_token
      rescue JWT::ExpiredSignature
        return
      end
      @current_user ||= User.find_by(auth_token: auth_token)
    end
  end

  def log_out(user)
    logged_in? ? user.generate_authentication_token! : user.destroy_token!
    auth_token = user.auth_token
    user.update_attribute(:auth_token, auth_token)
  end

  def logged_in?
    current_user.present?
  end

  def authenticate_with_token!
    render json: { errors: "Not authenticated" }, status: :unauthorized unless logged_in?
  end

  def log_in(user)
    create_session(user)
    user.generate_authentication_token!
    user.update_attribute(:auth_token, user.auth_token)
  end

  def authenticate_as_self_or_admin!
    render json: { errors: "Not authorized" }, status: :unauthorized unless is_self? || is_admin?
  end

  def is_self?
    user = User.find(params[:id])
    auth_token = request.headers["Authorization"]
    auth_token = auth_token.split(" ").last if auth_token
    user.auth_token != auth_token
  end

  def is_admin?
    if logged_in? && current_user.authenticate(params[:password])
      current_user.admin
    end
  end
end

The output of the p caller makes it appear that the very act of calling render json: user is making a call to my method current_user. The same error occurs with rendering JSON in the users_controller.rb.

System configuration

Rails version: Originally on 5.0.0 (beta 2), Updated to 5.1.0 (alpha) in attempt to fix this issue

Ruby version: 2.2.3p173

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions