Skip to content

Latest commit

 

History

History
228 lines (146 loc) · 8.8 KB

File metadata and controls

228 lines (146 loc) · 8.8 KB

EazySkool — API Documentation & Microservices Roadmap

This file documents the current API surface (v1), database models inferred from your code, security and validation recommendations, caching & scaling strategies, and a practical roadmap for migrating the project to a microservices architecture in the future.


Table of contents

  1. API Base & Routing Summary
  2. Authentication & Session Flow
  3. Endpoints (detailed)
  4. Database Models (inferred)
  5. Validation, Error Handling & Best Practices
  6. Security Notes & Immediate Fixes
  7. Caching & Scaling (Redis, PM2, Nginx)
  8. Microservices Roadmap (how microservices will perform)
  9. Migration Plan — Monolith → Microservices (practical steps)
  10. Appendix: Example Docker / K8s snippets & OpenAPI starter

API Base & Routing Summary

API base (implicit in app): / (server-rendered EJS views)

Key routes observed in code:

  • GET / — Landing page (EJS)
  • GET /about — About page
  • POST /create — Create user (Student or Teacher)
  • GET /login, POST /login — Login flow
  • GET /signup — Render signup page
  • GET /dashboard — Role-based redirect to student/teacher dashboard
  • GET /teacher-dashboard — Teacher landing
  • GET /student-dashboard — Student landing
  • GET /teacher-dashboard/students — List students
  • GET /teacher-dashboard/students/add (form)
  • POST /teacher-dashboard/students/add — Create student (requires an existing user of role Student)
  • GET /teacher-dashboard/students/edit/:id, POST /teacher-dashboard/students/update/:id — Update student
  • GET /teacher-dashboard/students/delete/:id — Delete student (and associated subject marks)
  • GET /teacher-dashboard/students/subjects/:id, POST /teacher-dashboard/students/subjects/:id — Add marks
  • GET /teacher-dashboard/students/view-marks/:email — View marks for a student
  • GET /logout — Clear token & render landing

Most routes are server-rendered (EJS). A future REST API design should expose JSON endpoints (e.g., /api/v1/...) that follow the patterns below.


Authentication & Session Flow

Current behaviour (from code):

  • Users are created via POST /create with bcrypt-hashed password.
  • JWT tokens are signed with a hard-coded secret ('SECRET_KEY') and set as a cookie: res.cookie('token', token).
  • isLoggedIn middleware verifies req.cookies.token using jwt.verify and attaches decoded payload to req.user.
  • Role authorization uses authorizeRole(role) to check req.user.role.

Endpoints (detailed)

Below are example JSON-style endpoints you should add (or mirror) alongside the EJS views for future API clients.

Auth

  • POST /api/v1/auth/register — Register (Admin/Teacher/Student)
  • POST /api/v1/auth/login — Login (returns JWT in httpOnly cookie or as response token)
  • POST /api/v1/auth/logout — Logout (clears cookie)
  • GET /api/v1/auth/me — Get profile for logged-in user

Users

  • GET /api/v1/users/ — (Admin) list users
  • GET /api/v1/users/:id — get user
  • PUT /api/v1/users/:id — update user
  • DELETE /api/v1/users/:id — delete user

Students

  • POST /api/v1/students — create student profile (teacher/admin)
  • GET /api/v1/students — list students
  • GET /api/v1/students/:id — get student
  • PUT /api/v1/students/:id — update student
  • DELETE /api/v1/students/:id — delete student

Marks / Subjects

  • POST /api/v1/marks — create marks
  • GET /api/v1/marks/student/:studentId — get marks for a student
  • PUT /api/v1/marks/:id — update marks
  • DELETE /api/v1/marks/:id — delete marks

Files

  • POST /api/v1/files/upload — upload profile pictures (use dedicated file-service later)
  • GET /uploads/:filename — static (already served)

Example success response format (JSON):

{ "success": true, "data": { /* resource */ } }

Example error format:

{ "success": false, "error": "ValidationError", "message": "Email is required" }

