Skip to content

MinKhantt/fastapi_auth

Repository files navigation

FastAPI Auth API

Production-ready FastAPI Authentication & Authorization API

This project provides a robust and scalable authentication and authorization API built with FastAPI. It's designed to be a solid foundation for applications requiring secure user management, JWT-based authentication, and social logins (Google OAuth2).

Live Deployment

The application is currently deployed and live on Render.com:

Features

  • User Authentication: Secure user registration, email/password login, and JSON Web Token (JWT) based authentication with access and refresh tokens.
  • Social Login: Seamless integration with Google OAuth2 for user authentication.
  • User Authorization: Role-based access control, distinguishing between regular users and superusers for administrative privileges.
  • User Management: Comprehensive CRUD operations for user accounts, with appropriate access restrictions.
  • Database Management: Utilizes PostgreSQL with SQLAlchemy (ORM) and Alembic for efficient and version-controlled database migrations.
  • API Documentation: Automatic generation of interactive OpenAPI (Swagger UI) and ReDoc documentation, including authentication flows.
  • Configuration: Centralized and flexible configuration using pydantic-settings to manage environment variables from a .env file.
  • Security: Implements Argon2 for strong password hashing and python-jose for secure JWT handling.
  • Health Check: A dedicated /health endpoint for monitoring application status.

Technologies

  • Web Framework: FastAPI
  • ASGI Server: Uvicorn
  • Database: PostgreSQL
  • ORM/Migrations: SQLAlchemy, Alembic
  • Authentication: JWT (python-jose), Argon2 (password hashing), Authlib (OAuth), itsdangerous
  • Data Validation/Settings: Pydantic, pydantic-settings, python-dotenv
  • HTTP Client: httpx
  • Package Manager: uv

Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

Prerequisites

  • Python 3.12+
  • Docker (if using Docker Compose for local development)

Installation

Docker Compose (Recommended for Local Development)

The easiest way to get the project running locally is using Docker Compose, which sets up the database and the FastAPI application.

  1. Clone the repository:

    git clone https://github.com/MinKhantt/fastapi_auth.git # Replace with your actual repository URL
    cd fastapi_auth
  2. Create a .env file: Copy the .env.example (or refer to app/core/config.py) and fill in the necessary environment variables. Essential variables include:

    • SECRET_KEY: A strong secret key for JWT signing.
    • DATABASE_URL: PostgreSQL connection string (e.g., postgresql+psycopg://user:password@db:5432/dbname).
    • GOOGLE_CLIENT_ID: Your Google OAuth client ID.
    • GOOGLE_CLIENT_SECRET: Your Google OAuth client secret.
    • FIRST_SUPERUSER_EMAIL: Email for the initial superuser account.
    • FIRST_SUPERUSER_PASSWORD: Password for the initial superuser account.

    Refer to .env.example for a template and further details.

  3. Start the services:

    docker-compose up --build

    This command will:

    • Build the Docker images.
    • Start the PostgreSQL database container.
    • Run Alembic database migrations.
    • Start the FastAPI application.
    • Create an initial superuser if FIRST_SUPERUSER_EMAIL does not already exist in the database.

    The API will be accessible at http://localhost:8000.

Local Development (without Docker Compose)

If you prefer to run the application directly on your host machine without Docker Compose:

  1. Clone the repository:
    git clone https://github.com/MinKhantt/fastapi_auth.git # Replace with your actual repository URL
    cd fastapi_auth
  2. Create a .env file: Similar to the Docker Compose setup, create a .env file based on app/core/config.py and fill in your environment variables. Ensure DATABASE_URL points to a running PostgreSQL instance (e.g., postgresql+psycopg://user:password@localhost:5432/dbname).
  3. Install uv (if not already installed):
    pip install uv
  4. Create a virtual environment and install dependencies:
    uv venv
    source .venv/bin/activate  # On Windows, use `.venv\Scripts\activate`
    uv sync
  5. Run database migrations: Make sure your PostgreSQL database is running and accessible via the DATABASE_URL in your .env file.
    uv run alembic upgrade head
  6. Start the application:
    uv run uvicorn app.main:app --reload
    The API will be accessible at http://localhost:8000.

Deployment to Render.com

This project can be deployed to Render.com as a Python Web Service.

  1. Render PostgreSQL Database: Create a PostgreSQL database service on Render. Copy its Internal Database URL.
  2. Render Web Service: Create a new Web Service on Render, linking it to your GitHub repository.
    • Runtime: Python
    • Build Command:
      uv sync --frozen && python -m pip install alembic && alembic upgrade head
    • Start Command:
      uv run uvicorn app.main:app --host 0.0.0.0 --port $PORT
    • Environment Variables: Configure all necessary environment variables in the Render UI, including:
      • DATABASE_URL: Set to postgresql+asyncpg:// + your Internal Database URL details.
      • SYNC_DATABASE_URL: Set to postgresql+psycopg2:// + your Internal Database URL details.
      • SECRET_KEY, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI (update with your Render service URL), FIRST_SUPERUSER_EMAIL, FIRST_SUPERUSER_PASSWORD, etc.
  3. Update Google OAuth Credentials: In the Google Cloud Console, update the Authorized redirect URI for your OAuth client to match your deployed Render service URL (e.g., https://fastapi-auth-sppx.onrender.com/api/v1/auth/google/callback).

API Endpoints

The API exposes the following primary endpoints:

  • Authentication (/api/v1/auth):
    • POST /register: Register a new user.
    • POST /login: Authenticate a user with email and password, returning JWT tokens.
    • POST /refresh: Refresh an expired access token using a refresh token.
    • GET /me: Retrieve details of the currently authenticated user.
    • GET /google/login: Initiate Google OAuth2 login flow.
    • GET /google/callback: Handle the Google OAuth2 callback.
  • User Management (/api/v1/users):
    • GET /: Retrieve a list of all users (superuser only).
    • POST /: Create a new user (superuser only).
    • GET /{user_id}: Retrieve details of a specific user.
    • PUT /{user_id}: Update details of a specific user (superuser only).
    • DELETE /{user_id}: Delete a specific user (superuser only).
  • Health Check:
    • GET /health: Check the application's health status.
  • Root:
    • GET /: Basic welcome message.

Most protected endpoints require a JWT Bearer token in the Authorization header (Authorization: Bearer <your_token>).

Documentation

Interactive API documentation is automatically generated and available at:

  • Swagger UI: https://fastapi-auth-sppx.onrender.com/docs (or http://localhost:8000/docs for local)
  • ReDoc: https://fastapi-auth-sppx.onrender.com/redoc (or http://localhost:8000/redoc for local)

Contributing

Contributions are welcome! Please feel free to open issues or submit pull requests.

License

This project is licensed under the MIT License - see the LICENSE file for details. (Note: A LICENSE file should be added if not present).

About

Production-ready FastAPI authentication and authorization API with JWT, refresh tokens, Google OAuth2 and user management. Deployed live on Render.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors