Repository navigation
Architecture and Design
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
Requests entering the application pass through an ordered pipeline of non-blocking Swift-NIO middlewares configured in configure.swift:
-
SecurityHeadersMiddleware(Positioned at.beginning):- Injected ahead of
ErrorMiddlewareto ensure security headers are attached to all responses, including4xxand5xxerror payloads. -
HSTS (
Strict-Transport-Security): Enforcesmax-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.
- Injected ahead of
-
CORSMiddleware:- Strict origin validation against
ALLOWED_ORIGIN. - Rejects wildcard
*origins in production environments to prevent cross-site credential leakage.
- Strict origin validation against
-
RateLimiterMiddleware:- In-memory token-bucket rate limiting protecting public endpoints (
/auth/login,/auth/signup/*) against brute-force attacks and volumetric credential stuffing.
- In-memory token-bucket rate limiting protecting public endpoints (
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 toValidationUtilitiesand orchestration to services. -
StudentController: Handles student profile access. Enforces resource authorization policies viaAuthorizationServicebefore attempting database lookups. -
HealthController: ExposesGET /health/live(process liveness) andGET /health/ready(executesSELECT 1against PostgreSQL).
-
-
GraphQL Engine:
-
registerGraphQLRoutes: MountsPOST /graphqland conditionalGET /graphiql. - Schema defined via Graphiti, compiling typed Swift structs into standard GraphQL types.
-
All core business operations and authorization policies are centralized within reusable singleton services in Sources/StudentAppBackend/Services/:
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.
Manages JWT lifecycles, cryptographically signed with HMAC-SHA256:
-
signAccessToken(for:on:): Generates JWTs containing user ID, role, and expiration timestamp. -
authenticateStudent(from:): ParsesAuthorization: Bearer <token>, validates cryptographic signature, and checks the database token blacklist. -
revokeToken(_:on:): Stores the JWT identifier (JTI) or token hash inrevoked_tokensto block token reuse before natural expiration.
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 (
23505in PostgreSQL) into clean HTTP409 Conflictdomain errors.
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
}
-
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.
