Skip to content

Architecture and Design

Rajesh Mani edited this page Sep 13, 2026 · 1 revision

StudentAppBackend Banner

Architecture & System Design


1. Architectural Overview

StudentAppBackend implements a Clean Layered Architecture powered by Vapor 4 and Swift 6's native structured concurrency. High throughput and resilience are achieved by decoupling transport logic (REST and GraphQL) from business domains and persistence tiers.

graph TD
    subgraph Ingress["Ingress & Transport"]
        HTTP[Incoming HTTP/HTTPS Request]
        Middleware[Security Middleware Stack]
    end

    subgraph Presentation["Presentation Layer"]
        Controllers[Route Collections / Controllers]
        GraphQL[GraphQL Schema & Resolvers]
    end

    subgraph Domain["Business & Domain Layer"]
        AuthSvc[AuthorizationService]
        TokenSvc[TokenService]
        StudentSvc[StudentService]
        EmailSvc[SendGridEmailService]
    end

    subgraph DataAccess["Data Access Layer"]
        Fluent[Fluent ORM Engine]
        PostgresDriver[FluentPostgresDriver]
    end

    subgraph Storage["Storage Tier"]
        DB[(PostgreSQL 16 Database)]
    end

    HTTP --> Middleware --> Controllers & GraphQL
    Controllers --> AuthSvc & TokenSvc & StudentSvc & EmailSvc
    GraphQL --> AuthSvc & TokenSvc & StudentSvc
    AuthSvc & TokenSvc & StudentSvc --> Fluent
    Fluent --> PostgresDriver --> DB
Loading

2. Ingress & Security Middleware Pipeline

Requests entering the application pass through an ordered pipeline of non-blocking Swift-NIO middlewares configured in configure.swift:

  1. SecurityHeadersMiddleware (Positioned at .beginning):
    • Injected ahead of ErrorMiddleware to ensure security headers are attached to all responses, including 4xx and 5xx error payloads.
    • HSTS (Strict-Transport-Security): Enforces max-age=2592000 (30 days default) over HTTPS or trusted reverse-proxy connections (X-Forwarded-Proto).
    • Content Security: Emits X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and browser anti-XSS protections.
  2. CORSMiddleware:
    • Strict origin validation against ALLOWED_ORIGIN.
    • Rejects wildcard * origins in production environments to prevent cross-site credential leakage.
  3. RateLimiterMiddleware:
    • In-memory token-bucket rate limiting protecting public endpoints (/auth/login, /auth/signup/*) against brute-force attacks and volumetric credential stuffing.

3. Presentation Layer Boundaries

The codebase maintains strict separation between HTTP protocol handling and application logic:

  • Thin Controllers:
    • AuthController: Handles routing for signup, login, OTP recovery, and logout. Contains zero inline business logic; delegates input validation to ValidationUtilities and orchestration to services.
    • StudentController: Handles student profile access. Enforces resource authorization policies via AuthorizationService before attempting database lookups.
    • HealthController: Exposes GET /health/live (process liveness) and GET /health/ready (executes SELECT 1 against PostgreSQL).
  • GraphQL Engine:
    • registerGraphQLRoutes: Mounts POST /graphql and conditional GET /graphiql.
    • Schema defined via Graphiti, compiling typed Swift structs into standard GraphQL types.

4. Domain & Service Layer

All core business operations and authorization policies are centralized within reusable singleton services in Sources/StudentAppBackend/Services/:

AuthorizationService

Enforces Role-Based Access Control (RBAC) and prevents Insecure Direct Object References (IDOR):

  • canAccessStudentRecord(requester:targetStudentID:):
    • admin / principal / teacher: Authorized to access any student record.
    • student: Strictly restricted to accessing their own UUID (requester.id == targetStudentID).
  • filterAccessibleStudents(requester:allStudents:): Scopes collection queries dynamically based on caller privileges.

TokenService

Manages JWT lifecycles, cryptographically signed with HMAC-SHA256:

  • signAccessToken(for:on:): Generates JWTs containing user ID, role, and expiration timestamp.
  • authenticateStudent(from:): Parses Authorization: Bearer <token>, validates cryptographic signature, and checks the database token blacklist.
  • revokeToken(_:on:): Stores the JWT identifier (JTI) or token hash in revoked_tokens to block token reuse before natural expiration.

StudentService

Encapsulates user lifecycle operations:

  • Manages bcrypt password hashing (Bcrypt.hash(...)).
  • Normalizes country codes and phone numbers into canonical E.164 strings.
  • Maps database unique constraint violations (23505 in PostgreSQL) into clean HTTP 409 Conflict domain errors.

5. Persistence Tier & Data Modeling

The database tier is modeled with Fluent ORM entities running on PostgreSQL 16:

erDiagram
    STUDENT ||--o{ PASSWORD_RESET_TOKEN : "requests"
    STUDENT {
        UUID id PK
        string firstName
        string lastName
        string name
        string email UK
        string passwordHash
        string role
        string status
        string countryCode
        string contactNumber UK
        timestamp dob
        timestamp createdAt
        timestamp updatedAt
    }

    PASSWORD_RESET_TOKEN {
        UUID id PK
        string email FK
        string code
        timestamp codeExpiresAt
        boolean verified
        string sessionToken
        timestamp sessionExpiresAt
        int attempts
        boolean used
        timestamp createdAt
    }

    REVOKED_TOKEN {
        UUID id PK
        string tokenHash UK
        timestamp expiresAt
        timestamp createdAt
    }
Loading
  • Student: Represents user accounts with first-class role (student, teacher, principal, admin), account status (active, suspended, pending), and unique contact details.
  • PasswordResetToken: Tracks 6-digit verification codes, ephemeral session tokens, expiry timestamps, and brute-force attempt counters.
  • RevokedToken: Real-time token blacklist for invalidated JWTs.