# briiel/gcorg_apiv1 architecture

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

- Interactive diagram: https://gitdiagram.com/briiel/gcorg_apiv1
- Repository: https://github.com/briiel/gcorg_apiv1

## Overview

1. **System boundary**
   - This is a Node.js/Express REST API for the GC Organize event management system.
   - It sits between an Angular frontend and a MySQL database, and also integrates with Cloudinary and email delivery.
   - The API is intentionally security-heavy: authentication, RBAC, transport encryption, field-level encryption, rate limiting, and browser access blocking are all part of the request path.

2. **Core request pipeline**
   - Incoming traffic enters `src/server.js`, then passes through security and body-processing middleware before reaching routers.
   - The main cross-cutting layers are: direct browser blocking, security headers, compression, rate limiting, CORS, JSON parsing, transport decryption, and later response encryption.
   - This means most `/api/*` calls are not plain JSON requests; they are wrapped in the hybrid transport-encryption scheme.

3. **Layered application structure**
   - The code is organized into a classic three-step backend flow: routes → controllers → services/models.
   - Routes define URL surface area and middleware composition.
   - Controllers are thin HTTP adapters.
   - Services contain business rules and coordinate multi-step operations.
   - Models hold the raw MySQL query logic.
   - This separation is consistent across auth, users, events, certificates, notifications, roles, admin, archive, and evaluations.

4. **Primary domains**
   - **Auth and user management**: registration, login, JWT verification, privacy-policy acceptance, user lookup.
   - **Event management**: create/update/list/register/attendance/status transitions/trash/restore/permanent delete.
   - **Evaluations**: event feedback submission and retrieval, with certificate-triggering behavior.
   - **Certificates**: request, approve/reject, status updates, and retrieval.
   - **Roles and organizations**: role upgrade requests and organization membership checks.
   - **Notifications**: read-state updates and fetch dispatching.
   - **Archive/trash**: restoration and purge flows for soft-deleted entities.
   - **Metrics**: public visit counters.
   - **Admin**: OSWS admin management and elevated fetch/approval flows.

5. **Security and identity model**
   - Authentication is JWT-based; `authMiddleware` validates tokens and attaches user context to requests.
   - Authorization is role-based using `checkRole`, with roles centered on `student`, `orgofficer`, and `oswsadmin`.
   - A notable detail is that some role checks are backed by a live database lookup, not just token claims, to avoid stale permissions.
   - Passwords use bcrypt, and sensitive database fields are encrypted with AES-256-GCM via `utils/encryption.js`.

6. **Transport encryption boundary**
   - The API uses hybrid RSA + AES-256-GCM encryption at the HTTP layer for `/api/*`.
   - The frontend sends an RSA-wrapped session key in `X-Session-Key`; the backend unwraps it using the RSA private key from environment config.
   - Encrypted request bodies are decrypted before controller logic runs, and JSON responses are encrypted before leaving the server.
   - This is a major architectural boundary because it affects every protected client-server interaction.

7. **Data layer and MySQL behavior**
   - The database is MySQL through `mysql2` with a small connection pool and retry logic.
   - `src/config/db.js` and `src/utils/dbRetry.js` indicate resilience around transient DB failures.
   - The models are query-centric rather than ORM-driven, so schema and SQL shape the application behavior closely.
   - Environment validation is strict: startup fails if required DB/security variables are missing.

8. **File and media handling**
   - Uploaded images flow through `uploadMiddleware`, which uses in-memory storage, image processing, and Cloudinary upload.
   - Event posters and proof-of-payment images are the main media types mentioned.
   - If Cloudinary is unavailable in development, the system can fall back to storing base64 data URLs, which changes storage and retrieval characteristics.
   - This makes media an external dependency rather than local disk state.

9. **Certificate generation subsystem**
   - Certificates are not just records; they are generated artifacts.
   - `certificateGenerator.js` uses canvas-based rendering with layout assets in `src/assets`.
   - The system can generate sample certificates and store/upload produced artifacts.
   - Evaluation or approval flows can trigger certificate creation, especially for OSWS events.

10. **Notifications and background automation**
   - Notification services support event-driven user messaging and read-state updates.
   - Reminder and notification template modules suggest templated outbound communication, likely via email and/or in-app notifications.
   - Background automation includes event status updates and periodic cleanup of trash.
   - In development, status updates can run on an interval; in production, an authenticated cron webhook is used instead.
   - Cleanup is scheduled nightly with `node-cron` to permanently remove aged trashed records.

