Mentray Docs Overview
✦ Official Documentation v1.0

The Complete University LMS.

Mentray is an enterprise-grade, AI-powered Learning Management System for universities, colleges, and coaching institutes — covering students, faculty, classrooms, content, assessments, fees, and analytics in one unified platform.

⚡ React 18 + Vite 5 🔧 11 Microservices 🤖 GPT-4 Integration 🐳 Docker + Kubernetes 📱 PWA — Offline Ready 🎓 Multi-Role Access 💳 Fee Management 🏫 Classroom Management
25+Pages
11Services
50+Endpoints
5Roles
25+Modules
15K+Lines

A Complete University LMS Platform

Mentray is a full-stack university management system — covering every role from student and faculty to admin staff and parents. Manage courses, classrooms, timetables, assignments, fees, quizzes, and analytics from a single platform.

🎓

Student Management

Full student lifecycle — enrollment, profiles, progress tracking, achievements, subscriptions, and parent linkage.

👩‍🏫

Faculty & Staff

Teacher portals, role-based access for staff, classroom assignment, timetable management, and AI tools.

🏫

Classroom Management

Virtual classrooms with timetables, assignments, announcements, and parent communication portals.

💳

Fee Management

Fee overview, payment tracking, subscription plans, and Razorpay/Stripe payment gateway integration.

📚

Course Content (LMS)

Hierarchical content: Subject → Division → Topic → Card → Tab (Text, Video, PDF, Audio, Quiz).

🤖

AI-Powered Tools

GPT-4 MCQ generation, handwriting OCR for answer evaluation, AI timetable builder, and student risk analysis.

🏛️
Built for Universities & Institutes Mentray supports multi-tenant deployments for universities, colleges, and coaching institutes — with 5 distinct user roles: Admin, Content Manager, Teacher, Student, and Parent. Each role gets a purpose-built interface with scoped permissions.

Quick Start Guide

Get Mentray running locally in under 10 minutes using Docker Compose.

Prerequisites

Node.js ≥ 18 Docker & Compose PostgreSQL 15+ MongoDB 7+ Python 3.11+ RabbitMQ 3

1 — Clone & Install

bash
# Clone the repository
git clone https://github.com/mentray/platform.git
cd platform

# Install root dependencies
npm install

# Copy environment files for all services
cp services/api-gateway/.env.example services/api-gateway/.env
cp services/auth-service/.env.example services/auth-service/.env
cp services/content-service/.env.example services/content-service/.env
# Repeat for remaining services…

2 — Start with Docker

bash
# Start all infrastructure + services
docker-compose up -d

# Tail logs
docker-compose logs -f

# Stop everything
docker-compose down

3 — Access Services

ServiceURLDescription
Frontend Apphttp://localhost:5173React PWA
API Gatewayhttp://localhost:3000Main API entry point
Auth Servicehttp://localhost:3001JWT Authentication
Content Servicehttp://localhost:3003LMS Content
Quiz Servicehttp://localhost:3004MCQ Quizzes
Analytics Servicehttp://localhost:3005Performance analytics
OCR AI Servicehttp://localhost:5001Handwriting OCR
MCQ Generatorhttp://localhost:5002AI question generation
RabbitMQ UIhttp://localhost:15672Message queue dashboard
MinIO Consolehttp://localhost:9001Object storage

4 — Seed Sample Data

bash
# Run database migrations
npm run migrate

# Seed sample university content & users
node seed-lms.js

# Default admin credentials
Email:    admin@mentray.com
Password: Admin@1234
⚠️
Change Default Credentials Always update the default admin password and all .env secrets before deploying to production.

Tech Stack

Mentray is built on a modern, production-grade technology stack carefully chosen for scalability, developer experience, and performance.

Frontend

⚛️

React 18

Component-based UI with concurrent rendering, Suspense, and React Router v6.

Vite 5

Lightning-fast builds, HMR, and optimized production bundles with code splitting.

🎨

Material-UI v7

Enterprise component library with theming, responsive breakpoints, and accessibility.

🌊

Framer Motion

Declarative animations and gesture-driven transitions for a polished UX.

📈

Recharts

Composable charting library for analytics dashboards and performance graphs.

📱

PWA + Vite PWA

Service workers, offline support, installable app manifest, and background sync.

Backend

🟢

Node.js 18 + Express

9 backend microservices each as independent Express applications with modular routing.

🐍

Python FastAPI

2 AI/ML services (OCR + MCQ Generator) built with FastAPI for async performance.

🔐

JWT + Passport.js

Stateless authentication with access tokens, refresh tokens, and role-based guards.

📮

RabbitMQ

Event-driven messaging for cross-service communication, notifications, and async jobs.

Data Layer

🐘

PostgreSQL 15

Primary relational database — 5 isolated databases for auth, users, content, quiz, and analytics.

🍃

MongoDB 7

Document store for user activity logs, focus sessions, and flexible analytics data.

🔴

Redis 7

Session caching, rate-limit counters, real-time leaderboards, and pub/sub channels.

🗃️

MinIO

S3-compatible object storage for PDFs, videos, images, and audio content.

DevOps & Infrastructure

🐳

Docker + Compose

Full containerization for every service with multi-stage builds and health checks.

☸️

Kubernetes

Production orchestration with HPA, rolling updates, ConfigMaps, and Secrets.

📉

Prometheus + Grafana

Metrics collection, alerting rules, and real-time dashboards for all services.

System Architecture

Mentray follows an Event-Driven Microservices pattern with a single API Gateway entry point, independent service databases, and async messaging via RabbitMQ.

CLIENT LAYER
React PWA Vite + MUI + PWA
GATEWAY LAYER
API Gateway :3000 — Auth · Rate Limit · Routing
↓ ↓ ↓ ↓ ↓
MICROSERVICES LAYER
Auth:3001
User Profile:3002
Content:3003
Quiz:3004
Analytics:3005
Focus:3006
Notifications:3007
Reports:3008
OCR AI:5001 Python
MCQ Gen AI:5002 Python
DATA & MESSAGING LAYER
PostgreSQL5 Databases
MongoDBAnalytics
RedisCache & Sessions
RabbitMQEvent Bus
MinIOObject Storage

