Skip to content

Latest commit

 

History

History
390 lines (306 loc) · 23.3 KB

README.md

File metadata and controls

390 lines (306 loc) · 23.3 KB

📚 Spring E-Learning & CBT Platform

Java 21 Spring Boot React 19 Tailwind CSS v4 PostgreSQL Redis Laravel Edition License

🇮🇩 Baca dalam Bahasa Indonesia

🐘 Looking for the Laravel & Livewire edition? A companion monolithic edition built with Laravel 13, Livewire 3, and Laravel Reverb is available at: https://github.com/mfarim/laravel-elearning

A full-featured web-based E-Learning and Computer Based Test (CBT) platform for managing modern academic learning activities between Admin, Teacher, and Student. Built as a containerized modular monolith with a decoupled SPA frontend: Java 21 LTS, Spring Boot 3.5+, React 19, and Tailwind CSS v4, featuring stateless JWT authentication with Redis-backed refresh-token rotation and impersonation, WebSocket STOMP real-time candidate proctoring, and Apache POI Excel batch processing.


✨ Key Features

👨‍💼 Admin Panel

Feature Description
Dashboard Real-time statistics overview: teachers, students, classrooms, subjects, CBT metrics
Teachers Full CRUD with automatic user account provisioning & NIP validation
Students CRUD + classroom filtering + 📥 Excel Batch Import (.xlsx) + Exam Cards Print
Classrooms CRUD + homeroom teacher assignment + capacity & academic year management
Subjects CRUD + subject code + credit units + assigned teacher mapping
Announcements CRUD + multi-target broadcasting (All / Teacher / Student) + publish toggle
Impersonation Instant one-click login as teacher or student for administrative debugging
Security Spring Security 6 stateless JWT tokens, BCrypt hashing, and method-level @PreAuthorize

👨‍🏫 Teacher Panel

Feature Description
Dashboard Teaching metrics, scheduled examinations, active assignments, and recent activity
Learning Materials CRUD + multi-type content (Document, Video, Text, Link, Audio) + student view tracking
Assignments CRUD + deadline dates + instructions + submission grading with feedback
CBT Examinations CRUD + duration timer + passing grade (KKM) + randomize questions/options + retry toggles + show or hide the score from students
Question Builder Multiple Choice (A-E), True/False, Essay + points allocation + 📥 Excel Import
Live Telemetry Monitor Real-time WebSocket candidate status, question progress bar, and anti-cheat flag alerts
Exam Hall Tickets Print ready-to-use official CBT student candidate cards with NIS barcodes

👨‍🎓 Student Panel — Mobile-First Design

Feature Description
Home Dashboard Responsive mobile drawer, upcoming exams countdown, active assignments, announcements
Learning Modules Browse, read, and download structured course materials per enrolled subject
Assignment Hub View assignment instructions + file upload dropzone + feedback review
CBT Exam Room Fullscreen examination runner with countdown timer, anti-cheat detection, and auto-submit
Grades & GPA Summary Subject average breakdown, progress bars, and passing grade pass/fail status

🖥️ CBT Exam System Workflow

Exam List → Confirmation & Instructions → Secure Exam Runner
                                           ├── ⏱️ Synchronized Timer (auto-submit on expiry)
                                           ├── 🔒 Anti-Cheat Proctoring (fullscreen & tab change alerts)
                                           ├── 📍 Color-Coded Question Palette (answered / remaining)
                                           ├── 💾 Instant Auto-Save (on every option selection)
                                           └── 📊 Real-Time Proctor Telemetry (WebSocket push to teacher)

📸 Screenshots

🔐 Login Page

Login Page

👨‍💼 Admin Panel

Dashboard Teachers Management
Admin Dashboard Teachers
Students Management Classrooms Management
Students Classrooms
Subjects Management Announcements
Subjects Announcements

👨‍🏫 Teacher Panel

Dashboard Learning Materials
Teacher Dashboard Materials
Assignments Management CBT Examinations
Assignments Exams
Question Builder & Bank
Question Bank

👨‍🎓 Student Panel (Mobile-First Design)

Home Dashboard Learning Materials Assignments Hub
Student Dashboard Materials Assignments
Examination Room Grades & Report Card
Student Exams Student Grades

🛠️ Tech Stack

