Skip to content

Repository files navigation

🧠 BrainCheck β€” Containerized MCQ Quiz Platform

Next-Generation Cloud-Native Assessment Platform Powered by Python, Flask, Docker & CI/CD

Python Version Flask Framework Docker Multi-Stage Docker Compose Bootstrap 5.3 SQLite Database CI/CD Pipeline Security Hardened Academic Capstone License: MIT


πŸš€ Quick Start β€’ ✨ Features β€’ πŸ› Architecture β€’ 🐳 Docker Deep Dive β€’ πŸ“‘ Academic Report β€’ 🚦 API Routes



πŸ“– Executive Summary

BrainCheck is an enterprise-grade, fully containerized Multiple-Choice Question (MCQ) assessment web application engineered with modern cloud-native standards. Built using Python 3.13 and Flask 3.x, the platform features a dynamic, randomized assessment engine with real-time countdown timers, interactive score progression analytics, and a comprehensive administrative portal with full CRUD controls.

The entire system is packaged inside an optimized 2-stage multi-stage Docker build, enforcing least-privilege non-root execution (appuser), persistent volume storage (braincheck_data), and self-healing container healthchecks. It is verified through automated GitHub Actions CI/CD workflows covering code quality linting (Flake8), unit test suites, and live container validation.


🌟 Key Highlights at a Glance

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  ⚑ Ultra-Fast Multi-Stage Docker Build (<180 MB lean runtime)             β”‚
β”‚  πŸ›‘οΈ Defense-in-Depth Security: PBKDF2 Hashing, CSRF Tokens, Non-Root UID    β”‚
β”‚  ⏱️ Real-Time Countdown Timer with Zero-Latency Auto-Submit Fallback        β”‚
β”‚  πŸ”€ Deterministic Session Shuffling for Fair & Unbiased Testing             β”‚
β”‚  πŸ“Š Canvas Analytics Engine: Score progression charts & performance meters  β”‚
β”‚  πŸ‘‘ Full Admin Suite: Dynamic Categories, Question Authoring & User Audits   β”‚
β”‚  πŸ”„ Self-Seeding Database: Instantly launches with pre-loaded quiz topics   β”‚
β”‚  πŸš€ Production-Ready CI/CD: Automated linting, test runner & Docker health   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“‘ Table of Contents


πŸ› System Architecture

BrainCheck implements the Application Factory Pattern with modular Flask Blueprints, cleanly separating authentication, student dashboard analytics, quiz session states, and administrative CRUD operations.

graph TD
    Client([🌐 Client Web Browser])

    subgraph Container Boundary ["🐳 Docker Runtime Container (Port 5000)"]
        subgraph Routing & Controller Layer
            AppFactory["βš™οΈ App Factory (create_app)"]
            AuthBP["πŸ” auth_bp: /auth"]
            MainBP["πŸ“Š main_bp: /dashboard"]
            QuizBP["🎯 quiz_bp: /quiz"]
            AdminBP["πŸ›‘οΈ admin_bp: /admin"]
        end

        subgraph Middleware & Security
            LoginMgr["πŸ”‘ Flask-Login (Session State)"]
            CSRFMgr["πŸ›‘οΈ Flask-WTF (CSRF Protection)"]
            RBACGuard["πŸ‘‘ @admin_required (RBAC Guard)"]
        end

        subgraph Domain & Persistence Layer
            ORM["πŸ—„οΈ Flask-SQLAlchemy ORM"]
            Models["πŸ“¦ User | Category | Question | Attempt"]
        end
    end

    subgraph Storage ["πŸ’Ύ Persistent Named Volume"]
        DB[("πŸ’½ database.db (/app/instance)")]
    end

    Client <-->|HTTP GET / POST| AppFactory
    AppFactory --> AuthBP & MainBP & QuizBP & AdminBP
    AuthBP & MainBP & QuizBP & AdminBP --> LoginMgr
    AuthBP & MainBP & QuizBP & AdminBP --> CSRFMgr
    AdminBP --> RBACGuard
    AuthBP & MainBP & QuizBP & AdminBP --> ORM --> Models --> DB
Loading

✨ Core Features

πŸ‘¨β€πŸŽ“ Student Assessment Portal

  • πŸ” Secure Onboarding: Fast registration and login powered by cryptographic password hashing (PBKDF2 SHA-256).
  • πŸ“š Categorized Exploration: Browse pre-seeded quiz topics (Python, Docker, JavaScript, General Knowledge) with live question counters.
  • πŸ”€ Smart Shuffling Engine: Questions are automatically shuffled into random sequences and preserved in user session state.
  • ⏱️ Visual Countdown Timer: Real-time JavaScript timer bar with automated form submission upon timeout.
  • πŸ” Bidirectional Navigation: Step forward and backward through questions with automatic radio selection memory.
  • πŸ“ˆ Instant Detailed Scorecard: Immediate evaluation with overall percentage badge, correct answer highlights, and review breakdown.
  • πŸ“Š Historical Performance Analytics: Personal dashboard tracking total quizzes attempted, average score, personal best, and past test records.

πŸ›‘οΈ Administrative Control Center

  • πŸ‘‘ Role-Based Access Control: Strict access guard (@admin_required) preventing privilege escalation.
  • πŸ“Š Executive Dashboard: System-wide metric cards for total users, admins, categories, questions, attempts, and overall platform average.
  • πŸ“ Dynamic Category Manager: Create, view, and safely cascade-delete quiz categories.
  • πŸ“ Full MCQ Authoring Suite: Create, edit, filter, and delete 4-option MCQs with dynamic category binding.
  • πŸ‘₯ User Audit Directory: Real-time inspection of all registered student accounts and timestamps.
  • πŸ“œ Platform-Wide Attempt Logs: Comprehensive history of all student submissions and scores.

πŸ”’ Security & Hardening Model

  • πŸ”‘ Cryptographic Salting & Hashing: Powered by Werkzeug's PBKDF2 SHA-256 hashing.
  • πŸ›‘οΈ CSRF Token Enforcement: Every form submission validated with cryptographically signed tokens via Flask-WTF.
  • πŸͺ Hardened Session Cookies: Configured with HTTPOnly=True, SameSite=Lax, and configurable Secure=True for HTTPS.
  • πŸ‘€ Non-Root Container Sandboxing: Runs inside Docker as dedicated unprivileged user appuser:appgroup (UID 10001).
  • πŸ’‰ SQL Injection Immunity: Zero raw SQL concatenation; 100% parameterized queries via SQLAlchemy ORM.

🐳 Cloud-Native & DevOps Standards

  • ⚑ 2-Stage Multi-Stage Build: Isolates build tools in stage 1; yields an ultra-lean runtime container in stage 2.
  • πŸš€ Layer-Caching Optimization: Dependency layer is cached independently from application source code.
  • πŸ’Ύ Named Volume Durability: Database file preserved across container destroys via braincheck_data.
  • 🩺 Container Self-Healing: Built-in HEALTHCHECK socket probe monitoring server responsiveness every 30 seconds.
  • πŸ”„ Multi-Stage CI/CD: GitHub Actions automating Flake8 linting, unit test execution, and live container validation.

πŸ›  Tech Stack Architecture

Layer Technology Version Purpose
Language Python 3.13 Core runtime and backend logic
Framework Flask 3.x WSGI web application routing & Blueprints
ORM / DB SQLAlchemy SQLite 3.x Relational schema modeling & data storage
Auth & Security Flask-Login CSRF Latest User sessions, PBKDF2 hashing, and CSRF protection
Frontend UI Bootstrap 5.3 Mobile-first responsive styling and icons
Charts HTML5 Canvas ES6 Interactive score progression visualization
Container Engine Docker Latest Container runtime & multi-stage packaging
Orchestrator Compose v2 Service lifecycle, healthchecks, and volumes
Testing Unittest Built-in Test fixtures & route assertion framework
CI/CD GitHub Actions v4 Automated linting, test suite, and container health verification

πŸš€ Quick Start Guide

Option 1: 🐳 Docker Compose (Recommended)

The fastest and most reliable way to launch the entire stack:

# 1. Clone the repository
git clone https://github.com/Priya-Ranjan-0201/BrainCheck.git
cd BrainCheck

# 2. Build image and launch container in detached mode
docker compose up -d --build

# 3. View live server logs
docker compose logs -f web

🌐 Open in your browser: http://localhost:5000

To stop the container:

docker compose down

