Skip to content

About

A complete online testing and quiz management system built with Node.js, Express.js, MongoDB, EJS, and MVC architecture featuring authentication, quiz management, analytics, and leaderboard functionality.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

22 Commits

Folders and files

Repository files navigation

πŸš€ Quizmaster Online Testing System

A complete online testing and quiz management system built with Node.js, Express.js, MongoDB, EJS, and MVC architecture featuring authentication, quiz management, analytics, and leaderboard functionality.

Documented Β· MIT licensed Β· Maintained

EJS License PRs


Screenshots

Application screenshot

🐍 Contribution graph

Contribution snake

πŸ“š Project Overview

QuizMaster is a complete Online Testing System built with Node.js, Express.js, MongoDB, and EJS. It allows admins to create and manage quizzes, and students to attempt quizzes, view results, and compete on leaderboards.

This project is developed as part of a backend development course and follows MVC architecture with RESTful API principles.


πŸ‘₯ Group Members

  • Muhammad Afzal Kalwar
  • Ayesha Bibi
  • Hafsa Kanwal Awan

✨ Features

Admin Features

  • βœ… Create, Edit, Delete Quizzes
  • βœ… Add, Edit, Delete Questions
  • βœ… View all Students
  • βœ… View Quiz Attempts
  • βœ… View Leaderboard
  • βœ… Analytics & Dashboard
  • βœ… System Statistics

Student Features

  • βœ… Register & Login
  • βœ… Browse Available Quizzes
  • βœ… Attempt Quizzes with Timer
  • βœ… Submit Answers & View Results
  • βœ… View Score & Percentage
  • βœ… View Leaderboard
  • βœ… Track Previous Attempts
  • βœ… View Performance History

πŸ› οΈ Technologies Used

Core Technologies

  • Node.js - JavaScript runtime
  • Express.js - Web framework
  • MongoDB - NoSQL database
  • Mongoose - ODM for MongoDB
  • EJS - Template engine
  • Express-Session - Session management

Architecture & Concepts

  • MVC Architecture - Model-View-Controller pattern
  • RESTful APIs - REST principles for API design
  • Middleware - Custom middleware for logging, auth, errors
  • Async/Await - Asynchronous programming
  • Node.js fs module - File system operations
  • path module - Path utilities
  • events module - Event emitter pattern
  • MongoDB Aggregation Pipeline - Advanced queries
  • Error Handling Middleware - Centralized error management

NOT Used (As Per Requirements)

  • ❌ React, Angular, Next.js
  • ❌ TypeScript
  • ❌ JWT Authentication
  • ❌ Redux
  • ❌ Docker
  • ❌ Redis
  • ❌ Socket.io
  • ❌ GraphQL

πŸ“ Project Structure