Layer Technology
Backend Core Java 21 LTS, Spring Boot 3.5.7
Security & Auth Spring Security 6, JJWT 0.12.6, Method Security (@PreAuthorize), Impersonation Engine
Persistence PostgreSQL 16, Spring Data JPA, Hibernate 6, HikariCP, Flyway Migrations
Token Store & Realtime Redis 7 (refresh-token rotation, optional shared rate limits and cross-instance events), Spring WebSocket + STOMP (in-memory simple broker), SockJS
File Storage Local Docker volume or S3-compatible object storage (AWS S3, MinIO)
Batch Processing Apache POI (Excel .xlsx batch parsing for Students & Question Banks)
API Documentation Springdoc OpenAPI 3 / Swagger UI (/swagger-ui/index.html)
Frontend Core React 19, TypeScript 5+, Vite 6
Styling Tailwind CSS v4 (Native CSS engine with @tailwindcss/vite)
State Management Zustand 5, Axios with JWT interceptors
Icons & UI Lucide React
Deployment Docker Compose, Multi-stage Dockerfiles (OpenJDK 21 Alpine & Node 22 Alpine), Nginx 1.28

🏛️ High-Level System Architecture

The platform is a modular monolith (one Spring Boot service split into domain modules) with a separate React SPA, deployed as Docker containers on a VPS behind Cloudflare, with defense-in-depth at every layer. Data model, request flows, design decisions, and scaling limits are documented in docs/ARCHITECTURE.md.

graph TD
    Client["🌐 Clients / Web Browsers<br/>(Admin, Teacher, Student)"]
    
    subgraph Edge ["🛡️ Perimeter & Edge Layer"]
        CF["Cloudflare Edge Proxy<br/>• WAF & DDoS Shield<br/>• SSL/TLS Termination<br/>• CF-Connecting-IP Passthrough"]
    end

    subgraph Host ["🖥️ VPS Host Server"]
        Nginx["Host Reverse Proxy / Nginx<br/>• Port 80/443 Loopback (127.0.0.1)<br/>• Security Headers (nosniff, SAMEORIGIN)<br/>• Actuator Endpoints Blocked (404)"]
        
        subgraph DockerNet ["Docker Network (elearning-network)"]
            Frontend["📦 elearning-frontend<br/>React 19 SPA + Vite + Tailwind v4"]
            
            Backend["☕ elearning-backend<br/>Java 21 LTS + Spring Boot 3.5.7<br/>• Spring Security 6 (Stateless JWT)<br/>• Bucket4j Login Rate Limiting (A07)<br/>• STOMP WebSocket (in-memory simple broker)<br/>• Apache POI with Batch Guards"]
            
            Postgres[("🐘 elearning-postgres<br/>PostgreSQL 16 Relational DB<br/>• Flyway Automated Migrations<br/>• HikariCP Connection Pool")]
            
            Redis[("⚡ elearning-redis<br/>Redis 7<br/>• Refresh-token store<br/>• Rotation & revocation by jti")]
            
            Storage[("📁 backend_storage<br/>Persistent Docker Volume<br/>• Uploads (/app/storage/uploads)<br/>• File Extension Whitelisting")]
        end
    end

    Client -->|HTTPS / WSS| CF
    CF -->|Proxied Traffic| Nginx
    Nginx -->|Static Assets| Frontend
    Nginx -->|/api/ & /ws| Backend
    Backend -->|HikariCP / JPA| Postgres
    Backend -->|Refresh tokens| Redis
    Backend -->|Safe File I/O| Storage
Loading

🔒 Security & OWASP Top 10 Mapping

OWASP Standard Mitigation in this Platform
A01: Broken Access Control Method-level security (@PreAuthorize) on all administrative and user directory endpoints; classroom ownership validation preventing IDOR on assignments and discussions; STOMP WebSocket ChannelInterceptor verifying teacher/admin privileges.
A02: Cryptographic Failures BCrypt password hashing; HMAC-SHA256 JWT tokens with mandatory 256-bit+ secret key validation on application boot; automated fail-fast if JWT_SECRET is missing.
A03: Injection 100% parameterized Spring Data JPA queries eliminating SQL Injection; no OS command execution; strict input DTO @Valid constraints.
A04: Insecure Design Examination answer keys and explanations strictly stripped (null) from student payloads; examination duration deadlines enforced on the server-side, not trusting client clocks.
A05: Security Misconfiguration Spring Boot Actuator endpoints strictly blocked (404) from public Nginx reverse proxy; all Docker service ports bound to loopback 127.0.0.1; security headers (X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN) enforced.
A06: Vulnerable Components Java 21 LTS, Spring Boot 3.5.7, PostgreSQL 16, Redis 7, React 19. Multi-stage Docker containers running under non-root spring:spring user.
A07: Identification Failures Login Rate Limiter: 5 attempts per minute per account email and 100 per minute per IP address (sized for a computer lab behind one public IP, APP_RATE_LIMIT_LOGIN_PER_IP), returning 429 Too Many Requests with Retry-After header. Signed-in API calls are limited per user, not per IP.
A08: Software & Data Integrity Strict file upload extension whitelist (.pdf, .docx, .xlsx, .jpg, .png, etc.); executable and scriptable types (.html, .svg, .exe, .sh) explicitly rejected to prevent Stored XSS; safe download Content-Disposition.
A09: Logging & Monitoring Anti-cheat proctoring violation alerts logged with student NIS; internal /actuator/health probe available for container healthchecks.
A10: SSRF Zero user-controlled outbound HTTP requests from backend services.

🏗️ Real-Time Telemetry & WebSocket Architecture

The live examination monitoring feature uses Spring WebSocket with STOMP and Spring's in-memory simple broker to push candidate progress to the teacher in real time. Answers and attempts are persisted in PostgreSQL first, then an event is broadcast. Moving to a Redis/RabbitMQ broker relay for multi-instance deployments is on the roadmap (see docs/ARCHITECTURE.md).

Message Flow

┌─────────────────┐       ┌──────────────────────┐       ┌─────────────────────┐       ┌──────────────────┐
│  Candidate in   │──────▶│   Spring Controller  │──────▶│   PostgreSQL        │       │                  │
│  Exam Runner    │       │  /api/v1/exams/...   │       │ (attempts, answers) │       │   Spring STOMP   │
└─────────────────┘       └──────────┬───────────┘       └─────────────────────┘       │  Message Broker  │
                                     │                                                 │  (/ws/cbt)       │
                                     │  messagingTemplate.convertAndSend()             │                  │
                                     └────────────────────────────────────────────────▶│                  │
                                                                                       └────────┬─────────┘
                                                                                                │
                                                                       Real-time Telemetry Push │
                                                                                                ▼
                                                                                   ┌────────────────────────┐
                                                                                   │  Teacher Proctoring    │
                                                                                   │  Monitor Dashboard     │
                                                                                   │  → Instant auto-update │
                                                                                   └────────────────────────┘

Key Components

File / Component Purpose
backend/.../WebSocketConfig.java Configures STOMP endpoints (/ws/cbt) and message broker destinations (/topic, /app)
backend/.../ExamTelemetryMessage.java DTO representing real-time candidate heartbeat, progress, and anti-cheat violations
backend/.../ExamService.java Broadcasts telemetry updates upon student answers, time alerts, and submission events
frontend/src/pages/exams/ExamMonitor.tsx Proctoring dashboard with STOMP/SockJS client listener and candidate progress cards
frontend/src/pages/exams/ExamRunner.tsx Secure candidate runner detecting window blur, tab switching, and fullscreen lock

🚀 Installation & Quick Setup

Prerequisites

  • Docker & Docker Compose
  • Java 21 LTS (for local backend development)
  • Node.js 22+ (for local frontend development)

Quick Setup (Docker Compose — Recommended)

# Clone the repository
git clone https://github.com/mfarim/spring-elearning-react.git
cd spring-elearning-react

# Generate a JWT signing secret (required, no default)
echo "JWT_SECRET=$(openssl rand -base64 32)" > .env

# Launch full stack (PostgreSQL 16, Redis 7, Spring Boot backend, and React frontend)
docker compose up -d

# (Optional) Seed realistic demo data (teachers, classrooms, subjects, exams)
docker exec -i elearning-postgres psql -U postgres -d elearning < backend/src/main/resources/db/migration/seed_demo_data.sql

Access the services:

For contribution guidelines and coding standards, see CONTRIBUTING.md.


Manual Setup (Local Development)

1. Start Infrastructure

docker compose up -d postgres redis

2. Start Backend (Spring Boot)

cd backend
# JWT_SECRET must be set (same value as in .env)
export $(grep JWT_SECRET ../.env)
./mvnw clean spring-boot:run

3. Start Frontend (React + Vite)

cd frontend
npm install
npm run dev

🔑 Demo Accounts

The database comes pre-seeded with ready-to-test accounts for each academic role:

Role Email Password Portal URL
Admin admin@sekolah.id (or admin@elearning.com) password /dashboard
Guru (Teacher) budi@sekolah.id (or teacher@elearning.com) password /dashboard
Siswa (Student) andi.pratama1@siswa.id (or student@elearning.com) password /dashboard

Quick Demo Login buttons are also available directly on the login screen for instant one-click access.


📥 Student Excel Import Format

The student batch importer accepts standard .xlsx spreadsheets with the following columns:

Column Header Required Example Value Description
Name ✅ Andi Pratama Student's full registered name
Email ✅ andi@siswa.id Unique login credential email
NIS ✅ 20250001 Student identification number (unique barcode identifier)
Classroom ✅ X IPA 1 Target classroom name
NISN ➖ 0012345678 National student identification number
Gender ➖ L / P (or M / F) Gender identification
Address ➖ Jl. Merdeka No. 45 Residential home address

🧪 Testing & Validation

Backend Tests

cd backend
./mvnw test