Database Models (inferred)

From the code you provided, you have Mongoose models roughly shaped as follows.

User (collection: users)

{ _id, username, email, password, role, createdAt, updatedAt }
  • role values used: 'Student', 'Teacher'.

Student (collection: students)

{ _id, name, Class, rollno, dob, email, phone, address, profilePicture }
  • Student email links to User.email and is used as the joining key in the current monolith.

Subject / Marks (collection: subjects)

{ _id, email, science, maths, socialscience, english, TotalMarks }
  • This model stores marks keyed by student email.

Notes: using email as the linking field is workable now, but a more robust design uses ObjectId references (i.e., studentId: ObjectId) to avoid inconsistencies when email changes.


Caching & Scaling (Redis, PM2, Nginx)

Caching (Redis)

  • Cache frequently read but rarely updated endpoints: students list, teacher dashboard stats, static assets.
  • Cache invalidation points: clear cache when student is created/updated/deleted or marks change.
  • Use redis (node-redis) and patterns such as GET -> CACHE check -> DB fetch -> SETEX.

Horizontal scaling

  • Run multiple Node.js instances using pm2 cluster mode or container replicas behind a load balancer.
  • Use an external session/cookie store (JWT reduces server session state but Redis can be used for token blacklisting if required).

Load balancing

  • Nginx or cloud load balancer (AWS ALB, GCP LB) in front of Node instances. Example Nginx upstream config included in appendix.

Microservices Roadmap (how microservices will perform)

Below is a practical microservices decomposition and how each service will behave and interact. The goal: scale teams, improve reliability, and enable independent deploys.

Target service boundaries

  1. API Gateway / Edge

    • Public entry point for clients (web/mobile).
    • Responsibilities: TLS termination, rate-limiting, JWT verification (optional), routing to internal services, authentication proxy, static content caching, request logging.
    • Implementation ideas: Nginx + Kong/Traefik/Express Gateway or a managed API Gateway.
  2. Auth Service (auth-service)

    • Responsibilities: registration, login, token issuance, refresh tokens, logout, password resets.
    • Owns user credentials and authentication policies.
    • Exposes: /auth/login, /auth/register, /auth/refresh, /auth/logout.
    • Persists: user credentials (hashed), refresh tokens (if used).
  3. User Service (user-service)

    • Responsibilities: user profiles (non-credential data), role assignment, profile updates.
    • Owns user profile data (name, email, profilePicture metadata).
  4. Student Service (student-service)

    • Responsibilities: student domain objects (class, roll no, contact info), list/search students, student CRUD.
    • Persists student records.
  5. Marks / Subject Service (marks-service)

    • Responsibilities: storing and computing marks, totals, grade calculations, exam periods.
    • Provides endpoints for teacher to add marks and students/teachers to query marks.
  6. File Service / Media Service (file-service)

    • Responsibilities: receive uploads, run validations, generate thumbnails, store files in S3/GCS, return signed URLs.
    • Offloads heavy file I/O from app services.
  7. Reporting / Analytics Service (optional)

    • Responsibilities: aggregated statistics, top performers, historical reports; can be eventually powered by a read-optimized store.
  8. Notification Service (optional)

    • Responsibilities: email/sms/push notifications; asynchronous worker using message queue.

Communication patterns & data flow

  • Synchronous HTTP for request/response APIs (gateway → service). Keep payloads small and use API contracts (OpenAPI) per service.
  • Asynchronous events via message broker (RabbitMQ / Kafka) for eventual consistency and decoupling. Example events:
    • UserCreated → student-service subscribes to create student profile skeleton.
    • MarksUpdated → reporting-service updates aggregates, cache invalidation messages.
    • StudentDeleted → marks-service and file-service purge related data.

Data ownership

  • Each microservice owns its own database/schema. No shared DB. To get user profile with marks, orchestrate in gateway or via aggregator service.

Authentication

  • Auth-service issues JWT access tokens (short-lived) and refresh tokens (longer