forked from info-beamer/36c3-cms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathredis_session.py
45 lines (37 loc) · 1.32 KB
/
redis_session.py
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
import pickle
from flask import sessions
from util import get_random
from util.redis import REDIS
class RedisSession(sessions.CallbackDict, sessions.SessionMixin):
def __init__(self, sid=None, initial=None):
def on_update(self):
self.modified = True
sessions.CallbackDict.__init__(self, initial, on_update)
self.modified = False
self.new_sid = not sid
self.sid = sid or get_random()
class RedisSessionStore(sessions.SessionInterface):
def open_session(self, app, request):
sid = request.cookies.get(app.config["SESSION_COOKIE_NAME"])
if not sid:
return RedisSession()
data = REDIS.get(f"sid:{sid}")
if data is None:
return RedisSession()
return RedisSession(sid, pickle.loads(data))
def save_session(self, app, session, response):
if not session.modified:
return
state = dict(session)
if state:
REDIS.setex(f"sid:{session.sid}", 86400, pickle.dumps(state, 2))
else:
REDIS.delete(f"sid:{session.sid}")
if session.new_sid:
response.set_cookie(
app.config["SESSION_COOKIE_NAME"],
session.sid,
httponly=True,
secure=True,
samesite="Lax",
)