-
Notifications
You must be signed in to change notification settings - Fork 479
/
migrate_cookies_to_redis_store.rb
60 lines (53 loc) · 2.01 KB
/
migrate_cookies_to_redis_store.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require 'rack/session/abstract/id'
require 'redis-actionpack'
module ActionDispatch
module Session
module MigrateCookiesStore
# Ultimately loads session data from the database, after first checking
# for session data in the cookie and persisting it to the database if we
# find any.
def load_session(request)
# migrate_session_data will return the extracted session id if there
# was one; otherwise, we fetch the session id from the request object.
session_id = migrate_session_data(request) || current_session_id(request)
session_id, session = find_session(request, session_id)
[session_id, session || {}]
end
private
# If we already have existing session data in the cookie, this helper
# method will clear the cookie, write that session data to the database,
# and return the session id it extracted from the cookie.
#
# If the cookie does not contain any existing session data, do nothing
# and return nothing.
def migrate_session_data(request)
stale_session_check! do
session_data = unpacked_cookie_data(request)
if session_data.is_a?(Hash) && !session_data.empty?
session_id = Rack::Session::SessionId.new(session_data["session_id"])
request.set_header("action_dispatch.request.unsigned_session_cookie", {})
write_session(request, session_id, session_data.except("session_id"), request.session_options)
return session_id
end
end
end
def unpacked_cookie_data(request)
stale_session_check! do
if data = get_cookie(request) && data.is_a?(Hash)
data.stringify_keys!
end
data || {}
end
end
def get_cookie(request)
cookie_jar(request)[@key]
end
def cookie_jar(request)
request.cookie_jar.signed_or_encrypted
end
end
class MigrateCookiesToRedisStore < RedisStore
include MigrateCookiesStore
end
end
end