How eljoamy/backed_security_with_csrf works
Project type and purpose
• This is a standalone, containerized backend API built with FastAPI.
• Its primary purpose is to provide secure user-management endpoints (register, login, logout, profile, token refresh) with robust JWT-based authentication/authorization, CSRF protection, login throttling, and secure file upload.
File structure
• Top-level:
• app.py: entry point, instantiates FastAPI, mounts routers and middleware
• Dockerfile.backend_security + docker-compose.yml: container definitions
• .env.example: environment configuration
• db/init.sql: initial SQL schema for the relational database
• src/:
• config/: loading .env, CORS, DB connection
• middleware/: global request/response interceptors (CSRF, sessions, error handling)
• models/: SQLAlchemy ORM classes for user, login attempts, revoked tokens
• routes/api/v1/: HTTP handlers mapping to service calls
• schema/: Pydantic request/response definitions and examples
• security/: JWT creation/validation, security dependencies
• services/: core business logic (registration, login, profile update, refresh tokens)
• utils/: shared helpers (validators, logger, password handler, login attempt counter)
• Support files: requirements.txt, split_models.py, invalid_email_domains.txt
Key insights from README
• Emphasizes security features: HTTP-only cookies, CSRF tokens, JWT expiration & revocation, login limits, safe file uploads.
• Shows the intended layered architecture: routers → services → models/DB.
• Mentions containerization and interactive Swagger UI.
Main components and their relationships
A. API Layer (FastAPI Endpoints)
• login, logout, register, profile, token_refresh
• Defined in src/routes/api/v1/*.py
• Receives HTTP requests from clients (web/mobile/third-party).
B. Middleware Layer
• CORS, CSRF protection, session middleware, error handler
• Applies cross-cutting concerns before/after request handling.
C. Service Layer
• login_service, register_service, profile_service, refresh_token_service
• Encapsulates business rules, validation, calls to models and utils.
D. Security Layer
• JWT handler (create, verify, revoke), CSRF token generator
• Security dependencies injected into endpoints.
E. Data Layer
• SQLAlchemy models and database session
• Tables: users, login_attempts, revoked_tokens_jti
• DB initialized via db/init.sql and managed through Docker Compose (mysql/postgres container).
F. Utility Layer
• Validators (email, password), logger, file-upload checks, login attempt tracking.
Architectural patterns and principles
• Layered (Onion) Architecture: HTTP controllers → services (business) → repositories/models (data).
• Dependency Injection: FastAPI dependencies for DB sessions and security contexts.
• Separation of Concerns: clear folders for config, middleware, routes, services, models, utils.
• Stateless auth with tokens and blacklist (JTI revocation).