diff --git a/backend/app/main.py b/backend/app/main.py index 56a600a..255325e 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -21,7 +21,7 @@ uploads_dir.mkdir(exist_ok=True) # Create tables Base.metadata.create_all(bind=engine) -# Create admin user if doesn't exist +# Create or update admin user def create_admin_user(): from app.database.database import SessionLocal from app.models.user import User @@ -29,24 +29,27 @@ def create_admin_user(): db = SessionLocal() try: + # Check if admin with current email exists admin = db.query(User).filter(User.email == settings.admin_email).first() - if not admin: - try: - hashed_password = get_password_hash(settings.admin_password) - except Exception as hash_error: - print(f"⚠️ Password hashing error: {hash_error}") - print("⚠️ Using direct bcrypt hash as fallback...") - # Fallback: use bcrypt directly to avoid passlib version issues - import bcrypt - hashed_password = bcrypt.hashpw( - settings.admin_password.encode('utf-8'), - bcrypt.gensalt() - ).decode('utf-8') + + if admin: + # Admin exists, update password if needed + admin.hashed_password = get_password_hash(settings.admin_password) + admin.full_name = settings.admin_full_name + db.commit() + print(f"ℹ️ Admin user updated: {settings.admin_email}") + else: + # Delete any other admin users (old ones with different emails) + old_admins = db.query(User).filter(User.is_admin == True).all() + for old_admin in old_admins: + db.delete(old_admin) + db.commit() + # Create new admin user admin = User( email=settings.admin_email, full_name=settings.admin_full_name, - hashed_password=hashed_password, + hashed_password=get_password_hash(settings.admin_password), is_admin=True, is_active=True, must_change_password=True # Force password change on first login @@ -55,8 +58,6 @@ def create_admin_user(): db.commit() print(f"✅ Admin user created: {settings.admin_email}") print(f"⚠️ Default password: {settings.admin_password} (CHANGE THIS!)") - else: - print(f"ℹ️ Admin user already exists: {settings.admin_email}") except Exception as e: print(f"❌ Error creating admin user: {e}") db.rollback()