Skip to content

About

Production-grade authentication & authorization microservice for an online cinema platform. FastAPI + PostgreSQL + Redis with JWT (access/refresh), RBAC roles/permissions, TOTP MFA, Yandex OAuth (Authlib), Redis leaky-bucket rate limiting, and OpenTelemetry → Jaeger tracing. Containerized with Docker; includes pre-commit and pytest.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

65 Commits

Folders and files

Repository files navigation

🎬 Cinema Auth Service — FastAPI, JWT, RBAC, OAuth, MFA

Python FastAPI PostgreSQL Redis Docker OpenTelemetry Lint Type%20Checking Security License

A production‑ready authentication & authorization microservice for an online cinema platform. Built with FastAPI, PostgreSQL, and Redis; features JWT (access/refresh), RBAC roles/permissions, TOTP MFA, OAuth (Yandex example), rate limiting (leaky bucket), and OpenTelemetry tracing exported to Jaeger. Containerized with Docker.

Why use this? It’s a clean, modern async stack (Python 3.12, SQLAlchemy 2.0, Pydantic v2) with observability, security hardening, and strong DX (pre-commit, mypy, Ruff, Bandit).


Table of Contents


Features

  • 🔐 JWT-based auth: access/refresh tokens, blacklist on logout.
  • 👥 RBAC: roles, user-role mapping, permission checks, caching in Redis.
  • 🔑 OAuth: Yandex provider example using authlib (easily extensible).
  • 🔒 MFA: TOTP enable/verify flows.
  • 🚦 Rate limiting: Redis leaky bucket with role-aware config per traffic type.
  • 🧾 Login history: partitioned by date for scalable reads/writes.
  • 📈 Tracing: OpenTelemetry → Jaeger (FastAPI, SQLAlchemy, Redis, HTTPX instrumented).
  • 🧰 DX: pre-commit (Ruff, mypy, Bandit, detect-secrets), pytest, mypy settings.
  • 🐳 Dockerized: docker-compose ships Postgres, Redis, Jaeger, and the app.

Architecture

flowchart LR
    A[Client / Frontend] -->|JWT / Cookies| B(FastAPI App)
    subgraph Service
        B --> C[AuthService]
        C --> D[(PostgreSQL)]
        C --> E[(Redis)]
        B --> F[RateLimiter]
        B --> G[OAuth Providers]
    end
    B --> H[[OpenTelemetry]]
    H --> I[Jaeger UI]
