From 100dc0c7907ef6a1fbb6b910910657f150170aa9 Mon Sep 17 00:00:00 2001 From: Michael Chaney Date: Tue, 11 Jun 2024 20:55:29 -0500 Subject: [PATCH] Adds current_active_session helper. Closes #93, "Why is the ||= removed? current_user method". This adds memoization back to current_user / Current.user, plus causes log out when the current session is destroyed. --- app/controllers/active_sessions_controller.rb | 12 ++++++------ app/controllers/concerns/authentication.rb | 11 ++++++++--- app/models/current.rb | 1 + 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/app/controllers/active_sessions_controller.rb b/app/controllers/active_sessions_controller.rb index e085820..cc428d5 100644 --- a/app/controllers/active_sessions_controller.rb +++ b/app/controllers/active_sessions_controller.rb @@ -2,16 +2,16 @@ class ActiveSessionsController < ApplicationController before_action :authenticate_user! def destroy - @active_session = current_user.active_sessions.find(params[:id]) + active_session = current_user.active_sessions.find(params[:id]) - @active_session.destroy - - if current_user - redirect_to account_path, notice: "Session deleted." - else + if active_session == current_active_session forget_active_session + active_session.destroy reset_session redirect_to root_path, notice: "Signed out." + else + active_session.destroy + redirect_to account_path, notice: "Session deleted." end end diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb index 751f0c2..4afc4e0 100644 --- a/app/controllers/concerns/authentication.rb +++ b/app/controllers/concerns/authentication.rb @@ -3,6 +3,7 @@ module Authentication included do before_action :current_user + helper_method :current_active_session helper_method :current_user helper_method :user_signed_in? end @@ -41,10 +42,14 @@ def remember(active_session) private def current_user - Current.user = if session[:current_active_session_id].present? - ActiveSession.find_by(id: session[:current_active_session_id])&.user + Current.user ||= current_active_session&.user + end + + def current_active_session + Current.active_session ||= if session[:current_active_session_id].present? + ActiveSession.find_by(id: session[:current_active_session_id]) elsif cookies[:remember_token] - ActiveSession.find_by(remember_token: cookies.encrypted[:remember_token])&.user + ActiveSession.find_by(remember_token: cookies.encrypted[:remember_token]) end end diff --git a/app/models/current.rb b/app/models/current.rb index 73a9744..b1661ca 100644 --- a/app/models/current.rb +++ b/app/models/current.rb @@ -1,3 +1,4 @@ class Current < ActiveSupport::CurrentAttributes attribute :user + attribute :active_session end