Frontend Build & Lint Check

cd frontend
npm run build

📂 Project Structure

spring-elearning-react/
├── backend/
│   ├── src/main/java/com/elearning/
│   │   ├── config/              # Spring Security filter chain, WebSocket/STOMP config
│   │   ├── security/            # JWT provider & filter, refresh-token store, rate limiting
│   │   ├── common/              # Base entity, response wrappers, exception handler
│   │   └── modules/
│   │       ├── auth/            # Login, refresh, logout, password change, impersonation
│   │       ├── user/            # Users, Teachers, Students
│   │       ├── academic/        # Classrooms, Subjects
│   │       ├── announcement/    # Announcements
│   │       ├── material/        # Learning Materials & Material Views
│   │       ├── assignment/      # Assignments, Submissions, Discussions
│   │       ├── exam/            # CBT Exams, Question Bank, Attempts, Telemetry
│   │       └── grade/           # Grade summaries
│   └── src/main/resources/
│       ├── db/migration/        # Flyway SQL schema migrations & seeders
│       └── application.yml      # Spring Boot profile configurations
├── frontend/
│   ├── public/                  # Favicons, App Logo, OG Banner image
│   ├── src/
│   │   ├── api/                 # Axios HTTP client with JWT auto-refresh interceptors
│   │   ├── components/          # Common Layout, Sidebar, Top Navbar, ProtectedRoute
│   │   ├── pages/               # Admin, Teacher, Student, CBT Runner, Exam Monitor
│   │   ├── store/               # Zustand authentication & state management
│   │   └── types/               # TypeScript interfaces & DTO schemas
│   ├── index.html               # Semantic HTML with complete OpenGraph & JSON-LD SEO
│   └── vite.config.ts           # Vite 6 config with Tailwind CSS v4 native plugin
├── docs/ARCHITECTURE.md         # Data model, sequence diagrams, design decisions, scaling limits
├── screenshots/                 # Application showcase captures across roles
└── docker-compose.yml           # Multi-container orchestration definition

🚢 Production Deployment

For production deployments:

  1. Use the optimized multi-stage backend/Dockerfile and frontend/Dockerfile.
  2. Configure external production PostgreSQL and Redis connection strings in environment variables (SPRING_DATASOURCE_URL, SPRING_DATA_REDIS_HOST).
  3. Set a strong JWT secret (JWT_SECRET) with a minimum of 256 bits.
  4. Deploy behind Nginx or Cloudflare with SSL/TLS termination and WebSocket header forwarding (Upgrade and Connection headers).
  5. Add your public domain to APP_CORS_ALLOWED_ORIGINS (also used as the allowed WebSocket origins).
  6. Default accounts must change their password on first login. Set APP_DEMO_MODE=true only on a public demo instance with shared demo accounts.
  7. Keep SPRINGDOC_ENABLED=false and APP_REGISTRATION_ENABLED=false unless you need them.
  8. The refresh token is an httpOnly Secure cookie, so serve the app over HTTPS. Set APP_REFRESH_COOKIE_SECURE=false only for plain-HTTP local runs (the local docker-compose.yml already does).
  9. The SPA sends a Content-Security-Policy. If you enable analytics, allow its hosts on the frontend container, e.g. CSP_SCRIPT_SRC_EXTRA="https://www.googletagmanager.com" and CSP_CONNECT_SRC_EXTRA="https://*.google-analytics.com".
  10. Several backend instances: set APP_REALTIME_MODE=redis, APP_RATE_LIMIT_STORE=redis, and APP_STORAGE_TYPE=s3 with APP_STORAGE_S3_BUCKET (plus APP_STORAGE_S3_ENDPOINT and APP_STORAGE_S3_PATH_STYLE=true for MinIO), and enable sticky sessions for /ws. Details in docs/ARCHITECTURE.md.
  11. Time zone: exam schedules and deadlines are compared against the backend's clock. The image runs in Asia/Jakarta (WIB); set APP_TIMEZONE=Asia/Makassar (WITA) or Asia/Jayapura (WIT) for other regions. Change it outside exam hours: attempts in progress are timed against this clock.
  12. Real client IP / rate limiting: the backend trusts X-Forwarded-For only from internal proxies (Docker network). If the site is behind Cloudflare, restore the visitor IP on the host Nginx, otherwise all users share Cloudflare's IPs for rate limiting:
# http {} block of the host nginx — keep the list in sync with https://www.cloudflare.com/ips/
set_real_ip_from 173.245.48.0/20;   # ...add every Cloudflare IPv4/IPv6 range
real_ip_header CF-Connecting-IP;
# and in the proxied location:
proxy_set_header X-Forwarded-For $remote_addr;

📄 License

This project is open-sourced software licensed under the MIT license.