Why is current_user called on render in controller?
Asked Answered
P

1

6

I'm getting the following error when trying access the log in method of my sessions controller:

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:11:in `create'

If I comment out my render json: user in my controller response, all is good, except I need to respond with the user...Why on earth is the current_user method called on through line 11 of the sessions_controller.rb. Here's the relevant code:

lib/json_web_token.rb

require 'jwt'

class JsonWebToken
  def self.encode(payload, expiration = 24.hours.from_now)
    payload = payload.dup
    payload['exp'] = expiration.to_i
    JWT.encode(payload, Rails.application.secrets.json_web_token_secret)
  end

  def self.decode(token)
    JWT.decode(token, Rails.application.secrets.json_web_token_secret).first
  end
end

sessions_helper.rb

require 'json_web_token'

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

  def current_user
    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

sessions_controller.rb

class Api::SessionsController < ApplicationController
  before_action :authenticate_with_token!, only: [:destroy]
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)

    if user && user.authenticate(params[:session][:password])
      log_in user
      render json: user, status: :created
    else
      render json: user, status: :unprocessable_entity
    end
  end

  def destroy
    log_out current_user
    render status: 204
  end
end

user.rb

require 'json_web_token'

class User < ApplicationRecord
  attr_reader :current_password

  before_save { email.downcase! }
  before_create :generate_authentication_token!
  before_update :reset_confirmed!, :if => :email_changed?
  has_secure_password
  has_many :posts
  has_many :comments
  has_many :votes
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
  validates :username, presence: true, length: { maximum: 24 }, uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 8 }
  validates :auth_token, uniqueness: true

  def generate_authentication_token!
    begin
      self.auth_token = JsonWebToken.encode('id' => self.id, 'username' => self.username, 'email' => self.email, 'bio' => self.bio, 'confirmed' => self.confirmed, 'admin' => self.admin, 'points' => self.points)
    end while self.class.exists?(auth_token: auth_token)
  end

  def destroy_token!
    self.auth_token = nil
  end

  def reset_confirmed!
    self.confirmed = false
  end

  def upvotes
    self.votes.where(polarity: 1)
  end

  def downvotes
    self.votes.where(polarity: -1)
  end

  def update_with_password(user_params)
    current_password = user_params.delete(:current_password)
    user_params[:password] = current_password if user_params[:password].nil?

    if self.authenticate(current_password)
      self.update(user_params)
    else
      self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
      false
    end
  end
end

No, I am not using devise. I'm really hoping my eyes are just tired here...

Palinode answered 24/8, 2016 at 5:47 Comment(8)
Where's Rails.application.secrets.json_web_token_secret defined?Radioman
That secret is defined in a local_env.yml that is hidden git ignored. In the rails console, if I try to access the variable through Rails.application.secrets it works just fine.Palinode
@LouisCruz, can you post the code in your user.rb model?Elwira
@ArunKumar, of course! Thought I already had it there. It's up now.Palinode
What kind of before_actions are in ApplicationController?Education
@fylooi, I have two possibly relevant things: the first is protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }, and the second is include ActionController::RequestForgeryProtection. There are no before_action calls.Palinode
Hmm. I would guess that something is invoking logged_in? somewhere. Add puts caller to the top of your current_user method and see whether that provides any clarity?Education
@fylooi, logged_in? is never called, but when I place a p caller on the current_user method, I get a very long response that begins with ["/Users/louisstephancruz/.rvm/gems/ruby-2.2.4/bundler/gems/active_model_serializers-532828b4dad4/lib/action_controller/serialization.rb:25:in serialization_scope'",. Also, when I try to put a p caller` on my user_serializer.rb, it is never called.Palinode
P
8

It turns out that current_user was in fact being called since it is the default scope_name for Active Model Serializers. I changed the name of my current_user method to avoid this conflict. Here are the relevant docs.

Palinode answered 24/8, 2016 at 19:53 Comment(1)
Alternatively, you can add serialization_scope :view_context to the controller that you don't want to call current_user. I was having this problem trying to create an authentication token at login. It was calling current_user before I could even log somebody in.Tweed

© 2022 - 2024 — McMap. All rights reserved.