3.2 KiB

User Authentication Service

A FastAPI-based user authentication service with JWT token authentication.

Features

  • User registration and login
  • JWT-based authentication
  • Password hashing with bcrypt
  • SQLite database with SQLAlchemy ORM
  • Alembic migrations
  • Protected routes with OAuth2 dependencies
  • Health check endpoint

Project Structure

.
├── alembic.ini
├── app
│   ├── api
│   │   ├── deps.py
│   │   ├── endpoints
│   │   │   ├── auth.py
│   │   │   ├── health.py
│   │   │   └── users.py
│   │   └── routes.py
│   ├── core
│   │   ├── config.py
│   │   └── security.py
│   ├── crud
│   │   ├── base.py
│   │   └── user.py
│   ├── db
│   │   ├── base.py
│   │   ├── base_class.py
│   │   └── session.py
│   ├── models
│   │   └── user.py
│   ├── schemas
│   │   ├── token.py
│   │   └── user.py
│   └── utils
├── main.py
├── migrations
│   ├── env.py
│   └── versions
│       └── 0001_create_users_table.py
└── requirements.txt

Setup

  1. Clone the repository:
git clone <repository-url>
cd userauthenticationservice
  1. Create a virtual environment and install dependencies:
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt
  1. Set up environment variables:

Create a .env file in the root directory with the following content:

SECRET_KEY=your-secret-key
ACCESS_TOKEN_EXPIRE_MINUTES=10080  # 7 days
  1. Run database migrations:
alembic upgrade head
  1. Run the application:
uvicorn main:app --reload

API Endpoints

Authentication

  • POST /auth/register: Register a new user

    • Request: { "email": "user@example.com", "username": "username", "password": "password" }
    • Response: User object
  • POST /auth/login: Login and get access token

    • Request: Form data with username (email) and password
    • Response: { "access_token": "token", "token_type": "bearer" }

Users

  • GET /users/me: Get current user details (requires authentication)

    • Response: User object
  • PUT /users/me: Update current user details (requires authentication)

    • Request: { "email": "new-email@example.com", "username": "new-username", "password": "new-password" }
    • Response: Updated user object

Health Check

  • GET /health: Check API health
    • Response: { "status": "healthy", "database": "healthy" }

Authentication

The API uses JWT tokens for authentication. To access protected endpoints, include the token in the Authorization header:

Authorization: Bearer <your-token>

Database

The application uses SQLite as the database, with the file stored at /app/storage/db/db.sqlite. SQLAlchemy is used as the ORM, and Alembic for database migrations.

Environment Variables

  • SECRET_KEY: Secret key used for JWT token generation
  • ACCESS_TOKEN_EXPIRE_MINUTES: Token expiration time in minutes (default: 10080 - 7 days)
  • BACKEND_CORS_ORIGINS: List of allowed CORS origins (default: "*")