diff --git a/backend/app/main.py b/backend/app/main.py index 7f9e559..a840d45 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -13,7 +13,7 @@ from app.admin_router import router as admin_router from app.routers.auth import router as auth_router try: from app.routers.auto_login import router as auto_login_router - from app.services.auto_login_service import start_auto_login_scheduler + from app.services.auto_login_service import start_auto_login_scheduler, refresh_expired_auto_login_sessions _auto_login_available = True except Exception as _auto_login_err: auto_login_router = None @@ -174,6 +174,11 @@ def _run_startup_tasks(app: FastAPI): print(f"[STARTUP] live equity snapshot daemon failed to start: {exc}", flush=True) if _auto_login_available: + try: + refresh_expired_auto_login_sessions() + except Exception as exc: + app.state.background_warnings["auto_login_startup_refresh"] = str(exc) + print(f"[STARTUP] auto-login startup refresh failed: {exc}", flush=True) try: start_auto_login_scheduler() except Exception as exc: diff --git a/backend/app/services/auto_login_service.py b/backend/app/services/auto_login_service.py index 2e62d19..0d2404a 100644 --- a/backend/app/services/auto_login_service.py +++ b/backend/app/services/auto_login_service.py @@ -375,6 +375,22 @@ def refresh_all_auto_login_sessions() -> None: execute_auto_login(user_id=user["user_id"], email=user["email"]) +def refresh_expired_auto_login_sessions() -> None: + """Run on startup: re-login any users whose broker session is expired/disconnected.""" + from app.broker_store import get_user_broker + users = _get_all_auto_login_users() + if not users: + return + print(f"[AUTO-LOGIN] Startup check: {len(users)} auto-login user(s)", flush=True) + for user in users: + entry = get_user_broker(user["user_id"]) or {} + auth_state = str(entry.get("auth_state") or "").strip().upper() + connected = bool(entry.get("connected")) + if not connected or auth_state in {"EXPIRED", "DISCONNECTED", "PENDING", ""}: + print(f"[AUTO-LOGIN] Startup: refreshing expired session for {user['user_id']}", flush=True) + execute_auto_login(user_id=user["user_id"], email=user["email"]) + + # --------------------------------------------------------------------------- # Daily scheduler — runs at 6:05 AM IST every day # ---------------------------------------------------------------------------