11. **Operational endpoints and observability**
   - The API exposes health and metrics endpoints separately from the main protected business surface.
   - `/health` provides service liveness/uptime, while `/api/metrics/visits` is a public counter endpoint backed by the database.
   - There is also a cron-trigger endpoint secured by a shared secret rather than JWT, which is a distinct trust path from normal user traffic.

12. **Error handling and hardening**
   - Errors flow into a centralized error handler that normalizes DB, auth, validation, upload, and connectivity failures.
   - Production mode suppresses detailed 5xx messages to avoid leaking internals.
   - Additional hardening includes blocking direct browser navigation to API routes and applying custom response security headers.
   - This suggests the API is designed to be consumed by a trusted frontend, not by casual manual browsing.

13. **Utility and maintenance scripts**
   - The repository includes one-off scripts for encryption testing, data migration/encryption/decryption, certificate sample generation, database timezone checks, reminders, and notification seeding.
   - These are operational support tools rather than runtime dependencies, but they indicate the system has encrypted legacy data and periodic maintenance needs.
   - The existence of manual migration scripts also means schema evolution is controlled outside the app runtime.

14. **Architecture in one sentence**
   - Overall, this is a layered, security-first REST backend where JWT/RBAC and transport encryption guard a MySQL-centered domain model, while Cloudinary, email, certificate rendering, and scheduled jobs extend the core event-management workflow.

Main entry points: [`src/middleware/blockDirectBrowserAccess.js`](https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/blockDirectBrowserAccess.js) (Security stack), [`src/services`](https://github.com/briiel/gcorg_apiv1/tree/main/src/services) (Services), [`src/server.js`](https://github.com/briiel/gcorg_apiv1/blob/main/src/server.js) (Server), [`src/controllers/authController.js`](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/authController.js) (Auth domain)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_grp_runtime["Runtime boundary"]
  node_node_server["Server<br/>entrypoint<br/>[server.js]"]
  node_node_security["Security stack<br/>middleware"]
  node_node_authmw["Auth guard<br/>middleware<br/>[authMiddleware.js]"]
  node_node_rolemw["Role checks<br/>middleware<br/>[checkRole.js]"]
  node_node_secure_resp["Secure response<br/>middleware<br/>[secureResponse.js]"]
end

subgraph group_grp_app["Application layers"]
  node_node_routes["API routes"]
  node_node_controllers["Controllers<br/>http adapters"]
  node_node_services["Services<br/>business logic"]
  node_node_auth(("Auth domain<br/>[authController.js]"))
  node_node_users(("Users domain<br/>[userController.js]"))
  node_node_events(("Events domain<br/>[eventController.js]"))
  node_node_eval(("Evaluations<br/>domain"))
  node_node_certs(("Certificates<br/>domain"))
  node_node_roles(("Role requests<br/>domain"))
  node_node_admin(("Admin domain<br/>[adminController.js]"))
  node_node_notifications(("Notifications<br/>domain"))
  node_node_archive(("Archive<br/>domain"))
  node_node_metrics(("Metrics<br/>endpoint<br/>[metricsRoutes.js]"))
end

subgraph group_grp_data["Data and persistence"]
  node_node_db[("MySQL pool<br/>database<br/>[db.js]")]
  node_node_models["Models<br/>sql layer"]
  node_node_crypto["Field encryption<br/>crypto<br/>[encryption.js]"]
end

subgraph group_grp_support["Support systems"]
  node_node_uploads["Media upload<br/>media pipeline"]
  node_node_certgen["Certificate render<br/>artifact generator"]
  node_node_notifysvc["Notify engine<br/>automation"]
  node_node_cleanup["Cleanup jobs<br/>scheduler"]
  node_node_scripts["Ops scripts<br/>maintenance"]
end

node_node_server -->|"boots with"| node_node_security
node_node_security -->|"forwards to"| node_node_routes
node_node_routes -->|"dispatches"| node_node_controllers
node_node_controllers -->|"delegates"| node_node_services
node_node_services -->|"queries"| node_node_models
node_node_models -->|"uses"| node_node_db
node_node_security -->|"includes"| node_node_authmw
node_node_security -->|"includes"| node_node_rolemw
node_node_security -->|"includes"| node_node_secure_resp
node_node_auth -.->|"shares identity with"| node_node_users
node_node_auth -.->|"authorizes"| node_node_roles
node_node_events -->|"accepts media"| node_node_uploads
node_node_eval -.->|"triggers"| node_node_certs
node_node_certs -->|"renders"| node_node_certgen
node_node_notifications -->|"uses"| node_node_notifysvc
node_node_cleanup -.->|"scheduled by"| node_node_scripts
node_node_services -->|"encrypts fields"| node_node_crypto
node_node_server -.->|"starts jobs"| node_node_cleanup
node_node_metrics -->|"counts visits in"| node_node_db
node_node_admin -.->|"requires"| node_node_roles

click node_node_server "https://github.com/briiel/gcorg_apiv1/blob/main/src/server.js"
click node_node_security "https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/blockDirectBrowserAccess.js"
click node_node_authmw "https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/authMiddleware.js"
click node_node_rolemw "https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/checkRole.js"
click node_node_secure_resp "https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/secureResponse.js"
click node_node_routes "https://github.com/briiel/gcorg_apiv1/tree/main/src/routes"
click node_node_controllers "https://github.com/briiel/gcorg_apiv1/tree/main/src/controllers"
click node_node_services "https://github.com/briiel/gcorg_apiv1/tree/main/src/services"
click node_node_auth "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/authController.js"
click node_node_users "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/userController.js"
click node_node_events "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/eventController.js"
click node_node_eval "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/evaluationController.js"
click node_node_certs "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/certificateRequestController.js"
click node_node_roles "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/roleRequestController.js"
click node_node_admin "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/adminController.js"
click node_node_notifications "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/notificationController.js"
click node_node_archive "https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/archiveController.js"
click node_node_metrics "https://github.com/briiel/gcorg_apiv1/blob/main/src/routes/metricsRoutes.js"
click node_node_db "https://github.com/briiel/gcorg_apiv1/blob/main/src/config/db.js"
click node_node_models "https://github.com/briiel/gcorg_apiv1/tree/main/src/models"
click node_node_crypto "https://github.com/briiel/gcorg_apiv1/blob/main/src/utils/encryption.js"
click node_node_uploads "https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/uploadMiddleware.js"
click node_node_certgen "https://github.com/briiel/gcorg_apiv1/blob/main/src/utils/certificateGenerator.js"
click node_node_notifysvc "https://github.com/briiel/gcorg_apiv1/blob/main/src/services/notificationService.js"
click node_node_cleanup "https://github.com/briiel/gcorg_apiv1/blob/main/src/services/autoCleanupService.js"
click node_node_scripts "https://github.com/briiel/gcorg_apiv1/tree/main/src/scripts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_node_server,node_node_security,node_node_authmw,node_node_rolemw,node_node_secure_resp toneBlue
class node_node_routes,node_node_controllers,node_node_services,node_node_auth,node_node_users,node_node_events,node_node_eval,node_node_certs,node_node_roles,node_node_admin,node_node_notifications,node_node_archive,node_node_metrics toneAmber
class node_node_db,node_node_models,node_node_crypto toneMint
class node_node_uploads,node_node_certgen,node_node_notifysvc,node_node_cleanup,node_node_scripts toneRose
```

## Components

### Runtime boundary

HTTP entrypoints and request/response hardening around the API.

- [Server](https://github.com/briiel/gcorg_apiv1/blob/main/src/server.js): entrypoint · Starts the API and wires middleware, routes, and background tasks. · `src/server.js`
- [Security stack](https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/blockDirectBrowserAccess.js): middleware · Blocks direct browser access, applies security headers, rate limiting, CORS, body parsing, and transport encryption. · `src/middleware/blockDirectBrowserAccess.js`
- [Auth guard](https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/authMiddleware.js): middleware · Validates JWTs and attaches authenticated user context. · `src/middleware/authMiddleware.js`
- [Role checks](https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/checkRole.js): middleware · Enforces RBAC and may consult the database for fresh permissions. · `src/middleware/checkRole.js`
- [Secure response](https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/secureResponse.js): middleware · Encrypts outbound API responses before they leave the server. · `src/middleware/secureResponse.js`

### Application layers

Classic routes → controllers → services flow.

- [API routes](https://github.com/briiel/gcorg_apiv1/tree/main/src/routes): routes · Defines the REST surface and composes per-route middleware. · `src/routes`
- [Controllers](https://github.com/briiel/gcorg_apiv1/tree/main/src/controllers): http adapters · Thin request handlers that translate HTTP into service calls. · `src/controllers`
- [Services](https://github.com/briiel/gcorg_apiv1/tree/main/src/services): business logic · Coordinates workflows, validation, and multi-step operations. · `src/services`
- [Auth domain](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/authController.js): domain · Registration, login, token verification, and privacy-policy acceptance. · `src/controllers/authController.js`
- [Users domain](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/userController.js): domain · User lookup, profile access, and membership-related operations. · `src/controllers/userController.js`
- [Events domain](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/eventController.js): domain · Event lifecycle, registration, attendance, trash, restore, and deletion. · `src/controllers/eventController.js`
- [Evaluations](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/evaluationController.js): domain · Feedback submission and retrieval, with certificate-triggering behavior. · `src/controllers/evaluationController.js`
- [Certificates](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/certificateRequestController.js): domain · Certificate requests, approvals, status changes, and retrieval. · `src/controllers/certificateRequestController.js`
- [Role requests](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/roleRequestController.js): domain · Role upgrade requests and organization membership checks. · `src/controllers/roleRequestController.js`
- [Admin domain](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/adminController.js): domain · OSWS admin management and elevated approval/fetch flows. · `src/controllers/adminController.js`
- [Notifications](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/notificationController.js): domain · Fetches notifications and updates read state. · `src/controllers/notificationController.js`
- [Archive](https://github.com/briiel/gcorg_apiv1/blob/main/src/controllers/archiveController.js): domain · Restoration and purge flows for soft-deleted entities. · `src/controllers/archiveController.js`
- [Metrics](https://github.com/briiel/gcorg_apiv1/blob/main/src/routes/metricsRoutes.js): endpoint · Public visit counter and lightweight operational telemetry. · `src/routes/metricsRoutes.js`

### Data and persistence

MySQL models, connection handling, and encryption at rest.

- [MySQL pool](https://github.com/briiel/gcorg_apiv1/blob/main/src/config/db.js): database · mysql2 connection pool with retry behavior and strict env validation. · `src/config/db.js`
- [Models](https://github.com/briiel/gcorg_apiv1/tree/main/src/models): sql layer · Query-centric persistence for users, events, roles, admin, archive, notifications, evaluations, and certificates. · `src/models`
- [Field encryption](https://github.com/briiel/gcorg_apiv1/blob/main/src/utils/encryption.js): crypto · AES-256-GCM utilities for sensitive database fields and legacy data migration. · `src/utils/encryption.js`

### Support systems

Uploads, certificates, notifications, scheduled jobs, and scripts.

- [Media upload](https://github.com/briiel/gcorg_apiv1/blob/main/src/middleware/uploadMiddleware.js): media pipeline · In-memory upload processing, image handling, and Cloudinary integration with fallback storage behavior. · `src/middleware/uploadMiddleware.js`
- [Certificate render](https://github.com/briiel/gcorg_apiv1/blob/main/src/utils/certificateGenerator.js): artifact generator · Canvas-based certificate generation using layout assets. · `src/utils/certificateGenerator.js`
- [Notify engine](https://github.com/briiel/gcorg_apiv1/blob/main/src/services/notificationService.js): automation · Notification templates, reminder workflows, and outbound messaging coordination. · `src/services/notificationService.js`
- [Cleanup jobs](https://github.com/briiel/gcorg_apiv1/blob/main/src/services/autoCleanupService.js): scheduler · Periodic reminder sweeps, auto-cleanup, and cron-triggered maintenance. · `src/services/autoCleanupService.js`
- [Ops scripts](https://github.com/briiel/gcorg_apiv1/tree/main/src/scripts): maintenance · Encryption tests, migrations, sample certificate generation, and database checks. · `src/scripts`

## Connections

- Server → Security stack: boots with · Requests enter the hardened middleware chain.
- Security stack → API routes: forwards to · Protected API traffic reaches route handlers after transport and header processing.
- API routes → Controllers: dispatches · Routes bind URL surfaces to controllers.
- Controllers → Services: delegates · HTTP adapters hand off domain work to services.
- Services → Models: queries · Business logic reads and writes through query-centric models.
- Models → MySQL pool: uses · Models execute SQL through the MySQL pool.
- Security stack → Auth guard: includes · JWT validation is part of the request path.
- Security stack → Role checks: includes · RBAC checks gate privileged routes.
- Security stack → Secure response: includes · Responses are encrypted before leaving the server.
- Auth domain → Users domain: shares identity with · Authenticated user context feeds user-facing operations.
- Auth domain → Role requests: authorizes · Role-sensitive flows depend on auth state and permissions.
- Events domain → Media upload: accepts media · Event posters and proof images flow through upload handling.
- Evaluations → Certificates: triggers · Evaluations can lead to certificate generation or status changes.
- Certificates → Certificate render: renders · Certificates are produced as generated artifacts.
- Notifications → Notify engine: uses · Notification APIs are backed by notification services and templates.
- Cleanup jobs → Ops scripts: scheduled by · Background maintenance and reminder sweeps are also represented in ops scripts.
- Services → Field encryption: encrypts fields · Sensitive data is protected at rest with AES-GCM utilities.
- Server → Cleanup jobs: starts jobs · The server process also initializes scheduled automation.
- Metrics → MySQL pool: counts visits in · Public metrics are stored in the database.
- Admin domain → Role requests: requires · Elevated admin operations depend on role enforcement.
