From f0ce8b0ffa456de0f6d9deac2a0e69bb9fc649da Mon Sep 17 00:00:00 2001 From: Astra Logical Date: Thu, 23 Jul 2026 11:25:21 -0400 Subject: [PATCH] Persist credentials --- matrix_keycloak_bot.py | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/matrix_keycloak_bot.py b/matrix_keycloak_bot.py index c6828bf..1061cba 100644 --- a/matrix_keycloak_bot.py +++ b/matrix_keycloak_bot.py @@ -35,6 +35,8 @@ KEYCLOAK_REALM = os.getenv("KEYCLOAK_REALM", "master") KEYCLOAK_CLIENT_ID = os.getenv("KEYCLOAK_CLIENT_ID", "nest-matrix-bot") KEYCLOAK_CLIENT_SECRET = os.getenv("KEYCLOAK_CLIENT_SECRET", "your-client-secret") +CREDENTIALS_FILE = "/app/store/credentials.json" + # In-memory tracking of active requests pending_requests = {} @@ -458,10 +460,33 @@ async def main(): ), ) - print(f"Connecting to Matrix homeserver {MATRIX_HOMESERVER}...") - await client.login(MATRIX_BOT_PASSWORD) - print(f"Logged in as {MATRIX_BOT_USER}. Syncing...") + # 1. Attempt to restore an existing session + if os.path.exists(CREDENTIALS_FILE): + print("Restoring existing Matrix session...") + with open(CREDENTIALS_FILE, "r") as f: + creds = json.load(f) + + client.access_token = creds["access_token"] + client.user_id = creds["user_id"] + client.device_id = creds["device_id"] + + # 2. If no session exists, log in and save the credentials + else: + print(f"No existing session found. Logging in to {MATRIX_HOMESERVER}...") + resp = await client.login(MATRIX_BOT_PASSWORD) + + # Create the store directory if it doesn't exist + os.makedirs(os.path.dirname(CREDENTIALS_FILE), exist_ok=True) + + with open(CREDENTIALS_FILE, "w") as f: + json.dump({ + "access_token": resp.access_token, + "user_id": resp.user_id, + "device_id": resp.device_id, + }, f) + print(f"Logged in and saved credentials for {MATRIX_BOT_USER}.") + print("Syncing...") await client.sync_forever(timeout=30000, full_state=True)