Skip to main content

Fast and secure OAuth2 authentication module for FastAPI with email verification

Project description

oauth2fast-fastapi

๐Ÿ” Fast and secure OAuth2 authentication module for FastAPI with email verification and JWT tokens

[!WARNING] Internal Use Notice

This package is designed and maintained by the Solautyc Team for internal use. While it is publicly available, it may not work as expected in all environments or use cases outside of our specific infrastructure. We do not provide support or guarantees for external usage, and we are not responsible for any issues that may arise from using this package in other contexts.

Use at your own risk. Contributions and feedback are welcome, but compatibility with external environments is not guaranteed.

Features

  • ๐Ÿ” Complete OAuth2 Implementation: Full OAuth2 password flow with JWT tokens
  • ๐Ÿ“ง Email Verification: Built-in email verification system with customizable templates
  • ๐Ÿ‘ค User Management: Ready-to-use user registration, login, and profile endpoints
  • ๐Ÿ—„๏ธ SQLModel Integration: Async PostgreSQL support with SQLModel/SQLAlchemy
  • ๐Ÿ”‘ Secure Password Hashing: Argon2 password hashing (winner of Password Hashing Competition)
  • ๐ŸŽฏ FastAPI Dependencies: Easy-to-use dependencies for protected routes
  • โšก Async/Await: Full async support for high performance
  • ๐ŸŽจ Customizable: Extend the User model with your own fields
  • ๐Ÿ“ Type-Safe Configuration: Pydantic settings with environment variables
  • ๐Ÿ”„ Email Templates: Jinja2 templates for verification and welcome emails

Installation

From PyPI (Recommended)

pip install oauth2fast-fastapi

From Source

# Clone the repository
git clone https://github.com/AngelDanielSanchezCastillo/oauth2fast-fastapi.git
cd oauth2fast-fastapi

# Install in development mode
pip install -e .

# Or install with dev dependencies
pip install -e ".[dev]"

Quick Start

1. Configure Environment Variables

Create a .env file in your project root:

# Required JWT Configuration
SECRET_KEY=your-super-secret-key-change-this-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60

# Database Configuration
DB_DEFAULT_CONNECTION=auth
DB_CONNECTIONS__AUTH__HOST=localhost
DB_CONNECTIONS__AUTH__PORT=5432
DB_CONNECTIONS__AUTH__USERNAME=postgres
DB_CONNECTIONS__AUTH__PASSWORD=yourpassword
DB_CONNECTIONS__AUTH__DATABASE=myapp_db

# Mail Server Configuration
MAIL_DEFAULT_ACCOUNT=auth
MAIL_SMTP_ACCOUNTS__AUTH__HOST=smtp.gmail.com
MAIL_SMTP_ACCOUNTS__AUTH__PORT=587
MAIL_SMTP_ACCOUNTS__AUTH__USERNAME="noreply@yourapp.com"
MAIL_SMTP_ACCOUNTS__AUTH__PASSWORD="your-smtp-password"
MAIL_SMTP_ACCOUNTS__AUTH__SECURITY=tls
MAIL_SMTP_ACCOUNTS__AUTH__FROM_EMAIL="noreply@yourapp.com"
MAIL_SMTP_ACCOUNTS__AUTH__FROM_NAME="Your pp"
MAIL_SMTP_ACCOUNTS__AUTH__REPLY_TO="reply@yourapp.com"
MAIL_SMTP_ACCOUNTS__AUTH__TIMEOUT=60

# Application Settings
PROJECT_NAME=My App
FRONTEND_URL=https://yourapp.com
AUTH_URL_PREFIX=auth

[!IMPORTANT] The SECRET_KEY is required and must be set in your .env file. Generate a secure key:

python -c "import secrets; print(secrets.token_urlsafe(32))"

2. Basic FastAPI Integration

from fastapi import FastAPI, Depends
from oauth2fast_fastapi import router, engine, get_current_user, User
from sqlmodel import SQLModel

app = FastAPI()

# Include authentication router
app.include_router(router, prefix="/auth", tags=["Authentication"])

@app.on_event("startup")
async def startup():
    # Create database tables
    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)

@app.get("/profile")
async def get_profile(current_user: User = Depends(get_current_user)):
    return {
        "email": current_user.email,
        "name": f"{current_user.first_name} {current_user.last_name}",
        "verified": current_user.is_verified
    }