Key Architectural Decisions

🎯

Single Entry Point

All client requests go through the API Gateway, which handles auth verification, rate limiting, CORS, and intelligent routing to downstream services.

🔒

Database per Service

Each microservice owns its database — preventing tight coupling, enabling independent scaling, and simplifying fault isolation.

📨

Event-Driven Communication

Services communicate asynchronously via RabbitMQ queues for non-blocking operations like email delivery, analytics ingestion, and report generation.

📦

Stateless Services

All services are stateless — sessions stored in Redis, files in MinIO. This allows horizontal scaling behind a load balancer.

Microservices Reference

Mentray is composed of 11 independently deployable microservices — 9 in Node.js and 2 in Python.

#ServicePortRuntimeResponsibility
1API Gateway3000Node.jsAuth verification, rate limiting, routing, CORS, logging
2Auth Service3001Node.jsRegistration, login, JWT tokens, password reset, 2FA
3User Profile Service3002Node.jsProfile CRUD, avatar upload, preferences, progress tracking
4Content Service3003Node.jsSubject/Division/Topic/Card/Tab hierarchy, media management
5Quiz Service3004Node.jsQuiz management, question bank, attempt tracking, auto-grading
6Analytics Service3005Node.jsPerformance trends, blind-spot detection, risk scoring, recommendations
7Focus Service3006Node.jsPomodoro timer, session tracking, productivity scoring, daily stats
8Notification Service3007Node.jsEmail, push, and in-app notifications, scheduled reminders
9Report Service3008Node.jsPDF report generation, Excel exports, performance summaries
10OCR AI Service5001PythonHandwritten text extraction, document OCR, image preprocessing
11MCQ Generator Service5002PythonGPT-4 powered question generation, bulk MCQ creation, tagging

API Gateway — Detailed

The gateway is the single entry point for all client traffic. It performs:

  • JWT token validation on every protected route
  • Role-based access control (Admin, Content Manager, Learner)
  • Redis-backed rate limiting (configurable per route)
  • HTTP proxy routing to upstream microservices
  • Request/response logging with correlation IDs
  • Helmet.js security headers on all responses
  • CORS policy enforcement

Content Service — Data Hierarchy

tree
Subject (e.g., "Indian History")
  └── Division (e.g., "Ancient India")
        └── Topic (e.g., "Indus Valley Civilization")
              └── Card (e.g., "Key Facts")
                    └── Tab ─── Text
                           ├── Video
                           ├── PDF
                           ├── Audio
                           └── Quiz

This 5-level hierarchy enables extremely granular content organization matching any university or exam syllabus structure.

Quiz Service — Internal Components

📋 Quiz Management

  • Create / edit / publish quizzes
  • Set time limits and pass marks
  • Tag quizzes by subject, topic, difficulty
  • Shuffle questions & options

❓ Question Bank

  • Bulk import via CSV/JSON
  • AI-generated via MCQ Generator
  • Explanation & reference tagging
  • Difficulty classification (Easy/Medium/Hard)

📊 Attempt Tracking

  • Timed attempt sessions
  • Auto-submit on timeout
  • Detailed answer analysis
  • Historical attempt comparison

Database Architecture

Mentray uses a polyglot persistence strategy — choosing the right database engine for each service's access patterns.

PostgreSQL — Relational Data (5 Databases)

DatabaseServiceKey Tables
auth_dbAuth Serviceusers, refresh_tokens, password_resets, otp_verifications
users_dbUser Profileprofiles, achievements, bookmarks, study_plans, progress
content_dbContent Servicesubjects, divisions, topics, cards, tabs, media_assets
quiz_dbQuiz Servicequizzes, questions, options, attempts, answers, analytics
analytics_dbAnalytics Serviceperformance_metrics, risk_scores, subject_stats, daily_reports

MongoDB — Document Store

  • user_profiles — Extended user data, preferences, device tokens
  • activity_logs — Granular user activity for analytics processing
  • focus_sessions — Pomodoro timer sessions with productivity metadata
  • notification_logs — Delivery tracking for emails and push messages

Redis — Cache & Real-Time

  • JWT session storage with TTL expiry
  • Rate limit counters per IP / user
  • Content cache (popular topics/cards)
  • Real-time leaderboard sorted sets
  • Pub/Sub for live notifications

Authentication System

Mentray uses industry-standard JWT-based authentication with role-based access control across all microservices.

🔑

JWT Tokens

Short-lived access tokens (15 min) + long-lived refresh tokens (7 days) stored in HTTP-only cookies.

👥

Role-Based Access

Three roles: admin, content_manager, user — enforced at API Gateway and service level.

📧

Email Verification

OTP-based email verification on registration. Password reset via secure time-limited tokens.

Auth Flow

flow
1. Register  POST /api/v1/auth/register
   → Validate email uniqueness → Hash password (bcrypt 12) → Send OTP

2. Login     POST /api/v1/auth/login
   → Verify credentials → Issue access_token + refresh_token → Set cookie

3. Request   Any protected endpoint
   → Gateway extracts Bearer token → Verify signature → Attach user context

4. Refresh   POST /api/v1/auth/refresh
   → Validate refresh_token → Issue new access_token (rotation)

5. Logout    POST /api/v1/auth/logout
   → Invalidate refresh_token in DB → Clear cookies

API Endpoints

POST/api/v1/auth/registerRegister new user
POST/api/v1/auth/loginLogin & get tokens
POST/api/v1/auth/logoutInvalidate session
POST/api/v1/auth/refreshRotate access token
POST/api/v1/auth/forgot-passwordRequest reset link
POST/api/v1/auth/reset-passwordSet new password
POST/api/v1/auth/verify-emailVerify OTP

Content Management System

A fully-featured CMS with a 5-level hierarchical content model designed for any university or institute syllabus.

Content Hierarchy

📘

1. Subjects

Top-level subjects/courses defined by the institution (e.g., Mathematics, Physics, History, Computer Science, Law).

📂

2. Divisions

Major sub-divisions within each subject (e.g., Ancient India, Medieval India, Modern India within History).

📃

3. Topics

Specific syllabus topics within each division with metadata, tags, difficulty level, and PYQ linkage.

🃏

4. Cards

Individual study units — compact, focused knowledge chunks optimized for active recall and spaced repetition.

🗂️

5. Tabs

Multi-format content within each card: Text, Video, PDF, Audio, and embedded Quiz tabs.

Content Features

  • Rich text editor with markdown support for Text tabs
  • Video streaming via MinIO with adaptive quality
  • PDF viewer with annotation support
  • Audio lectures with chapter markers
  • Embedded mini-quizzes within content cards
  • Content version control — track edits and revert
  • Access control — restrict content by subscription plan
  • Search across all content with full-text indexing
  • Tag-based content discovery and cross-linking
  • Bulk import/export via CSV and JSON

CMS Admin Endpoints

GET/api/v1/content/subjectsList all subjects
POST/api/v1/content/subjectsCreate subject
GET/api/v1/content/divisionsList divisions
GET/api/v1/content/topicsList topics with filters
GET/api/v1/content/cards/:idGet card with tabs
POST/api/v1/content/cardsCreate content card
PATCH/api/v1/content/tabs/:idUpdate tab content

Quiz Engine

A full-featured MCQ quiz system with timer, auto-grading, detailed explanations, and comprehensive analytics.

⏱️

Timed Quizzes

Configurable countdown timer per quiz. Auto-submit on expiry. Time-per-question tracking for analytics.

🎯

Auto-Grading

Instant scoring on submission. Negative marking support. Percentage and rank calculation.

💡

Explanations

Detailed explanations for every answer option. Source references and related topic links.

📊

Attempt History

Complete history of all attempts with side-by-side comparison. Identify improvement trends.

🔀

Question Shuffle

Random question and option ordering on each attempt to prevent memorization of patterns.

📋

Question Banks & PYQs

Previous Year Question bank with year-wise filtering, topic tags, difficulty classification, and bulk import.

Quiz Endpoints

GET/api/v1/quizzesList available quizzes
GET/api/v1/quizzes/:idGet quiz with questions
POST/api/v1/quizzesCreate quiz (Admin)
POST/api/v1/quizzes/:id/attemptStart a quiz attempt
POST/api/v1/attempts/:id/submitSubmit answers
GET/api/v1/attempts/:id/resultGet detailed results
GET/api/v1/questionsQuestion bank (Admin)
POST/api/v1/questions/bulkBulk import questions

Analytics & AI Insights

Mentray's analytics engine tracks every study interaction and uses AI to surface personalized insights, blind spots, and action recommendations.

📈

Performance Trends

Daily, weekly, and monthly performance charts across subjects and difficulty levels.

🔍

Blind Spot Detection

AI identifies consistently weak topics across multiple quiz attempts and study sessions.

⚠️

Risk Score

Composite risk scoring per subject — combining accuracy, time-per-question, and attempt frequency.

💬

Recommendations

Personalized "What to study next" recommendations based on weak areas and exam proximity.

🏆

Leaderboards

Real-time leaderboards per batch, subject, and time period stored in Redis sorted sets.

📅

Daily Reports

Automated daily summary emails with study time, quizzes taken, and progress highlights.

AI-Driven Student Insights The Analytics Service uses a weighted scoring algorithm across accuracy rate, time efficiency, topic recency, and syllabus coverage to generate prioritised study recommendations and flag at-risk students to faculty.

Analytics Endpoints

GET/api/v1/analytics/dashboardPersonal analytics overview
GET/api/v1/analytics/performancePerformance trend data
GET/api/v1/analytics/blind-spotsWeak area detection
GET/api/v1/analytics/recommendationsStudy recommendations
GET/api/v1/analytics/leaderboardTop performers

Focus Timer & Pomodoro

Built-in Pomodoro-based focus session tracking to help students maintain structured study habits.

🍅

Pomodoro Timer

Customizable focus/break intervals (default 25/5 min). Browser notification on session completion.

📊

Session Tracking

Every session stored with subject tag, duration, and productivity rating in MongoDB.

🎯

Daily Targets

Set daily study hour targets. Visual progress ring and streak counter for motivation.

🏅

Study Streaks

Consecutive day streaks automatically tracked. Streak badges and milestone celebrations.

Preset Templates

Learners can choose from built-in presets or create custom ones:

  • Classic Pomodoro — 25 min work / 5 min break / 15 min long break every 4 cycles
  • Deep Work — 90 min focus / 20 min break for intensive revision sessions
  • Short Burst — 15 min / 3 min for quick daily revision rounds
  • Custom — Fully configurable intervals and cycle counts

Focus Service Endpoints

POST/api/v1/focus/sessions/startStart focus session
POST/api/v1/focus/sessions/:id/endEnd session with rating
GET/api/v1/focus/sessionsGet session history
GET/api/v1/focus/statsDaily/weekly stats
GET/api/v1/focus/presetsGet timer presets
POST/api/v1/focus/presetsCreate custom preset

Subscription Plans

Mentray offers four subscription tiers with role-based content access and Razorpay/Stripe payment integration.

🆓

FREE

  • Access to 2 subjects
  • 5 quizzes per month
  • Basic analytics
  • Focus timer (unlimited)

BASIC

  • All subjects access
  • 50 quizzes per month
  • Advanced analytics
  • AI recommendations
👑

PREMIUM

  • All content & quizzes
  • AI-generated quizzes
  • OCR answer evaluation
  • Mains test series
  • Mentorship sessions
  • PDF report exports
♾️

LIFETIME

  • Everything in PREMIUM
  • Lifetime platform access
  • Priority support
  • Early feature access

Subscription Endpoints

GET/api/v1/subscriptions/plansList all plans
POST/api/v1/subscriptions/subscribeSubscribe to a plan
GET/api/v1/subscriptions/myMy active subscriptions
POST/api/v1/subscriptions/my/:id/cancelCancel subscription
POST/api/v1/subscriptions/webhook/paymentPayment gateway webhook
GET/api/v1/subscriptions/statsRevenue stats (Admin)

Notification System

Multi-channel notification delivery across email, browser push, and in-app notifications.

📧

Email

Transactional emails via SMTP/SendGrid — welcome, OTP, quiz results, daily summaries.

📲

Push Notifications

Web Push API via VAPID keys for browser notifications — session reminders, streaks, achievements.

🔔

In-App

Real-time bell icon notifications in the dashboard with read/unread state via Redis pub/sub.

✈️

Telegram

Optional Telegram bot delivery for daily quiz reminders and current affairs updates.

Notification Triggers

  • Study streak reminder (daily at configurable time)
  • Quiz result notification after auto-grading
  • Subscription expiry warning (7 days, 3 days, 1 day before)
  • New content published in subscribed subjects
  • Achievement unlocked celebration
  • Scheduled exam date reminders
  • Weekly performance summary email

AI-Powered Services

Two dedicated Python FastAPI services bring machine learning and generative AI capabilities to the platform.

MCQ Generator Service (Port 5002)

🤖

GPT-4 Integration

Uses OpenAI GPT-4 to generate high-quality MCQs from topic descriptions, documents, or keywords.

📦

Bulk Generation

Generate 10–100 questions per request with difficulty distribution, subject tagging, curriculum alignment, and explanation generation.

Quality Validation

AI self-validates questions for clarity, correctness, and curriculum relevance before saving to the question bank.

json
// POST /api/v1/ai/generate-mcqs
{
  "topic": "Fundamental Rights — Article 19",
  "count": 10,
  "difficulty": "medium",
  "include_explanations": true,
  "subject_id": 3
}

OCR AI Service (Port 5001)

🔍

Handwriting Recognition

Extract text from handwritten exam answers using EasyOCR + custom preprocessing pipeline.

📄

Document OCR

Extract text from scanned PDFs and images for bulk content ingestion and searchability.

🖼️

Image Preprocessing

Noise reduction, deskewing, binarization, and contrast enhancement for improved OCR accuracy.

🚀
Handwritten Answer Evaluation The OCR service enables students to upload handwritten exam answers. Text is extracted, then evaluated by GPT-4 against model answers — scoring structure, key point coverage, and language quality with detailed feedback.

Frontend Architecture

A production-grade React PWA built with Vite 5 and Material-UI v7, targeting mobile-first responsive design.

Project Structure

tree
frontend/src/
├── components/
│   ├── layouts/          # AdminLayout, UserLayout, PublicLayout
│   ├── charts/           # Recharts wrappers
│   ├── modals/           # Reusable dialog components
│   └── shared/           # Buttons, Cards, Forms
├── pages/
│   ├── admin/            # 11 admin pages
│   ├── user/             # 15 learner pages
│   └── auth/             # Login, Register
├── hooks/                # Custom React hooks
├── contexts/             # Auth, Theme contexts
├── services/             # Axios API service layer
├── utils/                # Formatters, validators
└── theme/                # MUI theme customization

Design System

Primary #0d9488
Secondary #7c3aed
Accent #f59e0b
Success #10b981
Error #ef4444

PWA Features

  • Service Worker with Workbox for offline caching
  • Web App Manifest for home screen installation
  • Background sync for offline quiz submissions
  • Push notification subscription management
  • Lazy loading with React.Suspense + Vite code splitting
  • Production bundle: ~1.6 MB total, ~943 KB gzipped

Admin Panel

A comprehensive admin dashboard at /admin — organised into 10 sections covering every aspect of university operations.

SectionPageRouteDescription
OverviewDashboard/adminKPI cards, growth charts, recent activity
Analytics/admin/analyticsPlatform-wide metrics and user engagement
Student ManagementAll Students/admin/studentsStudent list, profiles, progress, filters
Classrooms/admin/lms/classroomsAssign students to classrooms
Faculty ManagementAll Faculty/admin/facultyTeacher profiles, subjects, status
Teachers (LMS)/admin/lms/teachersLMS-specific teacher assignments
Admin StaffStaff Members/admin/staffAdmin staff directory and roles
Assign Roles/admin/users/rolesRBAC — assign and manage user roles
Subscriptions/admin/subscriptionsAll subscriptions, revenue stats
Fees & PaymentsFee Overview/admin/feesFee collection, pending, payment history
LMS ManagementClassrooms/admin/lms/classroomsVirtual classroom management
Timetables/admin/lms/timetablesSchedule builder per class/teacher
Assignments/admin/lms/assignmentsCreate and track assignments
Parents & Links/admin/lms/parentsParent portal linking and communication
Announcements/admin/lms/announcementsBroadcast notices to classes or all
ContentAll Content/admin/contentFull content library overview
Subjects/admin/content/subjectsSubject/course management
Current Affairs/admin/current-affairsDaily news & current affairs posts
Flash Cards/admin/content/flashcardsQuick-revision flashcard management
Quizzes & TestsManage Quizzes/admin/quizzesCreate and publish quizzes
Manage Questions/admin/questionsQuestion bank CRUD
PYQs/admin/pyqPrevious year question bank
Question Banks/admin/question-banksOrganised question collections
Test Series/admin/test-series-adminScheduled test series management
Test Analytics/admin/test-analyticsBatch-level test performance reports
AI ToolsAI Prompts/admin/ai-promptsManage GPT-4 prompt templates
AI Quiz Generator/admin/lms/ai-quizAuto-generate quizzes from topics
AI Timetable/admin/lms/ai-timetableAI-assisted timetable builder
Student Analysis/admin/lms/ai-analysisAI-driven student risk analysis
AI Usage Logs/admin/lms/ai-logsToken usage and cost tracking
Website CMSPackages/admin/cms/packagesPricing package content
Page Content/admin/cms/pagesPublic website page editor
Testimonials/admin/cms/testimonialsStudent/parent testimonial management
SystemSecurity/admin/securityAudit logs, login attempts, blocked IPs
Theme/admin/themePlatform branding and colour customization
Settings/admin/settingsGlobal platform configuration
🛡️
5 User Roles — Fully Scoped Admin panel routes are protected at both the frontend router and API Gateway levels. Roles: Admin (full access), Content Manager (CMS only), Teacher (classrooms + assignments), Student (learning + quizzes), Parent (read-only child progress).

Student Dashboard

The student portal at /dashboard — a personalised hub for courses, quizzes, focus sessions, progress tracking, and timetables.

PageRouteDescription
Dashboard Home/dashboardStats, subscription status, daily goals, quick actions
My Learning/dashboard/learningBrowse subjects/topics with search and filters
Progress/dashboard/progressVisual progress charts, completion rates per subject
Quizzes/dashboard/quizzesBrowse and start quizzes, view past attempts
Take Quiz/dashboard/quizzes/:id/takeInteractive quiz interface with timer
Quiz Results/dashboard/quizzes/results/:idDetailed results with explanations
Focus Timer/dashboard/focusPomodoro timer with session history
Achievements/dashboard/achievementsBadges, milestones, and streak display
Bookmarks/dashboard/bookmarksSaved cards and topics
Schedule/dashboard/scheduleStudy planner with calendar view
Subscriptions/dashboard/subscriptionsMy plan, usage, and upgrade options
Profile/dashboard/profileEdit name, photo, bio, preferences
Settings/dashboard/settingsNotifications, theme, timezone, password

API Gateway

All API traffic flows through the gateway at http://localhost:3000 (or https://api.mentray.com in production).

Base URL

text
Development : http://localhost:3000/api/v1
Production  : https://api.mentray.com/api/v1

Authentication Header

http
Authorization: Bearer <access_token>
Content-Type: application/json

Response Format

json
{
  "success": true,
  "data": { /* response payload */ },
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 142
  }
}

Error Response Format

json
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or expired token",
    "status": 401
  }
}

Rate Limiting

  • Global: 100 requests per minute per IP
  • Auth endpoints: 10 requests per minute per IP
  • AI generation: 5 requests per minute per user
  • Headers returned: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset

All API Endpoints

Complete reference of all 50+ API endpoints grouped by service domain.

Authentication

POST/api/v1/auth/registerPublic
POST/api/v1/auth/loginPublic
POST/api/v1/auth/logoutAuth required
POST/api/v1/auth/refreshRefresh token
POST/api/v1/auth/forgot-passwordPublic
POST/api/v1/auth/reset-passwordToken required

User Profile

GET/api/v1/profileOwn profile
PATCH/api/v1/profileUpdate profile
POST/api/v1/profile/avatarUpload avatar
GET/api/v1/usersList users (Admin)
POST/api/v1/usersCreate user (Admin)
PATCH/api/v1/users/:idUpdate user (Admin)
DELETE/api/v1/users/:idDelete user (Admin)

Content

GET/api/v1/content/subjectsAll subjects
GET/api/v1/content/subjects/:id/divisionsSubject's divisions
GET/api/v1/content/topicsTopics with filter
GET/api/v1/content/topics/:id/cardsTopic's cards
GET/api/v1/content/cards/:idCard with all tabs
POST/api/v1/content/cardsCreate card (Admin)
PATCH/api/v1/content/tabs/:idUpdate tab (Admin)
POST/api/v1/content/searchFull-text search

Quizzes

GET/api/v1/quizzesAvailable quizzes
GET/api/v1/quizzes/:idQuiz details
POST/api/v1/quizzesCreate quiz (Admin)
POST/api/v1/quizzes/:id/attemptStart attempt
POST/api/v1/attempts/:id/submitSubmit answers
GET/api/v1/attempts/:id/resultGet results
GET/api/v1/questionsQuestion bank (Admin)
POST/api/v1/questions/bulkBulk import (Admin)

Analytics

GET/api/v1/analytics/dashboardPersonal overview
GET/api/v1/analytics/performanceTrend data
GET/api/v1/analytics/blind-spotsWeak areas
GET/api/v1/analytics/recommendationsStudy suggestions
GET/api/v1/analytics/leaderboardRankings

Focus Timer

POST/api/v1/focus/sessions/startStart Pomodoro
POST/api/v1/focus/sessions/:id/endEnd session
GET/api/v1/focus/statsProductivity stats
GET/api/v1/focus/presetsTimer presets

Subscriptions

GET/api/v1/subscriptions/plansAll plans
POST/api/v1/subscriptions/subscribeSubscribe
GET/api/v1/subscriptions/myMy subscriptions
GET/api/v1/subscriptionsAll subs (Admin)
GET/api/v1/subscriptions/statsRevenue stats (Admin)

AI Services

POST/api/v1/ai/generate-mcqsGPT-4 MCQ generation
POST/api/v1/ai/ocrHandwriting OCR
POST/api/v1/ai/evaluate-answerMains answer evaluation

Deployment Guide

Mentray supports Docker Compose for development and Kubernetes for production deployments.

Development — Docker Compose

bash
# Start all services
docker-compose up -d

# Start specific service
docker-compose up -d api-gateway auth-service

# View logs
docker-compose logs -f content-service

# Rebuild after code changes
docker-compose build --no-cache api-gateway
docker-compose up -d api-gateway

Production — Kubernetes

bash
# Apply all Kubernetes manifests
kubectl apply -f infrastructure/k8s/

# Apply ConfigMaps and Secrets first
kubectl apply -f infrastructure/k8s/config/
kubectl apply -f infrastructure/k8s/secrets/

# Deploy services
kubectl apply -f infrastructure/k8s/services/

# Check rollout status
kubectl rollout status deployment/api-gateway -n mentray

# Scale a service horizontally
kubectl scale deployment quiz-service --replicas=3 -n mentray

Frontend Deployment

bash
# Install dependencies
cd frontend && npm install

# Build for production
npm run build

# Output: frontend/dist/ (~1.6 MB)
# Deploy to Nginx / Cloudflare Pages / Vercel

# Preview production build locally
npm run preview

Nginx Configuration