quizmaster/
β”‚
β”œβ”€β”€ config/
β”‚   └── db.js                    # MongoDB connection configuration
β”‚
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ User.js                  # User schema (admin/student)
β”‚   β”œβ”€β”€ Quiz.js                  # Quiz schema
β”‚   β”œβ”€β”€ Question.js              # Question schema
β”‚   β”œβ”€β”€ Attempt.js               # Quiz attempt schema
β”‚   └── Result.js                # Quiz result schema
β”‚
β”œβ”€β”€ controllers/
β”‚   β”œβ”€β”€ authController.js        # Authentication logic
β”‚   β”œβ”€β”€ quizController.js        # Quiz CRUD operations
β”‚   β”œβ”€β”€ questionController.js    # Question management
β”‚   β”œβ”€β”€ attemptController.js     # Quiz attempts & results
β”‚   └── adminController.js       # Admin operations
β”‚
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ authRoutes.js            # Auth endpoints
β”‚   β”œβ”€β”€ quizRoutes.js            # Quiz endpoints
β”‚   β”œβ”€β”€ questionRoutes.js        # Question endpoints
β”‚   β”œβ”€β”€ attemptRoutes.js         # Attempt endpoints
β”‚   └── adminRoutes.js           # Admin endpoints
β”‚
β”œβ”€β”€ middleware/
β”‚   β”œβ”€β”€ loggerMiddleware.js      # Request logging
β”‚   β”œβ”€β”€ errorMiddleware.js       # Error handling
β”‚   └── authMiddleware.js        # Authentication guards
β”‚
β”œβ”€β”€ views/
β”‚   β”œβ”€β”€ index.ejs                # Home page
β”‚   β”œβ”€β”€ login.ejs                # Login page
β”‚   β”œβ”€β”€ register.ejs             # Registration page
β”‚   β”œβ”€β”€ dashboard.ejs            # Student dashboard
β”‚   β”œβ”€β”€ quizzes.ejs              # Quizzes list
β”‚   β”œβ”€β”€ quizDetails.ejs          # Quiz details
β”‚   β”œβ”€β”€ attemptQuiz.ejs          # Quiz attempt page
β”‚   β”œβ”€β”€ result.ejs               # Result page
β”‚   β”œβ”€β”€ leaderboard.ejs          # Leaderboard page
β”‚   β”œβ”€β”€ studentResults.ejs       # Student results
β”‚   β”œβ”€β”€ myAttempts.ejs           # Student attempts
β”‚   β”œβ”€β”€ error.ejs                # Error page
β”‚   └── admin/
β”‚       β”œβ”€β”€ adminDashboard.ejs   # Admin dashboard
β”‚       β”œβ”€β”€ adminQuizzes.ejs     # Manage quizzes
β”‚       β”œβ”€β”€ addQuiz.ejs          # Add quiz form
β”‚       β”œβ”€β”€ editQuiz.ejs         # Edit quiz form
β”‚       β”œβ”€β”€ manageUsers.ejs      # Manage students
β”‚       β”œβ”€β”€ manageQuestions.ejs  # Manage questions
β”‚       β”œβ”€β”€ addQuestion.ejs      # Add question form
β”‚       β”œβ”€β”€ editQuestion.ejs     # Edit question form
β”‚       β”œβ”€β”€ quizAttempts.ejs     # Quiz attempts view
β”‚       └── analytics.ejs        # Analytics dashboard
β”‚
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   └── style.css            # Main stylesheet
β”‚   β”œβ”€β”€ js/
β”‚   β”‚   β”œβ”€β”€ main.js              # Main client-side JS
β”‚   β”‚   └── quiz-timer.js        # Quiz timer functionality
β”‚   └── images/
β”‚
β”œβ”€β”€ data/
β”‚   └── logs.txt                 # Request logs
β”‚
β”œβ”€β”€ app.js                       # Main application file
β”œβ”€β”€ package.json                 # Dependencies & metadata
└── README.md                    # This file

πŸ“Š Database Design

User Schema

{
  name: String,
  email: String (unique),
  password: String,
  role: String ("admin" | "student"),
  createdAt: Date
}

Quiz Schema

{
  title: String,
  category: String,
  difficulty: String ("Easy" | "Medium" | "Hard"),
  totalMarks: Number,
  timeLimit: Number (minutes),
  createdBy: ObjectId (User),
  createdAt: Date
}

Question Schema

{
  quizId: ObjectId (Quiz),
  questionText: String,
  optionA: String,
  optionB: String,
  optionC: String,
  optionD: String,
  correctAnswer: String ("A" | "B" | "C" | "D"),
  marks: Number
}

Attempt Schema

{
  studentId: ObjectId (User),
  quizId: ObjectId (Quiz),
  answers: Map (questionId -> answer),
  score: Number,
  totalQuestions: Number,
  attemptedAt: Date
}

Result Schema

{
  studentName: String,
  quizTitle: String,
  score: Number,
  totalMarks: Number,
  percentage: Number,
  submittedAt: Date,
  studentId: ObjectId (User),
  quizId: ObjectId (Quiz)
}

πŸš€ Installation & Setup

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB (running on localhost:27017)
  • npm package manager

Step 1: Install Dependencies

cd quizmaster
npm install

This installs:

  • express - Web framework
  • mongoose - MongoDB ODM
  • ejs - Template engine
  • express-session - Session management
  • nodemon - Development tool (auto-restart)

Step 2: Setup MongoDB

Ensure MongoDB is running:

# On Windows
mongod

# On macOS/Linux
brew services start mongodb-community

Create the database:

// Connect to MongoDB and it will create database automatically
// Database: quizmasterDB
// Connection: mongodb://127.0.0.1:27017/quizmasterDB

Step 3: Run Application

Development Mode (with auto-reload):

npm run dev

Production Mode:

npm start

Step 4: Access Application


πŸ“ API Endpoints

Authentication

  • GET /register - Registration page
  • POST /register - Register new student
  • GET /login - Login page
  • POST /login - Login user
  • GET /logout - Logout user