Option 2: πŸ“¦ Docker Direct CLI

# Build the Docker image
docker build -t braincheck:latest .

# Run container with persistent volume mount
docker run -d \
  --name braincheck_web \
  -p 5000:5000 \
  -v braincheck_data:/app/instance \
  -e SECRET_KEY="custom-production-secret-key" \
  braincheck:latest

Option 3: 🐍 Local Python Virtualenv

# 1. Clone and enter directory
git clone https://github.com/Priya-Ranjan-0201/BrainCheck.git
cd BrainCheck

# 2. Create and activate a virtual environment
python -m venv .venv
# On Windows (PowerShell / CMD):
.venv\Scripts\activate
# On macOS / Linux:
source .venv/bin/activate

# 3. Install production dependencies
pip install --upgrade pip
pip install -r requirements.txt

# 4. Start the server
python app.py

🌐 Open in your browser: http://127.0.0.1:5000


Option 4: πŸͺŸ Windows One-Click Batch Launchers

Convenient batch scripts are included for Windows developers:

  • Local Python Mode: Double-click run.bat (Sets up .venv, installs requirements, and runs Flask).
  • Docker Compose Mode: Double-click run_docker.bat (Executes docker compose up -d --build with status messages).

πŸ”‘ Default Login Credentials

BrainCheck automatically initializes the database schema and seeds default topics, questions, and a pre-configured administrator on first boot:

Role Email Password Landing Page Access Permissions
Administrator admin@braincheck.com Admin@123 /admin Full CRUD, user directory, global score audits
Student Create at /auth/register Your Password /dashboard Quiz taking, score history, personal scorecard

Tip

Customize the administrator password for production deployments by setting ADMIN_PASSWORD in your .env file or docker-compose.yml.


πŸ“‚ Project Directory Layout

BrainCheck/
β”œβ”€β”€ .dockerignore                 # Excludes venvs, caches, and git files from build context
β”œβ”€β”€ .env.example                  # Environment configuration template
β”œβ”€β”€ .gitignore                    # Git file exclusion rules
β”œβ”€β”€ Dockerfile                    # Production 2-stage multi-stage Docker build
β”œβ”€β”€ docker-compose.yml            # Declarative orchestration & volume persistence
β”œβ”€β”€ requirements.txt              # Production Python package dependencies
β”œβ”€β”€ config.py                     # Centralized application configuration & environment reader
β”œβ”€β”€ extensions.py                 # Isolated Flask extensions (SQLAlchemy, LoginManager, CSRF)
β”œβ”€β”€ app.py                        # App factory, route wiring & auto-database seeder
β”œβ”€β”€ run.bat                       # Windows 1-click launcher for local Python server
β”œβ”€β”€ run_docker.bat                # Windows 1-click launcher for Docker Compose
β”œβ”€β”€ README.md                     # Main project presentation & documentation
β”‚
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── docker-ci.yml         # Advanced pipeline (Flake8 Lint + Test + Live Healthcheck)
β”‚
β”œβ”€β”€ docs/                         # Detailed architectural & technical manuals
β”‚   β”œβ”€β”€ SUMMER_TRAINING_REPORT.md # Formal Academic Capstone Report (LPU B.Tech CSE)
β”‚   β”œβ”€β”€ ARCHITECTURE.md           # Deep dive into system architecture, state machine & data flow
β”‚   β”œβ”€β”€ API_AND_ROUTES.md         # Full endpoint catalog and request/response specifications
β”‚   β”œβ”€β”€ DOCKER_GUIDE.md           # Multi-stage build guide, security hardening & volume docs
β”‚   └── CONTRIBUTING.md           # Developer onboarding, code style & PR workflow
β”‚
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ __init__.py               # Models package initialization
β”‚   └── models.py                 # SQLAlchemy ORM models (User, QuizCategory, Question, Attempt)
β”‚
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ __init__.py               # Blueprints package export
β”‚   β”œβ”€β”€ auth.py                   # Authentication routes (/auth/login, /auth/register, /auth/logout)
β”‚   β”œβ”€β”€ main.py                   # Student dashboard & analytics (/dashboard)
β”‚   β”œβ”€β”€ quiz.py                   # Quiz engine, session shuffling & grading (/quiz/*)
β”‚   └── admin.py                  # Admin control center & CRUD operations (/admin/*)
β”‚
β”œβ”€β”€ templates/                    # Jinja2 HTML layout templates
β”‚   β”œβ”€β”€ base.html                 # Master layout with responsive navbar, flashes & footer
β”‚   β”œβ”€β”€ auth/                     # login.html, register.html
β”‚   β”œβ”€β”€ main/                     # dashboard.html
β”‚   β”œβ”€β”€ quiz/                     # categories.html, quiz.html, result.html, attempts.html
β”‚   └── admin/                    # dashboard.html, categories.html, questions.html,
β”‚                                 # add_question.html, edit_question.html, users.html, attempts.html
β”‚
β”œβ”€β”€ static/
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   └── style.css             # Modern cards, timer UI, badges, and responsive tables
β”‚   └── js/
β”‚       └── main.js               # Countdown timer engine, canvas charts, auto-dismiss alerts
β”‚
└── tests/
    β”œβ”€β”€ __init__.py               # Test package initialization
    └── test_app.py               # Automated unit test suite (6/6 passing test assertions)

πŸ—„ Database Relational Architecture

The database schema utilizes strict foreign key relationships and cascade deletion rules:

erDiagram
    USERS ||--o{ QUIZ_ATTEMPTS : "records"
    QUIZ_CATEGORIES ||--o{ QUESTIONS : "contains"
    QUIZ_CATEGORIES ||--o{ QUIZ_ATTEMPTS : "categorizes"

    USERS {
        int id PK
        string fullname
        string email UK
        string password_hash
        string role
        datetime created_at
    }

    QUIZ_CATEGORIES {
        int id PK
        string name UK
    }

    QUESTIONS {
        int id PK
        int category_id FK
        text question
        string option_a
        string option_b
        string option_c
        string option_d
        string correct_option
    }

    QUIZ_ATTEMPTS {
        int id PK
        int user_id FK
        int category_id FK
        int score
        int total_questions
        float percentage
        datetime completed_at
    }
Loading

🚦 API & Blueprint Reference

For complete payload specifications and request parameters, refer to docs/API_AND_ROUTES.md.

Blueprint Route Method Access Level Description
Root / GET Public Redirects directly to /dashboard/
auth_bp /auth/register GET, POST Public Student account registration
auth_bp /auth/login GET, POST Public User authentication & session generation
auth_bp /auth/logout GET Authenticated Terminates user session
main_bp /dashboard/ GET Authenticated Student analytics & available topics
quiz_bp /quiz/categories GET Authenticated Browse active quiz categories
quiz_bp /quiz/start/<id> GET Authenticated Initializes randomized session & timer
quiz_bp /quiz/take GET, POST Authenticated Question navigation & radio answer memory
quiz_bp /quiz/submit GET, POST Authenticated Evaluates answers & commits QuizAttempt
quiz_bp /quiz/result GET Authenticated Renders score percentage & question review
quiz_bp /quiz/attempts GET Authenticated Personal historical test logs
admin_bp /admin/ GET Admin Only Global metrics and system overview
admin_bp /admin/categories GET, POST Admin Only Category list & creation form
admin_bp /admin/categories/delete/<id> POST Admin Only Cascade deletion of category
admin_bp /admin/questions GET Admin Only Question inventory with category filter
admin_bp /admin/questions/add GET, POST Admin Only MCQ question authoring interface
admin_bp /admin/questions/edit/<id> GET, POST Admin Only Question updating interface
admin_bp /admin/questions/delete/<id> POST Admin Only Permanently deletes a question
admin_bp /admin/users GET Admin Only View all registered student accounts
admin_bp /admin/attempts GET Admin Only System-wide attempt logs & scores

βš™ Configuration Matrix (.env)

All parameters are configurable via environment variables or a .env file:

Environment Variable Default Value Description
FLASK_APP app.py Primary WSGI application entrypoint
FLASK_ENV production Environment mode (development, production, testing)
FLASK_DEBUG False Debug mode (Always keep False in production)
FLASK_HOST 0.0.0.0 Host IP address binding
FLASK_PORT / PORT 5000 HTTP port on which the server listens
SECRET_KEY braincheck-secret-key-change-me Cryptographic secret for session cookie signing & CSRF
DATABASE_URL sqlite:///instance/database.db SQLAlchemy connection string
QUIZ_TIME_LIMIT 300 Default time allowed per quiz in seconds (5 minutes)
ADMIN_EMAIL admin@braincheck.com Email for initial administrator account
ADMIN_PASSWORD Admin@123 Password for initial administrator account
SESSION_COOKIE_SECURE False Enforce HTTPS-only cookie transmission
SESSION_COOKIE_HTTPONLY True Mitigate XSS session hijacking
SESSION_COOKIE_SAMESITE Lax SameSite cookie policy

🐳 Docker Architecture & Multi-Stage Builds

BrainCheck utilizes a production 2-Stage Multi-Stage Build designed for security, minimal size, and ultra-fast rebuilds:

flowchart TD
    subgraph Stage1 ["Stage 1: Builder (python:3.13-slim)"]
        A1[Install build-essential] --> B1[Copy requirements.txt]
        B1 --> C1[Build Python Wheels in /opt/venv]
    end

    subgraph Stage2 ["Stage 2: Final Runtime (python:3.13-slim)"]
        A2[Create unprivileged user appuser:appgroup] --> B2["COPY --from=builder /opt/venv"]
        B2 --> C2[COPY application source]
        C2 --> D2[Create & chown /app/instance]
        D2 --> E2[USER appuser]
        E2 --> F2[HEALTHCHECK socket probe]
        F2 --> G2[ENTRYPOINT: python app.py]
    end

    Stage1 -->|Virtual Environment Artifacts| Stage2
Loading

Key Engineering Benefits:

  • Layer Cache Efficiency: requirements.txt is installed before copying source code; application edits rebuild in under 2 seconds.
  • Stripped Bloat: Compilers (gcc, make) and apt package caches are stripped, reducing image size to <180 MB.
  • Non-Root Hardening: Runs under appuser (UID 10001) preventing container breakout privilege escalation.
  • Self-Healing Probes: Native Docker HEALTHCHECK periodically checks socket responsiveness.

πŸ”„ Continuous Integration (CI/CD) Pipeline

Every pull request and push to main triggers our GitHub Actions pipeline:

flowchart LR
    A[Git Push / PR] --> B[Job 1: πŸ” Flake8 Lint]
    B --> C[Job 2: πŸ§ͺ Run Unittests]
    C --> D[Job 3: 🐳 Docker Build]
    D --> E[Job 4: 🩺 Live Health Check]
    E --> F[βœ… Merge Ready]
Loading
  1. Linting (flake8): Validates syntax integrity and PEP 8 compliance.
  2. Automated Unit Testing (unittest): Runs 6 test fixtures against an isolated in-memory test database.
  3. Multi-Stage Docker Build: Compiles container image with Buildx layer caching.
  4. Live Container Validation: Boots container in CI runner, sleeps for startup, executes HTTP status code checks (curl), and captures logs.

πŸ§ͺ Automated Testing & Quality Assurance

BrainCheck includes a comprehensive automated test suite built with Python's unittest framework:

# Execute test suite locally:
python -m unittest discover -s tests -p "test_*.py" -v

Verified Test Matrix:

  • test_index_redirects_to_dashboard β€” Asserts root route / redirects to dashboard/login (302).
  • test_database_category_seed β€” Verifies default categories and questions seed on initial boot.
  • test_user_registration β€” Validates user entity creation and password hashing.
  • test_user_login_validation β€” Tests credential matching and invalid login rejection.
  • test_dashboard_unauthenticated_redirect β€” Verifies protected views redirect unauthenticated users.
  • test_admin_route_protection_by_default β€” Asserts standard users receive access denials on /admin/*.
Ran 6 tests in 3.409s
OK (100% Passing)

πŸ“š Documentation Index

Explore the comprehensive technical manuals in the docs/ folder:


πŸŽ“ Academic Context & Credits

This project was developed as a Capstone Project for B.Tech Computer Science and Engineering (CSE) at Lovely Professional University (LPU), Punjab.


⭐ Support the Project

If you find this project helpful or inspiring, please consider giving it a Star on GitHub!

Built with ❀️ for students, educators, and cloud-native enthusiasts.

About

🧠 Containerized cognitive assessment & quiz architecture platform β€” modular Flask Blueprints, PostgreSQL schemas & Docker Compose.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages