π Quick Start β’ β¨ Features β’ π Architecture β’ π³ Docker Deep Dive β’ π Academic Report β’ π¦ API Routes
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.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β‘ 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 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- Executive Summary
- System Architecture
- Core Features
- Tech Stack Architecture
- Quick Start Guide
- Default Login Credentials
- Project Directory Layout
- Database Relational Architecture
- API & Blueprint Reference
- Configuration Matrix (
.env) - Docker Architecture & Multi-Stage Builds
- Continuous Integration (CI/CD) Pipeline
- Automated Testing & Quality Assurance
- Documentation Index
- Academic Context & Credits
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
- π 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.
- π 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.
- π 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 configurableSecure=Truefor 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.
- β‘ 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
HEALTHCHECKsocket probe monitoring server responsiveness every 30 seconds. - π Multi-Stage CI/CD: GitHub Actions automating Flake8 linting, unit test execution, and live container validation.
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# 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# 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
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(Executesdocker compose up -d --buildwith status messages).
BrainCheck automatically initializes the database schema and seeds default topics, questions, and a pre-configured administrator on first boot:
| Role | 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.
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)
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
}
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 |
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 |
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
- Layer Cache Efficiency:
requirements.txtis 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
HEALTHCHECKperiodically checks socket responsiveness.
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]
- Linting (
flake8): Validates syntax integrity and PEP 8 compliance. - Automated Unit Testing (
unittest): Runs 6 test fixtures against an isolated in-memory test database. - Multi-Stage Docker Build: Compiles container image with Buildx layer caching.
- Live Container Validation: Boots container in CI runner, sleeps for startup, executes HTTP status code checks (
curl), and captures logs.
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" -vtest_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)
Explore the comprehensive technical manuals in the docs/ folder:
- π Formal Academic Capstone Report β Complete 5-chapter formal internship report.
- π System Architecture Deep-Dive β Detailed component design, data flow, and security specifications.
- π¦ API & Route Reference Manual β Complete endpoint, payload schema, and session catalog.
- π³ Docker & Containerization Guide β Multi-stage builds, volume durability, and security hardening.
- π€ Contributing & Code Standards β Developer setup, branching strategy, and pull request checklist.
This project was developed as a Capstone Project for B.Tech Computer Science and Engineering (CSE) at Lovely Professional University (LPU), Punjab.
- Author & Developer: Priya Ranjan
- Registration Number:
12419647 - GitHub Repository: https://github.com/Priya-Ranjan-0201/BrainCheck