Loading
  • FastAPI app exposes /api/v1 routes for auth and RBAC.
  • PostgreSQL stores users, roles, user_role mappings, login history (partitioned).
  • Redis caches permissions, stores token blacklist & rate-limiter buckets.
  • OpenTelemetry exports traces to Jaeger (UI on http://localhost:16686).

Project Layout

auth_service/
├─ app/
│  ├─ api/v1/routes/         # auth.py, roles.py
│  ├─ core/                  # logging, tracing, security, oauth, deps
│  ├─ db/                    # async session factory
│  ├─ models/                # SQLAlchemy models
│  ├─ schemas/               # Pydantic v2 schemas
│  ├─ services/              # AuthService, RoleService, MFA
│  ├─ utils/                 # cache, rate limiter
│  ├─ main.py                # FastAPI app factory & middlewares
│  └─ cli.py                 # CLI (create superuser)
├─ alembic/                  # migrations (init + partitioning, social accounts)
├─ docker-compose.yml        # app + postgres + redis + jaeger
├─ Dockerfile                # multi-stage, non-root user
├─ requirements.txt          # pinned deps
└─ tests/                    # pytest (e.g., test_register.py)

Getting Started

Prerequisites

  • Docker & Docker Compose
  • (Optional) Python 3.12 + virtualenv

Configuration

Copy and edit the example environment file:

cp auth_service/.env.exm auth_service/.env
# Fill in DB creds, JWT secrets (>= 16 chars), Redis URL, session secret, OAuth keys

Key variables (see app/settings.py for details):

  • DATABASE_URL (async) / TEST_DATABASE_URL
  • JWT_SECRET_KEY, JWT_REFRESH_SECRET_KEY, JWT_ALGORITHM
  • REDIS_URL
  • SESSION_SECRET_KEY
  • FRONTEND_URL
  • YANDEX_CLIENT_ID, YANDEX_CLIENT_SECRET, YANDEX_CALLBACK_URL
  • Tracing: JAEGER_ENDPOINT (defaults to http://jaeger:4318/v1/traces)

Run with Docker

From the auth_service directory:

docker compose build auth-service
docker compose up -d db redis jaeger
docker compose up -d auth-service
docker compose ps
# App health endpoint:
curl http://localhost:8000/health

On container start, the entrypoint runs alembic upgrade head automatically.

Database Migrations

Initial migration (autogenerate) – if you need to (for local dev only):

docker compose run --rm --entrypoint bash auth-service -c   "alembic -c /app/alembic.ini revision --autogenerate -m 'Create initial tables'"
docker compose down && docker compose up -d

Partition login_history by login_at (range partitions):

docker compose run --rm --entrypoint bash auth-service -c   "alembic -c /app/alembic.ini revision --autogenerate -m 'Partition login_history by login_at'"
# Edit the generated migration to add the DDL (see alembic/migration_create_login_history_partitions.py)
docker compose run --rm --entrypoint bash auth-service -c   "alembic -c /app/alembic.ini upgrade head"
docker compose up -d auth-service

Create a Superuser (CLI)

# Interactive prompts for username/password
docker compose run --rm auth-service python -m app.cli create-superuser

API Docs

  • Swagger UI: http://localhost:8000/api/v1/docs
  • ReDoc: http://localhost:8000/api/v1/redoc
  • OpenAPI: http://localhost:8000/api/v1/openapi.json

API Overview

Auth Endpoints

/api/v1/auth

  • POST /register — create new user.
  • POST /login — exchange credentials for access/refresh tokens.
  • POST /refresh — rotate refresh → new access + refresh.
  • POST /logout — invalidate the provided refresh token (blacklist).
  • POST /logout_all_other_sessions — keep current session, invalidate the rest.
  • GET /history — login history for current user.
  • GET /{{provider}}/login — redirect to OAuth provider (e.g., yandex).
  • GET /{{provider}}/callback — OAuth callback → issue local tokens.

Example: Login

curl -X POST http://localhost:8000/api/v1/auth/login   -H "Content-Type: application/json"   -d '{"login":"demo","password":"secret"}'

Use Authorization: Bearer <access_token> for protected routes.

Roles & Permissions

/api/v1/roles

  • POST / — create role (name, permissions[]).
  • GET / — list roles.
  • GET /{{role_id}} — get role by id.
  • PUT /{{role_id}} — update role.
  • DELETE /{{role_id}} — delete role.
  • POST /{{role_id}}/assign/{{user_id}} — assign role to user.
  • DELETE /{{role_id}}/revoke/{{user_id}} — revoke role from user.
  • GET /{{user_id}}/permissions — list effective permissions for user.

Permission checks use a cached set in Redis; superusers implicitly have * (all).

Security & Rate Limiting

  • Passwords hashed with bcrypt via Passlib.
  • JWTs signed with HS256; refresh & access secrets are separate.
  • Refresh-token rotation with blacklist (Redis) on logout.
  • Leaky bucket rate limiting in Redis with role-aware config per traffic type (default, login, register). See app/settings.py → rate_limit_config.

Observability

  • OpenTelemetry instrumentation for FastAPI, SQLAlchemy, Redis, HTTPX.
  • Exporter → Jaeger (Collector OTLP HTTP enabled).
  • Jaeger UI at http://localhost:16686.

Testing & Quality

# Run tests
pytest -q

# Type-check
mypy

# Lint & format
ruff check --fix
ruff format

# Pre-commit (recommended)
pre-commit install
pre-commit run --all-files

Development

Local (without Docker), e.g. for quick hacking:

python -m venv .venv && source .venv/bin/activate
pip install -r auth_service/requirements.txt
export $(grep -v '^#' auth_service/.env | xargs)  # or use python-dotenv
uvicorn app.main:app --host 0.0.0.0 --port 8000

Changelog

See Changelog.md for notable changes (e.g., tracing, partitions, rate limiting).

License

No license specified. If you intend to open source this project, add a LICENSE file (e.g., MIT).


Acknowledgements

  • FastAPI, SQLAlchemy, Pydantic
  • OpenTelemetry & Jaeger
  • Redis & PostgreSQL

About

Production-grade authentication & authorization microservice for an online cinema platform. FastAPI + PostgreSQL + Redis with JWT (access/refresh), RBAC roles/permissions, TOTP MFA, Yandex OAuth (Authlib), Redis leaky-bucket rate limiting, and OpenTelemetry → Jaeger tracing. Containerized with Docker; includes pre-commit and pytest.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages