Skip to content

Commit 100dc0c

Browse files
committed
Adds current_active_session helper.
Closes stevepolitodesign#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.
1 parent 0e9d1de commit 100dc0c

File tree

3 files changed

+15
-9
lines changed

3 files changed

+15
-9
lines changed

app/controllers/active_sessions_controller.rb

+6-6
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@ class ActiveSessionsController < ApplicationController
22
before_action :authenticate_user!
33

44
def destroy
5-
@active_session = current_user.active_sessions.find(params[:id])
5+
active_session = current_user.active_sessions.find(params[:id])
66

7-
@active_session.destroy
8-
9-
if current_user
10-
redirect_to account_path, notice: "Session deleted."
11-
else
7+
if active_session == current_active_session
128
forget_active_session
9+
active_session.destroy
1310
reset_session
1411
redirect_to root_path, notice: "Signed out."
12+
else
13+
active_session.destroy
14+
redirect_to account_path, notice: "Session deleted."
1515
end
1616
end
1717

app/controllers/concerns/authentication.rb

+8-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ module Authentication
33

44
included do
55
before_action :current_user
6+
helper_method :current_active_session
67
helper_method :current_user
78
helper_method :user_signed_in?
89
end
@@ -41,10 +42,14 @@ def remember(active_session)
4142
private
4243

4344
def current_user
44-
Current.user = if session[:current_active_session_id].present?
45-
ActiveSession.find_by(id: session[:current_active_session_id])&.user
45+
Current.user ||= current_active_session&.user
46+
end
47+
48+
def current_active_session
49+
Current.active_session ||= if session[:current_active_session_id].present?
50+
ActiveSession.find_by(id: session[:current_active_session_id])
4651
elsif cookies[:remember_token]
47-
ActiveSession.find_by(remember_token: cookies.encrypted[:remember_token])&.user
52+
ActiveSession.find_by(remember_token: cookies.encrypted[:remember_token])
4853
end
4954
end
5055

app/models/current.rb

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
class Current < ActiveSupport::CurrentAttributes
22
attribute :user
3+
attribute :active_session
34
end

0 commit comments

Comments
 (0)