From fc45d356999acbd6f76fa0510c886b5c7919baab Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Sun, 30 May 2021 13:03:29 +0200 Subject: [PATCH] core: add migration for sessions Signed-off-by: Jens Langhammer --- .../migrations/0022_authenticatedsession.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/authentik/core/migrations/0022_authenticatedsession.py b/authentik/core/migrations/0022_authenticatedsession.py index 0b26abe07..8130ee682 100644 --- a/authentik/core/migrations/0022_authenticatedsession.py +++ b/authentik/core/migrations/0022_authenticatedsession.py @@ -3,12 +3,46 @@ import uuid import django.db.models.deletion +from django.apps.registry import Apps from django.conf import settings from django.db import migrations, models +from django.db.backends.base.schema import BaseDatabaseSchemaEditor +from django.utils.timezone import now import authentik.core.models +def migrate_sessions(apps: Apps, schema_editor: BaseDatabaseSchemaEditor): + db_alias = schema_editor.connection.alias + from django.contrib.sessions.backends.cache import KEY_PREFIX, SessionStore + from django.core.cache import cache + + AuthenticatedSession = apps.get_model("authentik_core", "AuthenticatedSession") + User = apps.get_model("authentik_core", "user") + + session_keys = cache.keys(KEY_PREFIX + "*") + for key in session_keys: + key = key.replace(KEY_PREFIX, "") + store = SessionStore(key) + data = store.load() + if data == {} or "_auth_user_id" not in data: + continue + if ( + AuthenticatedSession.objects.using(db_alias) + .filter(session_key=key) + .exists() + ): + continue + users = User.objects.using(db_alias).filter(pk=data.get("_auth_user_id")) + if not users.exists(): + continue + AuthenticatedSession.objects.using(db_alias).create( + session_key=key, + user=users.first(), + expires=data.get("_session_expiry", now()), + ) + + class Migration(migrations.Migration): dependencies = [ @@ -48,4 +82,5 @@ class Migration(migrations.Migration): "abstract": False, }, ), + migrations.RunPython(migrate_sessions), ]