3. Authentication Flow

Register a new user:

POST /auth/users/register
{
  "email": "user@example.com",
  "password": "SecurePassword123",
  "first_name": "John",
  "last_name": "Doe"
}

Verify email:

POST /auth/users/verify-email
{
  "token": "verification-token-from-email"
}

Login:

POST /auth/token
Content-Type: application/x-www-form-urlencoded

username=user@example.com&password=SecurePassword123

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}

Access protected endpoint:

GET /profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Protected Endpoints

Use the provided dependencies to protect your endpoints:

from fastapi import Depends
from oauth2fast_fastapi import get_current_user, get_current_verified_user, User

# Requires authentication only
@app.get("/dashboard")
async def dashboard(user: User = Depends(get_current_user)):
    return {"message": f"Welcome {user.email}"}

# Requires authentication AND email verification
@app.get("/premium")
async def premium_feature(user: User = Depends(get_current_verified_user)):
    return {"message": "Access granted to verified users only"}

Custom User Model

Extend the base User model with your own fields:

from oauth2fast_fastapi.models.user_model import User as BaseUser
from sqlmodel import Field

class CustomUser(BaseUser, table=True):
    __tablename__ = "custom_users"
    
    phone_number: str | None = Field(default=None)
    company: str | None = Field(default=None)
    role: str = Field(default="user")

Available Endpoints

The authentication router provides the following endpoints:

  • POST /auth/users/register - Register a new user
  • POST /auth/users/verify-email - Verify email with token
  • POST /auth/users/resend-verification - Resend verification email
  • POST /auth/token - Login and get JWT token
  • GET /auth/users/me - Get current user profile
  • PUT /auth/users/me - Update current user profile

Configuration Reference

All configuration is done via environment variables with nested delimiter __.

JWT Settings (Required)

  • SECRET_KEY - Required: Secret key for JWT signing
  • ALGORITHM - Default: "HS256": JWT algorithm
  • ACCESS_TOKEN_EXPIRE_MINUTES - Default: 60: Token expiration time in minutes

Database Settings

  • AUTH_DB__USERNAME - Database username
  • AUTH_DB__PASSWORD - Database password
  • AUTH_DB__HOSTNAME - Database host
  • AUTH_DB__NAME - Database name
  • AUTH_DB__PORT - Database port (default: 5432)

Mail Settings

  • AUTH_MAIL_SERVER__USERNAME - SMTP username
  • AUTH_MAIL_SERVER__PASSWORD - SMTP password
  • AUTH_MAIL_SERVER__SERVER - SMTP server
  • AUTH_MAIL_SERVER__PORT - SMTP port
  • AUTH_MAIL_SERVER__FROM_DIRECTION - From email address
  • AUTH_MAIL_SERVER__FROM_NAME - From name
  • AUTH_MAIL_SERVER__STARTTLS - Use STARTTLS (default: false)
  • AUTH_MAIL_SERVER__SSL_TLS - Use SSL/TLS (default: true)

Application Settings

  • PROJECT_NAME - Application name (used in emails)
  • FRONTEND_URL - Frontend URL (for email links)
  • AUTH_URL_PREFIX - Auth router prefix (default: "auth")

๐Ÿ“š Documentation

๐Ÿ“‹ Naming Conventions

This package follows consistent naming conventions for models and database tables:

Model Classes (Python)

  • Singular PascalCase
  • Examples: User, Role, Permission, Tenant

Database Tables

  • Plural snake_case
  • Examples: users, roles, permissions, tenants

Many-to-Many Join Tables

  • Plural snake_case on both table names
  • Alphabetical order of the two table names
  • Examples: role_users (r < u), permission_roles (p < r), tenant_users (t < u)

Mapping Tables (Multi-tenancy)

  • In Auth DB: TenantUser class โ†’ tenant_users table (maps users โ†” tenants)
  • In Tenant DB: User class โ†’ users table (local tenant user profile)

Generic Categories

  • Use Category for generic categorization (not PermissionCategory)
  • Can be reused across different entity types (roles, permissions, products, etc.)

๐Ÿ“ Module Structure