Quizzes

  • GET /quizzes - Get all quizzes
  • GET /quizzes/:id - Get quiz details
  • GET /quizzes/admin/create - Create quiz page
  • POST /quizzes/admin/create - Create quiz
  • GET /quizzes/admin/:id/edit - Edit quiz page
  • PUT /quizzes/admin/:id/edit - Update quiz
  • DELETE /quizzes/admin/:id/delete - Delete quiz

Questions

  • GET /questions/quiz/:quizId/questions - List questions
  • GET /questions/quiz/:quizId/add - Add question page
  • POST /questions/quiz/:quizId/add - Create question
  • GET /questions/quiz/:quizId/:questionId/edit - Edit question page
  • PUT /questions/quiz/:quizId/:questionId/edit - Update question
  • DELETE /questions/quiz/:quizId/:questionId/delete - Delete question

Quiz Attempts

  • GET /quiz/:quizId/start - Start quiz
  • POST /quiz/:quizId/submit - Submit quiz
  • GET /result/:resultId - View result
  • GET /my-attempts - View attempts
  • GET /my-results - View results

Admin

  • GET /admin/dashboard - Admin dashboard
  • GET /admin/quizzes - Manage quizzes
  • GET /admin/students - Manage students
  • GET /admin/leaderboard - View leaderboard
  • GET /admin/analytics - View analytics
  • GET /admin/quiz/:quizId/attempts - Quiz attempts

πŸ” Authentication & Authorization

Simple Session-Based Authentication

  • Uses express-session for session management
  • No JWT tokens (as per requirements)
  • User data stored in session after login

Role-Based Access Control

// Admin-only routes
isAdmin middleware checks req.session.role === 'admin'

// Student-only routes
isStudent middleware checks req.session.role === 'student'

// Protected routes
isAuthenticated middleware checks req.session.userId exists

Login Credentials

  • Student Login: Select "student" role
  • Admin Login: Select "admin" role
  • Password validation: Simple string comparison

πŸ“Š Key Features Implementation

1. Quiz Management

  • CRUD operations with full validation
  • Difficulty levels: Easy, Medium, Hard
  • Categories: General Knowledge, Science, Math, etc.
  • Time limits and total marks

2. Question Management

  • Multiple choice questions (A, B, C, D)
  • Mark allocation per question
  • Automatic validation

3. Score Calculation

// Score Calculation Formula
percentage = (score / totalMarks) * 100

// Example:
// Obtained: 75 marks
// Total: 100 marks
// Percentage = (75 / 100) * 100 = 75%

4. Leaderboard (MongoDB Aggregation)

// Aggregation Pipeline
db.results.aggregate([
  {
    $group: {
      _id: '$studentName',
      averageScore: { $avg: '$percentage' },
      totalAttempts: { $sum: 1 },
      totalScore: { $sum: '$score' }
    }
  },
  { $sort: { averageScore: -1 } },
  { $limit: 100 }
])

5. Logging System

  • Logs stored in data/logs.txt
  • Format: [timestamp] METHOD URL - IP: ipaddress
  • Uses fs module for file operations
  • Automatic file creation if not exists

6. Error Handling

  • Centralized error middleware
  • Validation error handling
  • Database error handling
  • 404 page not found
  • Custom error views

7. Events

  • userRegistered - When new user registers
  • userLogin - When user logs in
  • quizCreated - When quiz is created
  • quizSubmitted - When quiz is submitted
  • Event logging to console

πŸ§ͺ Testing the Application

Test Accounts

  1. Create a student account:

    • Go to /register
    • Fill in name, email, password
    • Login with student role
  2. Admin account (use default or create):

    • Login with admin role
    • Access /admin/dashboard

Test Workflow

As Admin:

  1. Create a quiz (e.g., "Math Quiz")
  2. Add questions to the quiz
  3. View dashboard statistics

As Student:

  1. Register and login
  2. Browse available quizzes
  3. Start a quiz and answer questions
  4. Submit and view results
  5. Check leaderboard
  6. View attempt history

πŸ›‘οΈ Middleware Explained

Logger Middleware

// Logs all HTTP requests
// File: middleware/loggerMiddleware.js
// Output: data/logs.txt

Error Middleware

// Centralized error handling
// File: middleware/errorMiddleware.js
// Handles validation, database, and server errors

Auth Middleware

// isAuthenticated - Check if logged in
// isAdmin - Check if admin role
// isStudent - Check if student role
// File: middleware/authMiddleware.js

πŸ“ Sample Data / Dummy Data

Sample Admin User

{
  name: "Admin User",
  email: "admin@quizmaster.com",
  password: "admin123",
  role: "admin"
}

Sample Student User

