How briiel/gcorg_apiv1 works
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: blockDirectBrowserAccess.js Security stack · services Services · server.js Server · authController.js Auth domain
Components 26
Runtime boundary
HTTP entrypoints and request/response hardening around the API.
- Server · Starts the API and wires middleware, routes, and background tasks.
src/server.js - Security stack · Blocks direct browser access, applies security headers, rate limiting, CORS, body parsing, and transport encryption.
src/middleware/blockDirectBrowserAccess.js - Auth guard · Validates JWTs and attaches authenticated user context.
src/middleware/authMiddleware.js - Role checks · Enforces RBAC and may consult the database for fresh permissions.
src/middleware/checkRole.js - Secure response · Encrypts outbound API responses before they leave the server.
src/middleware/secureResponse.js
Application layers
Classic routes → controllers → services flow.
- API routes · Defines the REST surface and composes per-route middleware.
src/routes - Controllers · Thin request handlers that translate HTTP into service calls.
src/controllers - Services · Coordinates workflows, validation, and multi-step operations.
src/services - Auth domain · Registration, login, token verification, and privacy-policy acceptance.
src/controllers/authController.js - Users domain · User lookup, profile access, and membership-related operations.
src/controllers/userController.js - Events domain · Event lifecycle, registration, attendance, trash, restore, and deletion.
src/controllers/eventController.js - Evaluations · Feedback submission and retrieval, with certificate-triggering behavior.
src/controllers/evaluationController.js - Certificates · Certificate requests, approvals, status changes, and retrieval.
src/controllers/certificateRequestController.js - Role requests · Role upgrade requests and organization membership checks.
src/controllers/roleRequestController.js - Admin domain · OSWS admin management and elevated approval/fetch flows.
src/controllers/adminController.js - Notifications · Fetches notifications and updates read state.
src/controllers/notificationController.js - Archive · Restoration and purge flows for soft-deleted entities.
src/controllers/archiveController.js - Metrics · Public visit counter and lightweight operational telemetry.
src/routes/metricsRoutes.js
Data and persistence
MySQL models, connection handling, and encryption at rest.
- MySQL pool · mysql2 connection pool with retry behavior and strict env validation.
src/config/db.js - Models · Query-centric persistence for users, events, roles, admin, archive, notifications, evaluations, and certificates.
src/models - Field encryption · 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 · In-memory upload processing, image handling, and Cloudinary integration with fallback storage behavior.
src/middleware/uploadMiddleware.js - Certificate render · Canvas-based certificate generation using layout assets.
src/utils/certificateGenerator.js - Notify engine · Notification templates, reminder workflows, and outbound messaging coordination.
src/services/notificationService.js - Cleanup jobs · Periodic reminder sweeps, auto-cleanup, and cron-triggered maintenance.
src/services/autoCleanupService.js - Ops scripts · Encryption tests, migrations, sample certificate generation, and database checks.
src/scripts
Connections 20
- 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.