Migrating from FastAPI Users¶
Your users keep their passwords. FastAPI Users hashes them with pwdlib (Argon2id, and bcrypt for older accounts), as NeoZen does, so the hashes are copied as they are. Everyone signs in again once: FastAPI Users' tokens and cookies don't carry over.
Checked with FastAPI Users 15.0.5 and its SQLAlchemy adapter 7.0.0, on SQLite.
What Maps to What¶
| FastAPI Users | NeoZen |
|---|---|
User (id, email, hashed_password, is_active, is_verified) |
Subject, the same fields; the id as a string |
is_superuser |
A role (Authorization) |
OAuthAccount |
SocialAccount |
Cookie transport with DatabaseStrategy |
NeoZenMiddleware and login_user |
| Bearer transport | A dependency over a NeoZen session |
JWTStrategy |
None: sessions are checked in the database, so they can be revoked |
current_user(active=True) |
CurrentUser (FastAPI guide) |
current_user(superuser=True) |
has_role("admin") |
current_user(verified=True) |
Check user.is_verified in a dependency |
UserManager.on_after_login and the other hooks |
Code in your route, after the call |
get_register_router, get_users_router |
Routes of your own |
get_reset_password_router |
PasswordResetService, behind routes of your own |
get_verify_router |
EmailVerificationService, behind routes of your own |
get_oauth_router |
OAuthClientService (OAuth Client), behind routes of your own |
The main difference: FastAPI Users gives you routers, NeoZen gives you services, and the routes are yours.
1. Set Up NeoZen Beside FastAPI Users¶
Follow the FastAPI guide, on the same database. Keep both hashers (Argon2Hasher(), BcryptHasher()). NeoZen's table names don't clash with FastAPI Users' defaults. Create them with neozen db upgrade.
2. Copy the Accounts¶
Back up the database first. This reads your FastAPI Users models and leaves their tables alone; run again, it copies only what is new.
"""Copy FastAPI Users accounts into NeoZen's tables. Safe to run again."""
from __future__ import annotations
import asyncio
from collections import Counter
from sqlalchemy import select
from auth import session_factory
from models import OAuthAccount, User # your FastAPI Users models
from neozen.core.utils import generate_id
from neozen.storage.sqlalchemy.models import SocialAccount, Subject
async def migrate() -> None:
async with session_factory() as db:
users = (await db.scalars(select(User))).unique().all()
# NeoZen stores emails in lowercase, one subject per address.
emails = Counter(user.email.lower() for user in users)
if clashes := [email for email, n in emails.items() if n > 1]:
raise SystemExit(f"Same email but for case, merge them first: {clashes}")
known = set(await db.scalars(select(Subject.id)))
for user in users:
if str(user.id) in known:
continue
db.add(
Subject(
id=str(user.id),
email=user.email,
hashed_password=user.hashed_password,
is_active=user.is_active,
is_verified=user.is_verified,
)
)
await db.flush()
linked = set(
await db.execute(
select(SocialAccount.provider_id, SocialAccount.provider_user_id)
)
)
for account in (await db.scalars(select(OAuthAccount))).unique():
if (account.oauth_name, account.account_id) in linked:
continue
db.add(
SocialAccount(
id=generate_id(),
subject_id=str(account.user_id),
provider_id=account.oauth_name,
provider_user_id=account.account_id,
email=account.account_email,
)
)
await db.commit()
for user in users:
if user.is_superuser:
print(f"was a superuser: {user.email} ({user.id})")
if __name__ == "__main__":
asyncio.run(migrate())
- It stops if two accounts have the same email but for case: NeoZen stores emails in lowercase, one subject per address.
- It doesn't update accounts copied earlier: do the last run with sign-in closed, so that no password changes in between.
- It leaves out the OAuth access and refresh tokens, which signing in doesn't need.
- If your app has no social login, drop the
OAuthAccountblock. - An
emaillonger than 255 characters doesn't fit.
3. Give Superusers a Role¶
The script prints who was a superuser. Create a role for your app's administrators and assign it:
In NeoZen, superuser and admin also open the admin console, if you mount it; pick another name for a role that shouldn't.
4. Switch the Routes¶
Replace Depends(fastapi_users.current_user(...)) with the dependencies of the FastAPI guide, and the auth router with its /login and /logout. Two things change for clients:
- Login takes JSON with
emailandpasswordthere; FastAPI Users takes a form withusernameandpassword. - A refused login is a 401; FastAPI Users answers 400.
Keep the old shapes in your routes if clients depend on them.
5. Your Own Columns¶
Columns you added to User, and foreign keys to it, can stay where they are: a subject has the same id as its user, as a string. Load your row with uuid.UUID(subject.id). Once nothing reads them, drop hashed_password from your table, and FastAPI Users' token table.