Files
session_redis_public/session_redis/session.py
T
Vincent Van Rossem ff8cd092bd [IMP] session_redis: add absolute expiration option
ODOO_SESSION_REDIS_EXPIRATION_ABSOLUTE=1 makes authenticated sessions expire
ODOO_SESSION_REDIS_EXPIRATION seconds after the login, whatever the activity.

Default mode: SET … EX instead of SET then EXPIRE, so a failed EXPIRE can no
longer leave a key without TTL. rotate() also resets should_rotate, as
odoo.http.FilesystemSessionStore does.
2026-09-25 11:03:00 +02:00

144 lines
4.9 KiB
Python

# Copyright 2016-2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
import json
import logging
from odoo.service import security
from odoo.tools._vendor.sessions import SessionStore
from . import json_encoding
# this is equal to the duration of the session garbage collector in
# odoo.http.session_gc()
DEFAULT_SESSION_TIMEOUT = 60 * 60 * 24 * 7 # 7 days in seconds
DEFAULT_SESSION_TIMEOUT_ANONYMOUS = 60 * 60 * 3 # 3 hours in seconds
_logger = logging.getLogger(__name__)
class RedisSessionStore(SessionStore):
"""SessionStore that saves session to redis"""
def __init__(
self,
redis,
session_class=None,
prefix="",
expiration=None,
anon_expiration=None,
absolute_expiration=False,
):
super().__init__(session_class=session_class)
self.redis = redis
if expiration is None:
self.expiration = DEFAULT_SESSION_TIMEOUT
else:
self.expiration = expiration
if anon_expiration is None:
self.anon_expiration = DEFAULT_SESSION_TIMEOUT_ANONYMOUS
else:
self.anon_expiration = anon_expiration
# authenticated sessions expire after `expiration` since their login
self.absolute_expiration = absolute_expiration
self.prefix = "session:"
if prefix:
self.prefix = f"{self.prefix}:{prefix}:"
def build_key(self, sid):
return f"{self.prefix}{sid}"
def save(self, session):
key = self.build_key(session.sid)
# allow to set a custom expiration for a session
# such as a very short one for monitoring requests
if session.uid:
expiration = session.expiration or self.expiration
else:
expiration = session.expiration or self.anon_expiration
if _logger.isEnabledFor(logging.DEBUG):
if session.uid:
user_msg = f"user '{session.login}' (id: {session.uid})"
else:
user_msg = "anonymous user"
_logger.debug(
"saving session with key '%s' and " "expiration of %s seconds for %s",
key,
expiration,
user_msg,
)
data = json.dumps(dict(session), cls=json_encoding.SessionEncoder).encode(
"utf-8"
)
if self.absolute_expiration and session.uid and not session.is_new:
# absolute mode: keep the TTL set at login (keepttl) and never
# recreate an expired session (xx); anonymous and new sessions
# get a full TTL below
if not self.redis.set(key, data, xx=True, keepttl=True):
return False
# keepttl keeps "no TTL": give one to a key left without
if self.redis.ttl(key) == -1:
self.redis.expire(key, expiration)
return True
# write the data and the TTL in one command: with SET then EXPIRE, a
# failed EXPIRE left a key without TTL, never expiring
return self.redis.set(key, data, ex=expiration)
def delete(self, session):
key = self.build_key(session.sid)
_logger.debug("deleting session with key %s", key)
return self.redis.delete(key)
def get(self, sid):
if not self.is_valid_key(sid):
_logger.debug(
"session with invalid sid '%s' has been asked, " "returning a new one",
sid,
)
return self.new()
key = self.build_key(sid)
saved = self.redis.get(key)
if not saved:
_logger.debug(
"session with non-existent key '%s' has been asked, "
"returning a new one",
key,
)
return self.new()
try:
data = json.loads(saved.decode("utf-8"), cls=json_encoding.SessionDecoder)
except ValueError:
_logger.debug(
"session for key '%s' has been asked but its json "
"content could not be read, it has been reset",
key,
)
data = {}
return self.session_class(data, sid, False)
def list(self):
keys = self.redis.keys("%s*" % self.prefix)
_logger.debug("a listing redis keys has been called")
return [key[len(self.prefix) :] for key in keys]
def rotate(self, session, env):
self.delete(session)
session.sid = self.generate_key()
# new key: save it with a full expiration, in absolute mode too
session.is_new = True
if session.uid and env:
session.session_token = security.compute_session_token(session, env)
session.should_rotate = False
self.save(session)
def vacuum(self, *args, **kwargs):
"""Do not garbage collect the sessions
Redis keys are automatically cleaned at the end of their
expiration.
"""
return None