oauth2fast-fastapi/
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ MANIFEST.in
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ oauth2fast_fastapi/
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ __version__.py
โ”‚       โ”œโ”€โ”€ settings.py          # Pydantic settings
โ”‚       โ”œโ”€โ”€ database.py          # Database engine
โ”‚       โ”œโ”€โ”€ dependencies.py      # FastAPI dependencies
โ”‚       โ”œโ”€โ”€ models/
โ”‚       โ”‚   โ”œโ”€โ”€ bases.py         # Base models
โ”‚       โ”‚   โ”œโ”€โ”€ mixins.py        # Model mixins
โ”‚       โ”‚   โ””โ”€โ”€ user_model.py    # User model
โ”‚       โ”œโ”€โ”€ routers/
โ”‚       โ”‚   โ”œโ”€โ”€ base_router.py   # Main router
โ”‚       โ”‚   โ””โ”€โ”€ users_router.py  # User endpoints
โ”‚       โ”œโ”€โ”€ schemas/
โ”‚       โ”‚   โ”œโ”€โ”€ token_schema.py  # JWT schemas
โ”‚       โ”‚   โ”œโ”€โ”€ user_schema.py   # User schemas
โ”‚       โ”‚   โ””โ”€โ”€ verification_schema.py
โ”‚       โ”œโ”€โ”€ utils/
โ”‚       โ”‚   โ”œโ”€โ”€ password_utils.py    # Password hashing
โ”‚       โ”‚   โ”œโ”€โ”€ token_utils.py       # JWT utilities
โ”‚       โ”‚   โ””โ”€โ”€ verification_utils.py
โ”‚       โ””โ”€โ”€ mail/
โ”‚           โ”œโ”€โ”€ connection.py    # SMTP connection
โ”‚           โ”œโ”€โ”€ service.py       # Email service
โ”‚           โ””โ”€โ”€ templates/       # Email templates
โ”‚               โ”œโ”€โ”€ verification.html
โ”‚               โ””โ”€โ”€ welcome.html
โ”œโ”€โ”€ docs/
โ”‚   โ”œโ”€โ”€ env.example
โ”‚   โ””โ”€โ”€ usage.md
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ basic_usage.py
โ”‚   โ”œโ”€โ”€ custom_user.py
โ”‚   โ””โ”€โ”€ complete_flow.py
โ””โ”€โ”€ tests/

Dependencies

This module depends on:

We are grateful to the maintainers and contributors of these projects.

Security Features

  • ๐Ÿ”’ Argon2 Password Hashing: Uses Argon2, the winner of the Password Hashing Competition
  • ๐ŸŽซ JWT Tokens: Secure token-based authentication
  • โœ‰๏ธ Email Verification: Prevents fake account creation
  • ๐Ÿ” Secure Defaults: Sensible security defaults out of the box
  • ๐Ÿ›ก๏ธ SQL Injection Protection: SQLModel/SQLAlchemy ORM prevents SQL injection

License

This project is licensed under the MIT License - see the LICENSE file for details.

Copyright (c) 2026 Angel Daniel Sanchez Castillo

Note: This package is designed and maintained by the Solautyc Team for internal use. While publicly available under MIT license, use at your own risk.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and questions, please use the GitHub Issues page.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

oauth2fast_fastapi-0.4.2.tar.gz (27.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

oauth2fast_fastapi-0.4.2-py3-none-any.whl (25.0 kB view details)

Uploaded Python 3

File details

Details for the file oauth2fast_fastapi-0.4.2.tar.gz.

File metadata

  • Download URL: oauth2fast_fastapi-0.4.2.tar.gz
  • Upload date:
  • Size: 27.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for oauth2fast_fastapi-0.4.2.tar.gz
Algorithm Hash digest
SHA256 d1ad5f1286cafa44e2107411cfc1d078da487ff59829f366aa537884d854f45a
MD5 4ae1a9e8fdc2296bba7c741808bf30dc
BLAKE2b-256 9b925632fb863deaa8633574614a99308b7a5c1d5e59213461931e26b3fff74b

See more details on using hashes here.

File details

Details for the file oauth2fast_fastapi-0.4.2-py3-none-any.whl.

File metadata

File hashes

Hashes for oauth2fast_fastapi-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 06fcd91dddd558424d6abcb86541179fff8b8c1067edb49e8e05daa770468583
MD5 ea96e0f3fd6f4fe4fa68a8ccfa5edc95
BLAKE2b-256 592362c5dc183e95057237627057d4cbb4a1d2f0534866f9d1c7cb86ee2aa23f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page