From 08228d8f12b9808af53607e490c4a8bdc8bfe937 Mon Sep 17 00:00:00 2001 From: Maciej Pienczyn Date: Mon, 9 Feb 2026 13:00:19 +0100 Subject: [PATCH] fix(auth): Fix DetachedInstanceError on dashboard for users with company associations user_loader was closing the SQLAlchemy session after loading User, causing lazy-load of company_associations to fail when dashboard template calls can_edit_company(). Eagerly load associations in user_loader. Co-Authored-By: Claude Opus 4.6 --- app.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/app.py b/app.py index cc2e297..14df504 100644 --- a/app.py +++ b/app.py @@ -320,10 +320,17 @@ logger.info("Blueprints registered") @login_manager.user_loader def load_user(user_id): - """Load user from database""" + """Load user from database with eager-loaded relationships""" + from sqlalchemy.orm import joinedload db = SessionLocal() try: - return db.query(User).filter_by(id=int(user_id)).first() + user = db.query(User).options( + joinedload(User.company_associations) + ).filter_by(id=int(user_id)).first() + if user: + # Force-load associations before detaching from session + _ = user.company_associations + return user finally: db.close()