{
  name: "John Doe",
  email: "john@example.com",
  password: "student123",
  role: "student"
}

Sample Quiz

{
  title: "General Knowledge Quiz",
  category: "General Knowledge",
  difficulty: "Medium",
  totalMarks: 50,
  timeLimit: 30,
  createdBy: ObjectId("admin"),
  createdAt: "2024-05-10"
}

To add sample data, use MongoDB shell or Compass.


🎨 UI/UX Features

Design Principles

  • Clean, professional interface
  • Responsive design (mobile-friendly)
  • Intuitive navigation
  • Consistent color scheme
  • Easy-to-read typography

Color Scheme

  • Primary: #3498db (Blue)
  • Secondary: #2ecc71 (Green)
  • Danger: #e74c3c (Red)
  • Warning: #f39c12 (Orange)

Key UI Components

  • Navigation bar (sticky)
  • Quiz cards with metadata
  • Quiz timer with countdown
  • Result cards with scores
  • Leaderboard table
  • Form validations
  • Error/success alerts

🚨 Error Handling

Error Pages

  • 404 Not Found - Invalid URL
  • 403 Forbidden - Insufficient permissions
  • 500 Server Error - Server issues

Validation Errors

  • Empty form fields
  • Invalid email format
  • Password mismatch
  • Duplicate email
  • Invalid quiz/question ID

Database Errors

  • Connection failures
  • Validation errors
  • Duplicate key errors
  • Invalid object IDs

πŸ“ˆ Analytics & Reporting

Admin Analytics Dashboard

  • Total students count
  • Total quizzes count
  • Total attempts count
  • Average score percentage
  • Top performing students
  • Attempts per quiz
  • Score distribution

Report Generation

Uses MongoDB aggregation pipeline:

// Example: Average score per quiz
db.results.aggregate([
  { $group: { _id: '$quizTitle', avg: { $avg: '$percentage' } } }
])

πŸ” Code Quality

Best Practices

  • βœ… MVC architecture followed
  • βœ… Async/await for all database operations
  • βœ… Error handling with try/catch
  • βœ… Input validation on all routes
  • βœ… Session-based authentication
  • βœ… Middleware for cross-cutting concerns
  • βœ… RESTful API design
  • βœ… Comments throughout code
  • βœ… Modular file structure
  • βœ… Separation of concerns

πŸ“š Learning Outcomes

This project demonstrates:

  • Node.js core modules (fs, path, events)
  • Express.js routing and middleware
  • MongoDB CRUD operations
  • MongoDB aggregation pipeline
  • EJS templating engine
  • MVC architecture implementation
  • RESTful API design
  • Session-based authentication
  • Error handling patterns
  • Async/await programming
  • Event-driven programming

πŸ› Troubleshooting

MongoDB Connection Error

Error: Cannot connect to MongoDB
Solution: Ensure MongoDB is running on port 27017

Port Already in Use

Error: EADDRINUSE: address already in use :::3000
Solution: Change PORT or kill process using port 3000

Session Not Working

Error: Session data not persisting
Solution: Ensure express-session is properly configured

Views Not Rendering

Error: Cannot find views
Solution: Check views path in app.js, ensure EJS is set as engine

πŸ“ž Support & Contact

For issues or questions:

  1. Check the logs in data/logs.txt
  2. Review console error messages
  3. Check browser console for client-side errors
  4. Verify MongoDB connection
  5. Ensure all dependencies are installed

πŸ“„ License

This project is developed for educational purposes as part of a backend development course.


🎯 Future Enhancements

  • Email notifications
  • Password reset functionality
  • Question bank with categories
  • Question difficulty analysis
  • Performance charts and graphs
  • Export results to PDF
  • Multi-language support
  • Two-factor authentication
  • API documentation (Swagger)

βœ… Course Requirements Met

βœ… Node.js asynchronous programming
βœ… Core Node.js modules (fs, path, events)
βœ… Express.js routing
βœ… EJS templates
βœ… REST APIs
βœ… Middleware & error handling
βœ… MongoDB CRUD & Aggregation
βœ… MVC architecture
βœ… DTO & Guards (role-based)
βœ… Manual implementations (no external auth libs)


Created for: Backend Development Course
Created by: Muhammad Afzal Kalwar, Ayesha Bibi, Hafsa Kanwal Awan
Date: May 2024
Version: 1.0.0

About

A complete online testing and quiz management system built with Node.js, Express.js, MongoDB, EJS, and MVC architecture featuring authentication, quiz management, analytics, and leaderboard functionality.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages