Skip to content

Custom user model

You can extend BluefoxUser with additional columns for your application.

Creating a custom model

from bluefox_auth import BluefoxUser
from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column


class User(BluefoxUser):
    __tablename__ = "users"

    display_name: Mapped[str | None] = mapped_column(String(100))
    company_id: Mapped[int | None] = mapped_column(ForeignKey("companies.id"))

Same table name

Your custom model must use __tablename__ = "users" — it extends the same table, not a new one.

Registering the model

Pass your custom model to BluefoxAuth:

from bluefox_auth import BluefoxAuth

BluefoxAuth(app, settings, user_model=User)

This stores the model on app.state.user_model, and all auth queries will use your model class instead of BluefoxUser.

Using the model in dependencies

The current_active_user and current_superuser dependencies return the model stored on app.state. Since your custom model extends BluefoxUser, it has all the base fields plus your additions:

from fastapi import Depends
from bluefox_auth import current_active_user


@app.get("/profile")
async def profile(user: User = Depends(current_active_user)):
    return {
        "email": user.email,
        "display_name": user.display_name,
        "company_id": user.company_id,
    }

Migrations

After defining your custom model, generate a migration:

alembic revision --autogenerate -m "add custom user fields"
alembic upgrade head

The migration will add the new columns to the existing users table.