🐛 fix(manager.py): migrate flows to default superuser if they don't have a user id associated with them when auto_login is enabled

🐛 fix(utils.py): handle case when superuser already exists during creation to prevent UNIQUE constraint violation
This commit is contained in:
Gabriel Luiz Freitas Almeida 2023-10-03 17:05:46 -03:00
commit f7884af3af
2 changed files with 31 additions and 3 deletions

View file

@ -58,6 +58,25 @@ class DatabaseService(Service):
with Session(self.engine) as session:
yield session
def migrate_flows_if_auto_login(self):
# if auto_login is enabled, we need to migrate the flows
# to the default superuser if they don't have a user id
# associated with them
settings_service = get_settings_service()
if settings_service.auth_settings.AUTO_LOGIN:
with Session(self.engine) as session:
flows = (
session.query(models.Flow).filter(models.Flow.user_id == None).all()
)
if flows:
logger.debug("Migrating flows to default superuser")
username = settings_service.auth_settings.SUPERUSER
user = get_user_by_username(session, username)
for flow in flows:
flow.user_id = user.id
session.commit()
logger.debug("Flows migrated successfully")
def check_schema_health(self) -> bool:
inspector = inspect(self.engine)

View file

@ -7,7 +7,7 @@ from langflow.services.settings.constants import (
DEFAULT_SUPERUSER_PASSWORD,
)
from sqlmodel import Session
from .getters import get_session, get_settings_service
from .getters import get_db_service, get_session, get_settings_service
from loguru import logger
@ -54,8 +54,12 @@ def get_or_create_super_user(session: Session, username, password, is_default):
logger.debug("Creating default superuser.")
else:
logger.debug("Creating superuser.")
return create_super_user(username, password, db=session)
try:
return create_super_user(username, password, db=session)
except Exception as exc:
if "UNIQUE constraint failed: user.username" in str(exc):
logger.debug("Superuser already exists.")
return None
def setup_superuser(settings_service, session: Session):
@ -193,3 +197,8 @@ def initialize_services():
setup_superuser(
service_manager.get(ServiceType.SETTINGS_SERVICE), next(get_session())
)
try:
get_db_service().migrate_flows_if_auto_login()
except Exception as exc:
logger.error(f"Error migrating flows: {exc}")
raise RuntimeError("Error migrating flows") from exc