diff --git a/app/main.py b/app/main.py index 046edc6..b3322a2 100644 --- a/app/main.py +++ b/app/main.py @@ -15,7 +15,7 @@ scanner = BackgroundScanner(db=get_db_session()) async def lifespan(app: FastAPI): load_dotenv() create_db_and_tables() - create_first_user() + create_first_user(db=get_db_session()) print("Database created and tables initialized.") scanner.start() yield diff --git a/app/services/auth.py b/app/services/auth.py index 0d8715d..bca7008 100644 --- a/app/services/auth.py +++ b/app/services/auth.py @@ -83,20 +83,19 @@ def auth_is_admin( ) return True -def create_first_user(): +def create_first_user(db: Session): print("Checking for admin user") - with Session(engine) as db: - admin_user = db.exec(select(UserDB)).first() - if admin_user is None: - password = ''.join(secrets.choice(string.digits) for i in range(8)) - print("Creating first admin user with password", password) - user = UserDB( - name="admin", - passwordhash=get_password_hash(password), - is_admin=True - ) - return add_and_refresh(db, user) - print(f"Admin user already exists: {admin_user.name}") + admin_user = db.exec(select(UserDB)).first() + if admin_user is None: + password = ''.join(secrets.choice(string.digits) for i in range(8)) + print("Creating first admin user with password", password) + user = UserDB( + name="admin", + passwordhash=get_password_hash(password), + is_admin=True + ) + return add_and_refresh(db, user) + print(f"Admin user already exists: {admin_user.name}") @token_router.post("/token") diff --git a/test/test_services/test_auth.py b/test/test_services/test_auth.py index a890459..e4f3798 100644 --- a/test/test_services/test_auth.py +++ b/test/test_services/test_auth.py @@ -140,7 +140,7 @@ def test_create_first_user(db_session): db_session.commit() # Create first user - result = create_first_user() + result = create_first_user(db=db_session) assert result is not None assert result.name == "admin" assert result.is_admin is True @@ -151,7 +151,7 @@ def test_create_first_user(db_session): assert user.is_admin is True # Test that it doesn't create another admin if one exists - second_result = create_first_user() + second_result = create_first_user(db=db_session) assert second_result is None # Should print "Admin user already exists"