Skip to content

Commit

Permalink
Adds current_active_session helper.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mdchaney committed Jun 12, 2024
1 parent 0e9d1de commit 100dc0c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 9 deletions.
12 changes: 6 additions & 6 deletions app/controllers/active_sessions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 8 additions & 3 deletions app/controllers/concerns/authentication.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions app/models/current.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
class Current < ActiveSupport::CurrentAttributes
attribute :user
attribute :active_session
end

0 comments on commit 100dc0c

Please sign in to comment.