Unexpected login behaviour in production in my Rails 7 app

48 Views Asked by At

I have a Rails 7 app with basic login functionality that authenticates and logs in the user. This works fine in development mode. After deploying to render.com I keep being redirected back to the the login page.

My best guess is that it is either related to TURBO_STREAM or something with how sessions are handled in production.

Any suggestions on this?

The logs:

I, [xxx]  INFO -- : [xxc681]   Parameters: {"authenticity_token"=>"[FILTERED]", "session"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, "commit"=>"Log in"}
I, [xxx]  INFO -- : [xxc681] Redirected to https://myapp.onrender.com/dashboard
I, [xxx]  INFO -- : [xxc681] Completed 302 Found in 2241ms (ActiveRecord: 78.1ms | Allocations: 29973)
I, [xxx]  INFO -- : [xx4e31] Started GET "/dashboard" for 172.71.98.11 at 2024-02-24 20:46:23 +0000
I, [xxx]  INFO -- : [xx4e31] Processing by AgreementsController#index as TURBO_STREAM
I, [xxx]  INFO -- : [xx4e31] Redirected to https://myapp.onrender.com/login

My controller methods:

class AgreementsController < ApplicationController
  include Auditable

  before_action :logged_in_user
  before_action :check_subscription
  before_action :check_credit, only: [:show]

  def index
    @user = current_user
    @q = Agreement.ransack(params[:q])
  end
end

and:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper

  # callbacks
  before_action :set_auditlog_variables

  # Make active_user variable available in the Auditable concern
  def set_auditlog_variables
    AuditLog.active_user = current_user if logged_in?
  end

  private

    # Confirms a logged-in user.
    def logged_in_user
      unless logged_in?
        store_location
        flash[:danger] = "Please log in."
        redirect_to login_url, status: :see_other
      end
    end
end

My helper methods

module SessionsHelper
  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
    session[:session_token] = user.session_token
    user.create_session_log(:login)
  end

  def current_user
    if (user_id = session[:user_id])
      user = User.find_by(id: user_id)
      if user && session[:session_token] == user.session_token
        @current_user = user
      end
    elsif (user_id = cookies.encrypted[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the given user is the current user.
  def current_user?(user)
    user && user == current_user
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end
end
0

There are 0 best solutions below