### Initializing Beanie ODM in FastAPI Startup Source: https://fastapi-users.github.io/fastapi-users/latest/migration/9x_to_10x Provides an example of how to initialize Beanie ODM with the FastAPI application during the startup event, specifying the database and document models. ```python from beanie import init_beanie @app.on_event("startup") async def on_startup(): await init_beanie( database=db, document_models=[ User, ], ) ``` -------------------------------- ### Install Dependencies Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example Installs necessary Python packages for FastAPI, FastAPI Users with SQLAlchemy, and Uvicorn for running the application. It also includes aiohttp for asynchronous SQLite operations. ```Python fastapi fastapi-users[sqlalchemy] uvicorn[standard] aiosqlite ``` -------------------------------- ### Install FastAPI Users with SQLAlchemy Source: https://fastapi-users.github.io/fastapi-users/latest/installation Installs the FastAPI Users library with support for SQLAlchemy as the database backend. This is a common setup for projects using relational databases with FastAPI. ```Shell pip install "fastapi-users[sqlalchemy]" ``` -------------------------------- ### Install FastAPI Users with Redis Support Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/authentication/strategies/redis Installs the fastapi-users library with the necessary optional dependencies for Redis integration. ```Shell pip install'fastapi-users[redis]' ``` -------------------------------- ### Install FastAPI Users with Beanie Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example Lists the necessary packages to install for FastAPI Users with Beanie integration, including FastAPI, FastAPI Users with Beanie support, and Uvicorn for running the application. ```text fastapi fastapi-users[beanie] uvicorn[standard] ``` -------------------------------- ### FastAPI Users Full Example with JWT Authentication Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example This snippet demonstrates a full working example of FastAPI Users with JWT authentication. It highlights the setup and usage of the library for secure user management. Remember to replace 'SECRET' with a strong, unique passphrase for security. ```python from fastapi import FastAPI from fastapi_users import FastAPIUsers from fastapi_users.authentication import JWTAuthentication from fastapi_users.db import SQLAlchemyUserDatabase from sqlalchemy import create_engine, Column, Integer, String, Boolean from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # Database Setup (Example with SQLAlchemy) DATABASE_URL = "sqlite:///./test.db" engine = create_engine(DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) email = Column(String, unique=True, index=True, nullable=False) hashed_password = Column(String, nullable=False) is_active = Column(Boolean, default=True) is_superuser = Column(Boolean, default=False) is_verified = Column(Boolean, default=False) Base.metadata.create_all(bind=engine) # User Database def get_user_db(): db = SessionLocal() try: yield SQLAlchemyUserDatabase(db, User) finally: db.close() # Authentication SECRET = "YOUR_STRONG_SECRET_KEY" authenticator = JWTAuthentication(secret=SECRET, lifetime_seconds=3600) fastapi_users = FastAPIUsers( get_user_db(), authenticator, ) app = FastAPI() app.include_router(fastapi_users.get_auth_router(authenticator)) app.include_router(fastapi_users.get_register_router()) app.include_router(fastapi_users.get_users_router()) @app.get("/authenticated") def authenticated_endpoint(user=fastapi_users.current_user()): return {"message": f"Hello, {user.email}! You are authenticated."} ``` -------------------------------- ### SQLAlchemy User and Access Token Database Setup Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/authentication/strategies/database Sets up SQLAlchemy models for users and access tokens, along with the necessary database engine and session management for FastAPI Users. It includes functions to create tables, get an async session, and retrieve user and access token databases. ```Python from collections.abc import AsyncGenerator from fastapi import Depends from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase from fastapi_users_db_sqlalchemy.access_token import ( SQLAlchemyAccessTokenDatabase, SQLAlchemyBaseAccessTokenTableUUID, ) from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase DATABASE_URL = "sqlite+aiosqlite:///./test.db" class Base(DeclarativeBase): pass class User(SQLAlchemyBaseUserTableUUID, Base): pass class AccessToken(SQLAlchemyBaseAccessTokenTableUUID, Base): pass engine = create_async_engine(DATABASE_URL) async_session_maker = async_sessionmaker(engine, expire_on_commit=False) async def create_db_and_tables(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def get_async_session() -> AsyncGenerator[AsyncSession, None]: async with async_session_maker() as session: yield session async def get_user_db(session: AsyncSession = Depends(get_async_session)): yield SQLAlchemyUserDatabase(session, User) async def get_access_token_db( session: AsyncSession = Depends(get_async_session), ): yield SQLAlchemyAccessTokenDatabase(session, AccessToken) ``` -------------------------------- ### Setup Register Router with FastAPI Users Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/routers/register This code demonstrates how to set up the registration router for FastAPI Users. It includes importing necessary components like FastAPI, FastAPIUsers, User model, and schemas. The code then initializes FastAPIUsers and includes the generated register router in the FastAPI application with a specified prefix and tags. ```Python import uuid from fastapi import FastAPI from fastapi_users import FastAPIUsers from .db import User from .schemas import UserCreate, UserRead fastapi_users = FastAPIUsers[User, uuid.UUID]( get_user_manager, [auth_backend], ) app = FastAPI() app.include_router( fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"], ) ``` -------------------------------- ### Main FastAPI Application Setup Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/oauth Sets up the main FastAPI application, including database initialization, user authentication routes, and OAuth integration with Google. ```Python from contextlib import asynccontextmanager from fastapi import Depends, FastAPI from app.db import User, create_db_and_tables from app.schemas import UserCreate, UserRead, UserUpdate from app.users import ( SECRET, auth_backend, current_active_user, fastapi_users, google_oauth_client, ) @asynccontextmanager async def lifespan(app: FastAPI): # Not needed if you setup a migration system like Alembic await create_db_and_tables() yield app = FastAPI(lifespan=lifespan) app.include_router( fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"] ) app.include_router( fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_verify_router(UserRead), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"], ) app.include_router( fastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET), prefix="/auth/google", tags=["auth"], ) @app.get("/authenticated-route") async def authenticated_route(user: User = Depends(current_active_user)): return {"message": f"Hello {user.email}!"} ``` -------------------------------- ### Example Script to Run Create User Function Source: https://fastapi-users.github.io/fastapi-users/latest/cookbook/create-user-programmatically This Python script shows how to execute the `create_user` function using `asyncio.run`. It's a simple example to demonstrate calling the user creation logic from a main execution block. ```Python import asyncio if __name__ == "__main__": asyncio.run(create_user("king.arthur@camelot.bt", "guinevere")) ``` -------------------------------- ### FastAPI Application Setup Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example Sets up the main FastAPI application, including database initialization, and includes routers for authentication, user registration, password reset, verification, and user management. ```Python from contextlib import asynccontextmanager from fastapi import Depends, FastAPI from app.db import User, create_db_and_tables from app.schemas import UserCreate, UserRead, UserUpdate from app.users import auth_backend, current_active_user, fastapi_users @asynccontextmanager async def lifespan(app: FastAPI): # Not needed if you setup a migration system like Alembic await create_db_and_tables() yield app = FastAPI(lifespan=lifespan) app.include_router( fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"] ) app.include_router( fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_verify_router(UserRead), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"], ) @app.get("/authenticated-route") async def authenticated_route(user: User = Depends(current_active_user)): return {"message": f"Hello {user.email}!"} ``` -------------------------------- ### Install FastAPI Users Source: https://fastapi-users.github.io/fastapi-users/latest/index This snippet shows how to install the FastAPI Users library using pip. It's the first step to integrate user management into your FastAPI project. ```bash pip install fastapi-users ``` -------------------------------- ### Create SQLAlchemy User Model and Database Setup Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/databases/sqlalchemy Defines a User model inheriting from SQLAlchemyBaseUserTableUUID, sets up an asynchronous engine and session maker for SQLite, and provides functions to create tables and get an async session. It also includes a dependency to get the SQLAlchemyUserDatabase. ```Python from collections.abc import AsyncGenerator from fastapi import Depends from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase DATABASE_URL = "sqlite+aiosqlite:///./test.db" class Base(DeclarativeBase): pass class User(SQLAlchemyBaseUserTableUUID, Base): pass engine = create_async_engine(DATABASE_URL) async_session_maker = async_sessionmaker(engine, expire_on_commit=False) async def create_db_and_tables(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def get_async_session() -> AsyncGenerator[AsyncSession, None]: async with async_sessionmaker() as session: yield session async def get_user_db(session: AsyncSession = Depends(get_async_session)): yield SQLAlchemyUserDatabase(session, User) ``` -------------------------------- ### Setup FastAPI Users Auth Router Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/routers/auth This code snippet demonstrates the basic setup of the FastAPI Users authentication router. It includes importing necessary components, initializing FastAPIUsers with a user manager and authentication backend, and including the generated auth router in the FastAPI application. ```Python import uuid from fastapi import FastAPI from fastapi_users import FastAPIUsers from .db import User fastapi_users = FastAPIUsers[User, uuid.UUID]( get_user_manager, [auth_backend], ) app = FastAPI() app.include_router( fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"], ) ``` -------------------------------- ### Install Dependencies for FastAPI Users SQLAlchemy Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/oauth Lists the necessary Python packages to install for using FastAPI Users with SQLAlchemy, including FastAPI, FastAPI Users with SQLAlchemy and OAuth support, and Uvicorn for running the application. ```text fastapi fastapi-users[sqlalchemy,oauth] uvicorn[standard] aiosqlite ``` -------------------------------- ### Install FastAPI Users with OAuth2 and SQLAlchemy Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/oauth Installs the fastapi-users library with optional dependencies for SQLAlchemy and OAuth2 support, enabling OAuth2 authentication in your FastAPI application. ```bash pip'fastapi-users[sqlalchemy,oauth]' ``` -------------------------------- ### MongoDB User Database with Beanie ODM Source: https://fastapi-users.github.io/fastapi-users/latest/migration/9x_to_10x Demonstrates the implementation of a MongoDB User database using Beanie ODM, including client setup and the `get_user_db` function. It shows the transition from the older MongoDBUserDatabase to BeanieUserDatabase. ```python import os import motor.motor_asyncio from fastapi_users.db import MongoDBUserDatabase from app.models import UserDB DATABASE_URL = os.environ["DATABASE_URL"] client = motor.motor_asyncio.AsyncIOMotorClient( DATABASE_URL, uuidRepresentation="standard" ) db = client["database_name"] collection = db["users"] async def get_user_db(): yield MongoDBUserDatabase(UserDB, collection) ``` ```python import motor.motor_asyncio from beanie import PydanticObjectId from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase DATABASE_URL = "mongodb://localhost:27017" client = motor.motor_asyncio.AsyncIOMotorClient( DATABASE_URL, uuidRepresentation="standard" ) db = client["database_name"] class User(BeanieBaseUser[PydanticObjectId]): pass async def get_user_db(): yield BeanieUserDatabase(User) ``` -------------------------------- ### Install FastAPI Users with Beanie Source: https://fastapi-users.github.io/fastapi-users/latest/installation Installs the FastAPI Users library with support for Beanie, an ODM for MongoDB, enabling integration with NoSQL databases. ```Shell pip install "fastapi-users[beanie]" ``` -------------------------------- ### FastAPI Users UserManager with UUIDIDMixin Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/user-manager Provides an example of creating a `UserManager` dependency for FastAPI applications using `UUIDIDMixin`. This setup includes configuring secrets for password reset and verification tokens, and defining callback methods for user registration and password reset events. ```Python import uuid from typing import Optional from fastapi import Depends, Request from fastapi_users import BaseUserManager, UUIDIDMixin from .db import User, get_user_db SECRET = "SECRET" class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]): reset_password_token_secret = SECRET verification_token_secret = SECRET async def on_after_register(self, user: User, request: Optional[Request] = None): print(f"User {user.id} has registered.") async def on_after_forgot_password( self, user: User, token: str, request: Optional[Request] = None, ): print(f"User {user.id} has forgot their password. Reset token: {token}") async def on_after_request_verify( self, user: User, token: str, request: Optional[Request] = None, ): print(f"Verification requested for user {user.id}. Verification token: {token}") async def get_user_manager(user_db=Depends(get_user_db)): yield UserManager(user_db) ``` -------------------------------- ### Cookie Transport Example Source: https://fastapi-users.github.io/fastapi-users/latest/index This Python code demonstrates how to set up a cookie transport for authentication in FastAPI Users. It includes configuring the cookie name and other relevant parameters. ```python from fastapi_users.authentication import CookieTransport cookie_transport = CookieTransport(cookie_name="fastapi-users", cookie_secure=False) ``` -------------------------------- ### Install FastAPI Users with OAuth2 and Beanie Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/oauth Installs the fastapi-users library with optional dependencies for Beanie ODM and OAuth2 support, facilitating OAuth2 authentication with Beanie in FastAPI. ```bash pip'fastapi-users[beanie,oauth]' ``` -------------------------------- ### FastAPI Application Setup with Beanie Lifespan Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example Sets up a FastAPI application with Beanie ODM for MongoDB integration. It includes a lifespan context manager for initializing the Beanie connection and defines routes for authentication and user management. ```Python from contextlib import asynccontextmanager from beanie import init_beanie from fastapi import Depends, FastAPI from app.db import User, db from app.schemas import UserCreate, UserRead, UserUpdate from app.users import auth_backend, current_active_user, fastapi_users @asynccontextmanager async def lifespan(app: FastAPI): await init_beanie( database=db, document_models=[ User, ], ) yield app = FastAPI(lifespan=lifespan) app.include_router( fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"] ) app.include_router( fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_verify_router(UserRead), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"], ) @app.get("/authenticated-route") async def authenticated_route(user: User = Depends(current_active_user)): return {"message": f"Hello {user.email}!"} ``` -------------------------------- ### Beanie MongoDB Database Setup Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example Configures the MongoDB connection using Motor and Beanie. It defines the database URL, creates an async client, and sets up a User document model inheriting from BeanieBaseUser and Beanie's Document. ```Python import motor.motor_asyncio from beanie import Document from fastapi_users.db import BeanieBaseUser from fastapi_users_db_beanie import BeanieUserDatabase DATABASE_URL = "mongodb://localhost:27017" client = motor.motor_asyncio.AsyncIOMotorClient( DATABASE_URL, uuidRepresentation="standard" ) db = client["database_name"] class User(BeanieBaseUser, Document): pass async def get_user_db(): yield BeanieUserDatabase(User) ``` -------------------------------- ### Install Dependencies for FastAPI Users with Beanie Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/oauth This snippet lists the necessary Python packages to install for a FastAPI project using FastAPI Users and Beanie ODM. It includes FastAPI, FastAPI Users with Beanie and OAuth support, and Uvicorn for running the application. ```text fastapi fastapi-users[beanie,oauth] uvicorn[standard] ``` -------------------------------- ### SQLAlchemyUserDatabase Adapter Instantiation Source: https://fastapi-users.github.io/fastapi-users/latest/migration/9x_to_10x Demonstrates the updated instantiation of `SQLAlchemyUserDatabase` in FastAPI Users v10, which now expects the `User` model directly and removes the `UserDB` parameter. ```Python async def get_user_db(session: AsyncSession = Depends(get_async_session)): yield SQLAlchemyUserDatabase(UserDB, session, UserTable) ``` ```Python async def get_user_db(session: AsyncSession = Depends(get_async_session)): yield SQLAlchemyUserDatabase(session, User) ``` -------------------------------- ### Initialize FastAPIUsers without Schemas Source: https://fastapi-users.github.io/fastapi-users/latest/migration/9x_to_10x Demonstrates initializing the FastAPIUsers class without passing Pydantic schemas directly. This is a change from previous versions where schemas were mandatory during initialization. ```python fastapi_users = FastAPIUsers( get_user_manager, [auth_backend], User, UserCreate, UserUpdate, UserDB, ) ``` ```python fastapi_users = FastAPIUsers[User, uuid.UUID]( get_user_manager, [auth_backend], ) ``` -------------------------------- ### SQLAlchemy User Model Example Source: https://fastapi-users.github.io/fastapi-users/latest/index This Python code demonstrates how to define a user model using SQLAlchemy for FastAPI Users. It includes essential fields like id, email, and hashed password. ```python from fastapi_users.db import SQLAlchemyBaseUserTable class User(SQLAlchemyBaseUserTable): pass ``` -------------------------------- ### SQLAlchemy Database Models and Setup Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/oauth Defines SQLAlchemy models for users and OAuth accounts, sets up the asynchronous database engine, and provides functions for database creation and session management. ```Python from collections.abc import AsyncGenerator from fastapi import Depends from fastapi_users.db import ( SQLAlchemyBaseOAuthAccountTableUUID, SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase, ) from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase, Mapped, relationship DATABASE_URL = "sqlite+aiosqlite:///./test.db" class Base(DeclarativeBase): pass class OAuthAccount(SQLAlchemyBaseOAuthAccountTableUUID, Base): pass class User(SQLAlchemyBaseUserTableUUID, Base): oauth_accounts: Mapped[list[OAuthAccount]] = relationship( "OAuthAccount", lazy="joined" ) engine = create_async_engine(DATABASE_URL) async_session_maker = async_sessionmaker(engine, expire_on_commit=False) async def create_db_and_tables(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def get_async_session() -> AsyncGenerator[AsyncSession, None]: async with async_session_maker() as session: yield session async def get_user_db(session: AsyncSession = Depends(get_async_session)): yield SQLAlchemyUserDatabase(session, User, OAuthAccount) ``` -------------------------------- ### Bearer Transport Example Source: https://fastapi-users.github.io/fastapi-users/latest/index This Python code illustrates how to configure a Bearer token transport for authentication with FastAPI Users. It specifies the authorization header name. ```python from fastapi_users.authentication import BearerTransport bearer_transport = BearerTransport(tokenUrl="/auth/jwt/login") ``` -------------------------------- ### Beanie User Model Example Source: https://fastapi-users.github.io/fastapi-users/latest/index This Python code illustrates how to define a user model using Beanie ODM for FastAPI Users. It showcases the structure required for MongoDB integration. ```python from fastapi_users.db import BeanieBaseUser class User(BeanieBaseUser): pass ``` -------------------------------- ### Update User ID Comparison in Python Source: https://fastapi-users.github.io/fastapi-users/latest/migration/08_to_1x Demonstrates how to correctly compare user IDs in Python code after migrating to UUIDs. The example shows the 'before' and 'after' states for asserting equality. ```python # Before assert "d35d213e-f3d8-4f08-954a-7e0d1bea286f" == user.id # Now assert "d35d213e-f3d8-4f08-954a-7e0d1bea286f" == str(user.id) ``` -------------------------------- ### Convert JWTAuthentication Backend (Python) Source: https://fastapi-users.github.io/fastapi-users/latest/migration/8x_to_9x Demonstrates the conversion of a JWTAuthentication backend from FastAPI Users v8 to v9. The new approach separates transport and strategy, requiring explicit definition of both. ```Python from fastapi_users.authentication import JWTAuthentication jwt_authentication = JWTAuthentication( secret=SECRET, lifetime_seconds=3600, tokenUrl="auth/jwt/login" ) ``` ```Python from fastapi_users.authentication import AuthenticationBackend, BearerTransport, JWTStrategy SECRET = "SECRET" bearer_transport = BearerTransport(tokenUrl="auth/jwt/login") def get_jwt_strategy() -> JWTStrategy: return JWTStrategy(secret=SECRET, lifetime_seconds=3600) auth_backend = AuthenticationBackend( name="jwt", transport=bearer_transport, get_strategy=get_jwt_strategy, ) ``` -------------------------------- ### Convert CookieAuthentication Backend (Python) Source: https://fastapi-users.github.io/fastapi-users/latest/migration/8x_to_9x Illustrates the migration of a CookieAuthentication backend from FastAPI Users v8 to v9. The update involves creating a CookieTransport and a strategy, then combining them into an AuthenticationBackend. ```Python from fastapi_users.authentication import CookieAuthentication cookie_authentication = CookieAuthentication(secret=SECRET, lifetime_seconds=3600) ``` ```Python from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy SECRET = "SECRET" cookie_transport = CookieTransport(cookie_max_age=3600) def get_jwt_strategy() -> JWTStrategy: return JWTStrategy(secret=SECRET, lifetime_seconds=3600) auth_backend = AuthenticationBackend( name="cookie", transport=cookie_transport, get_strategy=get_jwt_strategy, ) ``` -------------------------------- ### Renaming Pydantic Models to Schemas Source: https://fastapi-users.github.io/fastapi-users/latest/migration/9x_to_10x Explains the change in terminology from Pydantic models to schemas in FastAPI Users and demonstrates the updated schema definitions, including the generic type for user IDs. ```python from fastapi_users import models class User(models.BaseUser): pass class UserCreate(models.BaseUserCreate): pass class UserUpdate(models.BaseUserUpdate): pass class UserDB(User, models.BaseUserDB): pass ``` ```python import uuid from fastapi_users import schemas class UserRead(schemas.BaseUser[uuid.UUID]): pass class UserCreate(schemas.BaseUserCreate): pass class UserUpdate(schemas.BaseUserUpdate): pass ``` -------------------------------- ### Get Current Active Superuser Source: https://fastapi-users.github.io/fastapi-users/latest/usage/current-user Provides an example of retrieving users who are active and possess superuser privileges. Non-superusers will be denied access with a 403 Forbidden error. ```Python current_superuser = fastapi_users.current_user(active=True, superuser=True) @app.get("/protected-route") def protected_route(user: User = Depends(current_superuser)): return f"Hello, {user.email}" ``` -------------------------------- ### Serve Documentation Locally with Hatch Source: https://fastapi-users.github.io/fastapi-users/latest/index This command serves the project's documentation locally, making it accessible via a web browser. The documentation will be available at http://localhost:8000. ```bash hatch ``` -------------------------------- ### Setup FastAPI Verify Router Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/routers/verify This snippet shows how to set up and include the verify router from FastAPI Users in a FastAPI application. It demonstrates the necessary imports, initialization of FastAPIUsers, and inclusion of the verify router with a specified schema and prefix. ```Python import uuid from fastapi import FastAPI from fastapi_users import FastAPIUsers from .db import User from .schemas import UserRead fastapi_users = FastAPIUsers[User, uuid.UUID]( get_user_manager, [auth_backend], ) app = FastAPI() app.include_router( fastapi_users.get_verify_router(UserRead), prefix="/auth", tags=["auth"], ) ``` -------------------------------- ### Include Routers with Schema Initialization Source: https://fastapi-users.github.io/fastapi-users/latest/migration/9x_to_10x Shows how to include various routers from FastAPIUsers, including the updated method of passing Pydantic schemas (e.g., UserRead, UserCreate) during router initialization for functionalities like registration and user retrieval. ```python app.include_router( fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"] ) app.include_router(fastapi_users.get_register_router(), prefix="/auth", tags=["auth"]) app.include_router( fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_verify_router(), prefix="/auth", tags=["auth"], ) app.include_router(fastapi_users.get_users_router(), prefix="/users", tags=["users"]) ``` ```python app.include_router( fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"] ) app.include_router( fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_verify_router(UserRead), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"]) ``` -------------------------------- ### Get Current User (Active or Not) Source: https://fastapi-users.github.io/fastapi-users/latest/usage/current-user Demonstrates how to get the current user, regardless of their active status. This is useful for accessing user information even if the account is inactive. ```Python current_user = fastapi_users.current_user() @app.get("/protected-route") def protected_route(user: User = Depends(current_user)): return f"Hello, {user.email}" ``` -------------------------------- ### FastAPI Users Overview Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/overview This section provides a high-level overview of the FastAPI Users library's structure and how its components fit together. It highlights key areas such as user models, database adapters, authentication backends, UserManager, schemas, and the FastAPIUsers class itself. ```Markdown # Overview The schema below shows you how the library is structured and how each part fit together. ## User model and database adapters FastAPI Users is compatible with various **databases and ORM**. To build the interface between those database tools and the library, we provide database adapters classes that you need to instantiate and configure. ➡️ I'm using SQLAlchemy ➡️ I'm using Beanie ## Authentication backends Authentication backends define the way users sessions are managed in your app, like access tokens or cookies. They are composed of two parts: a **transport** , which is how the token will be carried over the requests (e.g. cookies, headers...) and a **strategy** , which is how the token will be generated and secured (e.g. a JWT, a token in database...). ➡️ Configure the authentication backends ## `UserManager` The `UserManager` object bears most of the logic of FastAPI Users: registration, verification, password reset... We provide a `BaseUserManager` with this common logic; which you should overload to define how to validate passwords or handle events. This `UserManager` object should be provided through a FastAPI dependency, `get_user_manager`. ➡️ Configure `UserManager` ## Schemas FastAPI is heavily using Pydantic models to validate request payloads and serialize responses. **FastAPI Users** is no exception and will expect you to provide Pydantic schemas representing a user when it's read, created and updated. ➡️ Configure schemas ## `FastAPIUsers` and routers Finally, `FastAPIUsers` object is the main class from which you'll be able to generate routers for classic routes like registration or login, but also get the `current_user` dependency factory to inject the authenticated user in your own routes. ➡️ Configure `FastAPIUsers` and routers ``` -------------------------------- ### Get Current Active User Source: https://fastapi-users.github.io/fastapi-users/latest/usage/current-user Shows how to retrieve only active users. If the authenticated user is inactive, a 401 Unauthorized error will be raised. ```Python current_active_user = fastapi_users.current_user(active=True) @app.get("/protected-route") def protected_route(user: User = Depends(current_active_user)): return f"Hello, {user.email}" ``` -------------------------------- ### Login Response Example Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/authentication/transports/bearer This is an example of a successful login response when using the Bearer transport. It returns a JSON object with an access_token and token_type. ```JSON { "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI", "token_type":"bearer" } ``` -------------------------------- ### Get Current Active and Verified User Source: https://fastapi-users.github.io/fastapi-users/latest/usage/current-user Illustrates how to fetch users who are both active and verified. Users who are not verified will receive a 403 Forbidden error. ```Python current_active_verified_user = fastapi_users.current_user(active=True, verified=True) @app.get("/protected-route") def protected_route(user: User = Depends(current_active_verified_user)): return f"Hello, {user.email}" ``` -------------------------------- ### Run Unit Tests with Hatch Source: https://fastapi-users.github.io/fastapi-users/latest/index This command executes all unit tests for the project using the Hatch build and environment manager. It ensures the codebase adheres to the expected quality standards. ```bash hatch ``` -------------------------------- ### Provide Database Adapter via Dependency (Python) Source: https://fastapi-users.github.io/fastapi-users/latest/migration/7x_to_8x In FastAPI Users v8.x.x, the database adapter should be instantiated within a custom dependency, leveraging FastAPI's dependency injection system for more dynamic instance creation, rather than direct instantiation. ```python from fastapi import Depends from fastapi_users.db import SQLAlchemyUserDatabase def get_user_db(): # Assuming you have a SQLAlchemy session setup yield SQLAlchemyUserDatabase(session, User) # Usage in FastAPIUsers initialization: # fastapi_users = FastAPIUsers(get_user_db, ...) ``` -------------------------------- ### Get Authenticated User Profile (axios) Source: https://fastapi-users.github.io/fastapi-users/latest/usage/flow This JavaScript code snippet uses axios to make a GET request to the /users/me endpoint. It includes an Authorization header with a Bearer token to authenticate the request and retrieve the user's profile data. ```javascript const TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGZkMzQ3N2ItZWNjZi00ZWUzLThmN2QtNjhhZDcyMjYxNDc2IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4NDI5fQ.anO3JR8-WYCozZ4_2-PQ2Ov9O38RaLP2RAzQIiZhteM'; axios.get( 'http://localhost:8000/users/me',{ headers:{ 'Authorization':`Bearer ${TOKEN}`, }, }) .then((response)=>console.log(response)) .catch((error)=>console.log(error)); ``` -------------------------------- ### FastAPI Users Manager and Authentication Backend Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example Configures the UserManager, JWT authentication backend, and FastAPIUsers instance. It includes handlers for user registration, password reset, and verification events. ```Python import uuid from typing import Optional from fastapi import Depends, Request from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, models from fastapi_users.authentication import ( AuthenticationBackend, BearerTransport, JWTStrategy, ) from fastapi_users.db import SQLAlchemyUserDatabase from app.db import User, get_user_db SECRET = "SECRET" class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]): reset_password_token_secret = SECRET verification_token_secret = SECRET async def on_after_register(self, user: User, request: Optional[Request] = None): print(f"User {user.id} has registered.") async def on_after_forgot_password( self, user: User, token: str, request: Optional[Request] = None ): print(f"User {user.id} has forgot their password. Reset token: {token}") async def on_after_request_verify( self, user: User, token: str, request: Optional[Request] = None ): print(f"Verification requested for user {user.id}. Verification token: {token}") def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)): yield UserManager(user_db) bearer_transport = BearerTransport(tokenUrl="auth/jwt/login") def get_jwt_strategy() -> JWTStrategy[models.UP, models.ID]: return JWTStrategy(secret=SECRET, lifetime_seconds=3600) auth_backend = AuthenticationBackend( name="jwt", transport=bearer_transport, get_strategy=get_jwt_strategy, ) fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend]) current_active_user = fastapi_users.current_user(active=True) ``` -------------------------------- ### Run Uvicorn Server Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example A simple Python script to run the FastAPI application using Uvicorn. It specifies the application module and host for the server. ```Python import uvicorn if __name__ == "__main__": uvicorn.run("app.app:app", host="0.0.0.0", log_level="info") ``` -------------------------------- ### Get User by ID Source: https://fastapi-users.github.io/fastapi-users/latest/usage/routes Retrieves a specific user by their ID. Requires authentication and authorization (superuser status). Returns 404 if the user is not found. ```python GET /{user_id} Responses: `200 OK` ```json { "id":"57cbb51a-ab71-4009-8802-3f54b4f2e23", "email":"king.arthur@camelot.bt", "is_active":true, "is_superuser":false } ``` `401 Unauthorized`: Missing token or inactive user. `403 Forbidden`: Not a superuser. `404 Not found`: The user does not exist. ``` -------------------------------- ### Run FastAPI Application with Uvicorn Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example A Python script to run the FastAPI application using Uvicorn. It specifies the application module and host for the server. ```Python import uvicorn if __name__ == "__main__": uvicorn.run("app.app:app", host="0.0.0.0", log_level="info") ``` -------------------------------- ### Get Current User Source: https://fastapi-users.github.io/fastapi-users/latest/usage/routes Retrieves the details of the currently authenticated active user. Returns a 401 Unauthorized error if the token is missing or the user is inactive. ```python GET /me Responses: `200 OK` ```json { "id":"57cbb51a-ab71-4009-8802-3f54b4f2e23", "email":"king.arthur@camelot.bt", "is_active":true, "is_superuser":false } ``` `401 Unauthorized`: Missing token or inactive user. ``` -------------------------------- ### Authenticate with Bearer Token Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/authentication/transports/bearer This example demonstrates how to make an authenticated request using the Bearer token in the Authorization header. The token is prefixed with 'Bearer '. ```Bash curl'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI' ``` -------------------------------- ### FastAPI Application Setup with Beanie Lifespan Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/oauth This Python code sets up a FastAPI application, including integrating Beanie ODM for database initialization via an async context manager lifespan. It includes routers for authentication, user management, and an OAuth flow with Google. ```python from contextlib import asynccontextmanager from beanie import init_beanie from fastapi import Depends, FastAPI from app.db import User, db from app.schemas import UserCreate, UserRead, UserUpdate from app.users import ( SECRET, auth_backend, current_active_user, fastapi_users, google_oauth_client, ) @asynccontextmanager async def lifespan(app: FastAPI): await init_beanie( database=db, document_models=[ User, ], ) yield app = FastAPI(lifespan=lifespan) app.include_router( fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"] ) app.include_router( fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_verify_router(UserRead), prefix="/auth", tags=["auth"], ) app.include_router( fastapi_users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"], ) app.include_router( fastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET), prefix="/auth/google", tags=["auth"], ) @app.get("/authenticated-route") async def authenticated_route(user: User = Depends(current_active_user)): return {"message": f"Hello {user.email}!"} ``` -------------------------------- ### Update SQLAlchemy Dependency Source: https://fastapi-users.github.io/fastapi-users/latest/migration/9x_to_10x This snippet shows the change in the FastAPI Users SQLAlchemy dependency from `fastapi-users[sqlalchemy2]` to `fastapi-users[sqlalchemy]` for version 10.x.x. ```Python fastapi-users[sqlalchemy2] uvicorn[standard] aiosqlite ``` ```Python fastapi-users[sqlalchemy] uvicorn[standard] aiosqlite ``` -------------------------------- ### Remove authentication_backend from /authorize URL (Bash) Source: https://fastapi-users.github.io/fastapi-users/latest/migration/8x_to_9x Demonstrates the change in the `/authorize` endpoint for OAuth. In v9, the `authentication_backend` query parameter is no longer required. ```Bash curl\ -H"Content-Type: application/json"\ -X\ http://localhost:8000/auth/google/authorize?authentication_backend=jwt ``` ```Bash curl\ -H"Content-Type: application/json"\ -X\ http://localhost:8000/auth/google/authorize ``` -------------------------------- ### SQLAlchemy Database Configuration Source: https://fastapi-users.github.io/fastapi-users/latest/configuration/full-example Defines the SQLAlchemy database models, including the User table inheriting from SQLAlchemyBaseUserTableUUID, and sets up asynchronous database sessions using SQLite. ```Python from collections.abc import AsyncGenerator from fastapi import Depends from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase DATABASE_URL = "sqlite+aiosqlite:///./test.db" class Base(DeclarativeBase): pass class User(SQLAlchemyBaseUserTableUUID, Base): pass engine = create_async_engine(DATABASE_URL) async_session_maker = async_sessionmaker(engine, expire_on_commit=False) async def create_db_and_tables(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def get_async_session() -> AsyncGenerator[AsyncSession, None]: async with async_session_maker() as session: yield session async def get_user_db(session: AsyncSession = Depends(get_async_session)): yield SQLAlchemyUserDatabase(session, User) ``` -------------------------------- ### JWT Authentication Strategy Example Source: https://fastapi-users.github.io/fastapi-users/latest/index This Python code snippet shows how to configure a JWT authentication strategy for FastAPI Users. It involves creating a JWTStrategy instance with a secret key. ```python from fastapi_users.authentication import JWTStrategy SECRET = "your-secret-key" def get_jwt_strategy() -> JWTStrategy: return JWTStrategy(secret=SECRET, lifetime_seconds=3600) ```