# eljoamy/backed_security_with_csrf architecture

> Architecture diagram of the GitHub repository eljoamy/backed_security_with_csrf, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-14). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/eljoamy/backed_security_with_csrf
- Repository: https://github.com/eljoamy/backed_security_with_csrf

## Overview

##### 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).

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% External Clients
    Client["Client (Browser/Mobile)"]:::external
    SwaggerUI["Swagger UI (/docs)"]:::external
    OAuth2["OAuth2 Providers\n(Google/GitHub)"]:::external

    %% Database Container
    DBContainer["Relational DB Container"]:::db

    %% FastAPI Service Container
    subgraph "FastAPI Service" 
        direction TB

        subgraph "Configuration Layer"
            direction TB
            Config["Config Loader"]:::config
            CORS["CORS Settings"]:::config
            DBConfig["DB Connection"]:::config
            EnvExample[".env.example"]:::config
        end

        subgraph "Middleware Layer"
            direction TB
            CSRF["CSRF Protection"]:::middleware
            Session["Session Management"]:::middleware
            ErrorHandler["Global Error Handling"]:::middleware
        end

        subgraph "API Layer"
            direction TB
            LoginEP["POST /login"]:::api
            LogoutEP["POST /logout"]:::api
            RegisterEP["POST /register"]:::api
            ProfileEP["GET/PUT /profile"]:::api
            RefreshEP["POST /token/refresh"]:::api
        end

        subgraph "Service Layer"
            direction TB
            LoginSvc["Login Service"]:::service
            RegisterSvc["Register Service"]:::service
            ProfileSvc["Profile Service"]:::service
            RefreshSvc["Refresh Token Service"]:::service
        end

        subgraph "Security Layer"
            direction TB
            JWTHandler["JWT Handler"]:::security
            SecDeps["Security Dependencies"]:::security
        end

        subgraph "Data Layer"
            direction TB
            UserModel["User ORM Model"]:::data
            LoginAttemptModel["Login Attempt Model"]:::data
            RevokedTokenModel["Revoked Token JTI Model"]:::data
            InitSQL["init.sql"]:::data
        end

        subgraph "Utility Layer"
            direction TB
            Validators["Validators"]:::util
            PwdHandler["Password Handler"]:::util
            LoginAttemptHandler["Login Attempt Tracker"]:::util
            Logger["Logger"]:::util
            InvalidEmailList["Invalid Email Domains"]:::util
        end

        ProfileDeps["Profile Dependencies"]:::dependency
    end

    %% Connections
    Client -->|"HTTP(S) w/CSRF & Cookies"| CSRF
    CSRF --> Session
    Session --> ErrorHandler
    ErrorHandler --> LoginEP
    ErrorHandler --> LogoutEP
    ErrorHandler --> RegisterEP
    ErrorHandler --> ProfileEP
    ErrorHandler --> RefreshEP

    SwaggerUI --> LoginEP
    Client --> SwaggerUI

    LoginEP -->|"calls"| LoginSvc
    LogoutEP -->|"calls"| RefreshSvc
    RegisterEP -->|"calls"| RegisterSvc
    ProfileEP -->|"calls"| ProfileSvc
    RefreshEP -->|"calls"| RefreshSvc

    LoginSvc -->|"uses"| JWTHandler
    ProfileSvc -->|"injects"| SecDeps
    RefreshSvc -->|"uses"| JWTHandler
    LoginSvc -->|"checks"| LoginAttemptHandler
    RegisterSvc -->|"validates"| Validators
    ProfileSvc -->|"hashes"| PwdHandler

    LoginSvc --> UserModel
    RegisterSvc --> UserModel
    ProfileSvc --> UserModel
    RefreshSvc --> RevokedTokenModel
    LoginSvc --> LoginAttemptModel

    UserModel -->|SQL| DBContainer
    LoginAttemptModel -->|SQL| DBContainer
    RevokedTokenModel -->|SQL| DBContainer
    InitSQL -->|DB Init| DBContainer

    OAuth2 --- RegisterEP

    %% Click Events
    click Config "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/config/config.py"
    click CORS "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/config/cors_config.py"
    click DBConfig "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/config/db_config.py"
    click EnvExample "https://github.com/eljoamy/backed_security_with_csrf/blob/main/.env.example"
    click CSRF "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/middleware/csrf_middleware.PY"
    click Session "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/middleware/session_middleware.py"
    click ErrorHandler "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/middleware/error_handler.py"
    click LoginEP "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/routes/api/v1/login.py"
    click LogoutEP "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/routes/api/v1/logout.py"
    click RegisterEP "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/routes/api/v1/register.py"
    click ProfileEP "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/routes/api/v1/profile.py"
    click RefreshEP "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/routes/api/v1/token_refresh.py"
    click LoginSvc "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/services/login_service.py"
    click RegisterSvc "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/services/register_service.py"
    click ProfileSvc "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/services/profile_service.py"
    click RefreshSvc "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/services/refresh_token_service.py"
    click JWTHandler "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/security/jwt_handler.py"
    click SecDeps "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/security/dependencies.py"
    click UserModel "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/models/user_model.py"
    click LoginAttemptModel "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/models/login_attempt_model.py"
    click RevokedTokenModel "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/models/revoked_token_jti_model.py"
    click InitSQL "https://github.com/eljoamy/backed_security_with_csrf/blob/main/db/init.sql"
    click Validators "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/utils/validators.py"
    click PwdHandler "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/utils/password_handler.py"
    click LoginAttemptHandler "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/utils/login_attempt_handler.py"
    click Logger "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/utils/logger.py"
    click InvalidEmailList "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/utils/invalid_email_domains.txt"
    click ProfileDeps "https://github.com/eljoamy/backed_security_with_csrf/blob/main/src/dependencies/profile_dependencies.py"

    %% Styles
    classDef external fill:#f9f,stroke:#333,stroke-width:1px
    classDef db fill:#bbf,stroke:#333,stroke-width:1px,stroke-dasharray: 5 5
    classDef config fill:#cff,stroke:#333,stroke-width:1px
    classDef middleware fill:#fcf,stroke:#333,stroke-width:1px
    classDef api fill:#cfc,stroke:#333,stroke-width:1px
    classDef service fill:#ffc,stroke:#333,stroke-width:1px
    classDef security fill:#fdd,stroke:#333,stroke-width:1px
    classDef data fill:#ddf,stroke:#333,stroke-width:1px
    classDef util fill:#efe,stroke:#333,stroke-width:1px
    classDef dependency fill:#ffd,stroke:#333,stroke-width:1px
```