nginx
server {
    listen 443 ssl http2;
    server_name mentray.com;

    root /var/www/mentray/dist;
    index index.html;

    # React Router — serve index.html for all routes
    location / {
        try_files $uri $uri/ /index.html;
    }

    # API proxy to gateway
    location /api/ {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Environment Variables

Each service has its own .env file. Below are the key variables for each service.

API Gateway

.env
PORT=3000
NODE_ENV=production
JWT_SECRET=your-super-secret-jwt-key-min-32-chars
JWT_EXPIRES_IN=15m
REFRESH_TOKEN_EXPIRES_IN=7d
REDIS_URL=redis://localhost:6379
AUTH_SERVICE_URL=http://localhost:3001
CONTENT_SERVICE_URL=http://localhost:3003
QUIZ_SERVICE_URL=http://localhost:3004
ANALYTICS_SERVICE_URL=http://localhost:3005

Auth Service

.env
PORT=3001
DB_URL=postgresql://user:pass@localhost:5432/auth_db
JWT_SECRET=same-as-gateway
BCRYPT_ROUNDS=12
SMTP_HOST=smtp.sendgrid.net
SMTP_USER=apikey
SMTP_PASS=your-sendgrid-api-key
FROM_EMAIL=noreply@mentray.com

AI Services (Python)

.env
OPENAI_API_KEY=sk-your-openai-api-key
OPENAI_MODEL=gpt-4
MAX_TOKENS=2000
DATABASE_URL=postgresql://user:pass@localhost:5432/quiz_db
MINIO_ENDPOINT=localhost:9000
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=minioadmin
🔒
Never commit .env files All .env files are in .gitignore. Use .env.example files as templates and manage production secrets via Kubernetes Secrets or a vault solution.

Security Architecture

Mentray is built with OWASP Top 10 mitigations in place across all services and the frontend.

🔐

Authentication

  • bcrypt password hashing (12 rounds)
  • JWT with short expiry + rotation
  • HTTP-only, Secure, SameSite cookies
  • Failed login lockout (5 attempts)
🛡️

API Security

  • Helmet.js security headers
  • CORS whitelist enforcement
  • Rate limiting per IP and user
  • Input validation with Joi/Zod
🔒

Data Security

  • Parameterized SQL queries (no raw SQL)
  • Database credentials via env only
  • TLS in transit (HTTPS + SSL for DBs)
  • Secrets managed via K8s Secrets
🕵️

Monitoring

  • Centralized structured logging
  • Prometheus metrics + Grafana alerts
  • Anomaly detection on login patterns
  • Audit logs for admin actions
OWASP Top 10 Compliance Injection (parameterized queries), Broken Auth (JWT rotation, lockout), XSS (React escaping + CSP), Insecure Design (RBAC), Security Misconfiguration (Helmet), and SSRF (allowlist for outbound requests) are all addressed.

LMS Modules

Mentray's backend is organised into 25+ discrete modules, each owning its own routes, controller, service, and database schema. Every module is independently testable and deployable.

🔐 Authentication & Users

🔑

auth

  • Email/password registration & login
  • JWT access + refresh token issuance
  • Token rotation & revocation
  • OTP email verification
  • Forgot/reset password flow
  • bcrypt password hashing (12 rounds)
  • Session lockout after 5 failed attempts
👤

user

  • User CRUD (Admin)
  • Role assignment (Admin, Content Manager, Teacher, Student, Parent)
  • Active/inactive status toggle
  • Avatar upload via MinIO
  • Profile edit (name, phone, bio)
  • Account settings & preferences
  • Impersonation support (admin view-as-user)
⚙️

settings

  • Global platform configuration
  • Per-user preferences (theme, timezone, language)
  • Notification opt-in/out per channel
  • Platform branding & colour theme
  • Feature flags per role

📚 Content Management

🗂️

content

  • 5-level hierarchy: Subject → Division → Topic → Card → Tab
  • Rich text editor (TipTap/Quill) for text tabs
  • Video, PDF, Audio, Quiz tab types
  • Content version history & restore
  • Access control by subscription plan
  • Tag-based content linking & search
  • Bulk import/export (CSV, JSON)
🎴

content — Flash Cards

  • Quick-revision flashcard decks
  • Front/back card format with media support
  • Spaced repetition scheduling
  • Difficulty self-rating (Easy/Good/Hard)
  • Deck progress tracking per student
🎓

courses

  • Full course catalogue with descriptions
  • Course enrollment & access management
  • Chapter/lesson ordering
  • Course progress percentage tracking
  • My Enrollments page per student
  • Course completion certificates (planned)
📰

current-affairs

  • Daily current affairs article publishing
  • Category & tag management
  • Date-filtered browsing
  • Daily Newspaper view for students
  • Article search & archive
  • Admin publishing workflow
📝

notes

  • Student personal notes per topic/card
  • Rich text note editor
  • Notes list with search & filter
  • Pin important notes
  • Export notes as PDF
🔖

bookmark

  • Bookmark any card, topic, or quiz
  • Organised bookmark collections
  • Quick access from dashboard
  • Bookmark count per content item

📝 Assessment & Testing

quiz

  • MCQ quiz creation with rules & settings
  • Timed & untimed modes
  • Negative marking support
  • Shuffle questions & options
  • Auto-grading on submission
  • Per-question explanations & references
  • Attempt history & comparison
  • Quiz archive & search
🏛️

pyq

  • Previous Year Question bank
  • Year-wise & subject-wise filtering
  • Difficulty classification (Easy/Medium/Hard)
  • Browser & solve interface for students
  • Bulk admin import via CSV
  • PYQ-quiz linking
📋

quiz — Question Banks

  • Organised question collections by topic
  • Bulk import (CSV/JSON) & AI generation
  • Question tagging & difficulty labelling
  • Reuse questions across multiple quizzes
  • Question usage & performance stats
📊

test-reports

  • Per-student test result reports
  • Batch-level aggregate analytics
  • Subject & topic-wise breakdown charts
  • Comparative performance vs class average
  • PDF report export
  • Teacher & admin dashboards
📐

mains

  • Long-form exam topic management
  • Mains practice answer submissions
  • Handwriting upload for OCR evaluation
  • GPT-4 model answer comparison
  • Structured feedback (content, language, format)

🏫 LMS Operations

🏫

lms — Classrooms

  • Virtual classroom creation & management
  • Student & teacher assignment to classrooms
  • Class-level announcements
  • Classroom-scoped timetables
  • Batch promotion management
📅

schedule

  • Student personal study planner
  • Calendar view with daily/weekly modes
  • Study goal setting per subject
  • Scheduled exam date reminders
  • AI-suggested study schedule
📋

lms — Assignments

  • Teacher creates assignments with due dates
  • File submission by students (PDF/image)
  • Grading & feedback by teacher
  • Submission status tracking
  • Late submission flagging
🕐

lms — Timetables

  • Class timetable builder (drag & drop)
  • Teacher availability scheduling
  • AI-assisted timetable generation
  • Clash detection & resolution
  • Student-facing timetable view
📣

notification — Announcements

  • Platform-wide & class-specific announcements
  • Priority levels (info, warning, urgent)
  • Scheduled publish & expiry dates
  • Multi-channel delivery (in-app, email, push)
👨‍👩‍👧

lms — Parent Portal

  • Parent ↔ student account linking
  • Read-only child progress view
  • Attendance & assignment completion overview
  • Fee payment status visibility
  • Notification delivery to parents

📊 Analytics, AI & Productivity

📈

report / analytics

  • Student performance trends (daily/weekly/monthly)
  • Subject-wise accuracy breakdown
  • Blind spot & weak area detection
  • Risk score per student per subject
  • Personalised study recommendations
  • Real-time leaderboards (Redis sorted sets)
  • PDF & Excel report export
🧠

cognitive

  • Cognitive load analytics per student
  • Attention span estimation from quiz timing
  • Retention curve modelling
  • Learning style pattern detection
  • Adaptive difficulty recommendations
🤖

ai-prompts

  • Admin-managed GPT-4 prompt templates
  • Prompt versioning & A/B testing
  • Context injection (subject, topic, level)
  • AI usage token tracking & cost logging
  • Model selection per use-case
⏱️

focus

  • Pomodoro timer with customisable intervals
  • Focus session MongoDB logging
  • Productivity score calculation
  • Daily & weekly study hours stats
  • Streak tracking & milestones
  • Preset templates (Classic, Deep Work, Short Burst)
🏅

achievement

  • Badge system with unlock conditions
  • Study streak achievements (7, 30, 100 days)
  • Quiz performance milestones
  • Content completion badges
  • Gamification leaderboard integration
  • Achievement notification & celebration animation
💬

discussion / group

  • Study group creation & join requests
  • Group discussion threads
  • Ask Anything (Q&A module)
  • Teacher-moderated class discussions
  • Upvote/downvote answers

💳 Platform, Billing & Communication

💳

subscription

  • 4 plans: FREE, BASIC, PREMIUM, LIFETIME
  • Razorpay/Stripe payment gateway
  • Webhook-based payment confirmation
  • Plan expiry & auto-renewal
  • Admin revenue statistics dashboard
  • Promo code & discount support
💰

fees (LMS)

  • Institute fee structure definition
  • Per-student fee assignment
  • Payment collection tracking
  • Pending & overdue fee alerts
  • Receipt generation (PDF)
  • Fee history per student & parent
🔔

notification

  • In-app notification bell (real-time, Redis pub/sub)
  • Email notifications (SMTP/SendGrid)
  • Browser push (VAPID Web Push)
  • Telegram bot delivery
  • Notification preferences per user
  • Scheduled & triggered delivery
🔍

search

  • Global full-text search across all content
  • Search by subject, topic, card, quiz
  • Tag-based search & filtering
  • Search result ranking by relevance
  • Recent search history
📤

upload

  • S3-compatible MinIO object storage
  • Multipart upload for large videos
  • Image compression & resizing
  • File type & size validation
  • Secure signed URL generation
  • Avatar, PDF, audio, video handling
🌐

cms

  • Public website page content management
  • Pricing packages editor
  • Student & parent testimonials
  • Homepage hero & feature sections
  • SEO meta tags per page

Complete Platform Functionality

Every feature available in the platform, organised by functional area.

🎓 Student-Facing Features

FeatureModuleDetails
Personalised DashboarduserStats cards (streak, study time, quiz score), quick actions, subscription status, daily goals
Course CataloguecoursesBrowse all subjects/courses, enroll, track completion percentage
Structured Content ViewercontentRead articles, watch videos, read PDFs, listen to audio, complete embedded quizzes
Flash CardscontentSpaced repetition card decks with self-rated difficulty for active recall
Quiz EnginequizTimed MCQ quizzes with shuffle, auto-grade, explanations, and attempt history
PYQ BrowserpyqFilter and solve previous year question papers by year, subject, difficulty
Test Historyquiz / test-reportsFull history of all quiz/test attempts with score breakdown and improvement tracking
Progress TrackingprogressVisual charts of completion and accuracy per subject and topic
Learning Analyticsreport / cognitivePerformance trends, blind spots, risk scores, cognitive load analysis
Mains PracticemainsUpload handwritten answers, receive GPT-4 structured feedback
Focus TimerfocusPomodoro sessions with presets, session logging, streaks, daily productivity score
Study ScheduleschedulePersonal calendar planner with daily/weekly view, goal setting per subject
BookmarksbookmarkSave any card, topic, quiz for later quick access
NotesnotesRich text personal notes attached to any content item
Current Affairscurrent-affairsDaily news articles with category filtering and newspaper-style reading view
Study GroupsgroupJoin/create peer study groups, group discussions, shared notes
Ask AnythingdiscussionQ&A forum per topic — ask questions, upvote answers, teacher replies
AchievementsachievementBadges, milestone celebrations, gamified streaks and leaderboards
AssignmentslmsView teacher-assigned tasks, submit files, receive graded feedback
Timetable ViewlmsPersonal class timetable with daily schedule
Subscription & PlanssubscriptionView current plan, upgrade/downgrade, payment history, invoice download
Profile & Settingsuser / settingsEdit name, photo, bio, password, notification preferences, theme, timezone
FeedbacklearnerRate content quality, submit improvement suggestions

👩‍🏫 Teacher-Facing Features

FeatureModuleDetails
Teacher DashboardlmsOverview of classrooms, pending assignments, student activity, announcements
My ClassroomslmsView assigned classrooms, class roster, manage enrolled students
My StudentslmsPer-student progress overview, quiz scores, attendance, risk flags
Assignments ManagerlmsCreate assignments with due dates, view submissions, grade and leave feedback
TimetablelmsView personal teaching timetable, request schedule changes
AnnouncementsnotificationPost class-level or platform-wide announcements with scheduling
Content AccesscontentBrowse and share content cards/topics with students
AI Quiz Generatorai-prompts / quizGenerate MCQ quizzes from a topic using GPT-4, review and publish
AI Timetable Builderlms / aiAuto-generate conflict-free timetables based on teacher availability and subjects
Student Risk Analysiscognitive / reportAI flags at-risk students based on quiz performance, inactivity, and blind spots
AnalyticsreportClass-level performance trends, subject accuracy charts, quiz completion rates
ProfileuserManage personal profile, subjects taught, contact details

🛡️ Admin Features

FeatureModuleDetails
Admin DashboardreportPlatform KPIs, new user growth, revenue, active sessions, top content
Platform AnalyticsreportEngagement metrics, retention rates, quiz completion, DAU/MAU trends
Student ManagementuserList, search, create, edit, delete students; toggle status; view progress
Faculty Managementuser / lmsCreate and manage teacher accounts, assign subjects and classrooms
Staff ManagementuserAdmin staff directory, role assignments, access control
Role Managementauth / userAssign/revoke roles (Admin, Content Manager, Teacher, Student, Parent)
Classroom ManagementlmsCreate classrooms, assign teachers and students, manage batches
Timetable ManagementlmsBuild and publish class timetables, resolve conflicts, view AI suggestions
Fees ManagementfeesDefine fee structures, track collections, view pending/overdue fees, generate receipts
SubscriptionssubscriptionView all subscriptions, revenue stats, cancel, create manual subscriptions
Content ManagementcontentFull CMS for subjects, divisions, topics, cards, tabs with media uploads
Current Affairscurrent-affairsPublish, edit, categorise daily current affairs articles
Flash Cards AdmincontentCreate and organise flashcard decks
Quiz ManagementquizCreate/edit/publish quizzes, set rules, view all attempts
Question BankquizFull question CRUD, bulk import, AI generation, usage statistics
PYQ ManagementpyqUpload and organise previous year questions with metadata
Test SeriesquizSchedule and manage recurring test series with enrolment
Test Analyticstest-reportsBatch-level test performance, comparative charts, student rankings
Test Reportstest-reportsExportable PDF reports per student and per batch
AI Promptsai-promptsManage GPT-4 prompt templates, version control, token usage logs
AI Usage Logsai-promptsTrack AI API costs, usage per feature, monthly spend
Website CMScmsEdit public website content (packages, pages, testimonials)
SecurityauthLogin attempt audit logs, blocked IPs, active session management
Theme SettingssettingsPlatform branding colours, logo, and typography
Global SettingssettingsFeature flags, maintenance mode, allowed domains, email config

🤖 AI & Automation Features

AI MCQ Generation

  • Generate 10–100 questions from a topic or document
  • GPT-4 with curriculum-aligned prompt templates
  • Automatic difficulty classification
  • Explanation generation per question
  • Admin review before publish
🔍

Handwriting OCR

  • EasyOCR engine with image preprocessing
  • Noise reduction, deskew, binarization
  • Structured text extraction from answer sheets
  • GPT-4 evaluation against model answers
  • Content, language, and structure scoring
📅

AI Timetable Builder

  • Teacher availability input
  • Subject load distribution
  • Automatic clash detection
  • Multiple timetable variants generated
  • Admin approval & publish flow
⚠️

Student Risk Analysis

  • Composite risk score (accuracy + time + frequency)
  • Blind spot topic identification
  • Inactivity & disengagement alerts
  • Personalised "study next" recommendations
  • Teacher dashboard risk flag notifications
🧠

Cognitive Analytics

  • Attention span estimation from quiz timing data
  • Memory retention curve modelling
  • Learning style pattern detection
  • Adaptive difficulty recommendations
  • Cognitive load trend visualisation
📊

Automated Reports

  • Daily summary email to students
  • Weekly batch performance report to teachers
  • Monthly revenue summary for admin
  • PDF & Excel export on demand
  • Scheduled via RabbitMQ cron jobs

User Roles & Permissions

Mentray implements Role-Based Access Control (RBAC) with 5 distinct roles. Every API route and frontend page is gated by role at both the API Gateway and React Router levels.

🛡️

Admin

Full platform access. Manages everything.

  • All student, faculty, staff management
  • Full CMS control
  • Fees, subscriptions, revenue
  • Platform settings & security
  • AI tools & usage monitoring
  • Impersonate any user
📝

Content Manager

Manages all learning content. No access to users or billing.

  • Create/edit subjects, divisions, topics, cards, tabs
  • Manage flashcards & current affairs
  • Upload media assets
  • Manage quiz question bank
  • Publish/unpublish content
👩‍🏫

Teacher

Manages assigned classrooms, students, and assessments.

  • View & manage assigned classrooms
  • Create assignments & grade submissions
  • Post announcements to class
  • View student analytics & risk flags
  • Generate AI quizzes & timetables
  • View & manage timetable
🎓

Student

Full learning access based on subscription plan.

  • Browse & study all enrolled content
  • Take quizzes, PYQs, test series
  • Submit assignments
  • Use focus timer & study planner
  • View own analytics & achievements
  • Participate in discussions & groups
  • Manage subscription plan
👨‍👩‍👧

Parent

Read-only access to linked child's progress and fees.

  • View child's quiz scores & progress
  • Check assignment submission status
  • View class timetable
  • Check fee payment status
  • Receive notifications about child

Role Permission Matrix

Feature Area Admin Content Mgr Teacher Student Parent
User Management✅ Full
Content CMS✅ Full✅ Full👁 Read👁 Read
Quiz Management✅ Full✅ Full✍ Create▶ Take
Classrooms✅ Full✅ Assigned👁 Own👁 Child's
Assignments✅ Full✅ Create/Grade📤 Submit👁 View
Timetables✅ Full👁 Own👁 Own👁 Child's
Fees & Billing✅ Full💳 Own👁 Child's
Analytics✅ Platform📊 Class📊 Own👁 Child's
AI Tools✅ Full✅ Content AI✅ Class AI
Settings✅ Full👤 Own👤 Own👤 Own
🔐
Enforcement at Two Levels Role checks happen at: (1) the API Gateway via JWT role claim on every request, and (2) the React Router via protected route components that redirect unauthorised roles before any page renders.