Skip to content

Commit 4f6a019

Browse files
Refactors redis/cookie handling
1 parent b9f1504 commit 4f6a019

File tree

2 files changed

+26
-20
lines changed

2 files changed

+26
-20
lines changed

app/controllers/kracken/sessions_controller.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ class SessionsController < ActionController::Base
77
def create
88
@user = user_class.find_or_create_from_auth_hash(auth_hash)
99
session[:user_id] = @user.id
10-
session[:user_cache_key] = cookies[:_radius_user_cache_key]
10+
session[:user_cache_key] = SESSION_REDIS.get(user_session_key(@user.id))
1111
session[:token_expires_at] = Time.zone.at(auth_hash[:credentials][:expires_at])
1212
redirect_to return_to_path
1313
end
@@ -44,5 +44,9 @@ def signout_redirect_query
4444
current_root.path = ''
4545
"?redirect_to=#{CGI.escape(current_root.to_s)}"
4646
end
47+
48+
def user_session_key(id)
49+
"rnsession:#{id}"
50+
end
4751
end
4852
end

lib/kracken/controllers/authenticatable.rb

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,11 @@ def check_token_expiry!
7373
def handle_user_cache_cookie!
7474
if SESSION_REDIS
7575
handle_user_cache_cookie_with_redis
76-
else
77-
if cookies[:_radius_user_cache_key]
78-
if cookies[:_radius_user_cache_key] == "none"
79-
delete_session_data
80-
elsif session[:user_cache_key] != cookies[:_radius_user_cache_key]
81-
clear_cache_cookie_and_sign_out
82-
end
76+
elsif cookies[:_radius_user_cache_key]
77+
if cookies[:_radius_user_cache_key] == "none"
78+
delete_session_data
79+
elsif session[:user_cache_key] != cookies[:_radius_user_cache_key]
80+
clear_cache_cookie_and_sign_out
8381
end
8482
end
8583
end
@@ -119,19 +117,23 @@ def user_signed_in?
119117
private
120118

121119
def handle_user_cache_cookie_with_redis
122-
# If the user passes us a cache key cookie:
123-
if cookies[:_radius_user_cache_key]
124-
expected_val = SESSION_REDIS.get(cookies[:_radius_user_cache_key])
120+
return redirect_to_sign_in unless session_present?
121+
return if session_and_redis_match?
125122

126-
# And we do not have that cookie in Redis
127-
if !expected_val
128-
delete_session_data
129-
# Or we have it in Redis, but it may be somebody else's
130-
# - it's not what we expect from their session
131-
elsif expected_val && expected_val != session[:user_cache_key]
132-
clear_cache_cookie_and_sign_out
133-
end
134-
end
123+
delete_session_data
124+
redirect_to_sign_in
125+
end
126+
127+
def session_present?
128+
session[:user_id] && session[:user_cache_key]
129+
end
130+
131+
def session_and_redis_match?
132+
SESSION_REDIS.get(user_session_key(session[:user_id])) == session[:user_cache_key]
133+
end
134+
135+
def user_session_key(id)
136+
"rnsession:#{id}"
135137
end
136138

137139
def delete_session_data

0 commit comments

Comments
 (0)