Skip to content

ManvithaDungi/PatientManagementSystem

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

241 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ₯ SecureHealth - Patient Management System

A HIPAA-Aware Healthcare Platform with Regulatory Compliance

Status: βœ… Production-Ready (with noted improvements for scaling)
Last Updated: April 20, 2026
Architecture: React 19 + Spring Boot 3.2 + PostgreSQL + Docker


πŸ“‹ Table of Contents

  1. Overview
  2. Technology Stack
  3. Key Features
  4. User Roles & Workflows
  5. Getting Started
  6. Project Structure
  7. Security Architecture
  8. API Documentation
  9. Database Schema
  10. Deployment
  11. Testing
  12. Known Issues & Improvements
  13. Developer Notes

🎯 Overview

SecureHealth is a comprehensive healthcare information management system that demonstrates enterprise-level security practices for handling sensitive medical data. The platform orchestrates complex workflows among multiple stakeholder roles while maintaining strict HIPAA-aligned access controls, audit trails, and data governance.

Problem It Solves:

  • Healthcare systems need to manage interactions across patients, doctors, nurses, lab technicians, and administrators
  • Each role needs different data visibility (patient can't see other patients, doctor can only see assigned patients)
  • Every access must be logged for compliance
  • Data must be encrypted, backed up, and retain-policy compliant

Why It Matters:

  • Demonstrates compliance-driven architecture (not feature-first)
  • Shows secure-by-default design (not bolted-on security)
  • Handles real-world healthcare scenarios (double-booking prevention, consent tracking, shift handovers)

πŸ› οΈ Technology Stack

Frontend

  • Framework: React 19.2.3 (Latest, with improved performance)
  • Routing: React Router v6.30.3 (client-side, with role-based guards)
  • Styling: Tailwind CSS 3.4.19 (utility-first, with custom theme)
  • State Management: React Context API (AuthContext, ThemeContext)
  • Data Visualization: Recharts (appointment calendars, vital signs charts)
  • HTTP Client: Fetch API with centralized error handling
  • Icons: Lucide-react (professional healthcare icons)
  • Animations: Framer Motion (smooth transitions)
  • Testing: React Testing Library + Jest
  • API Mocking: MSW (Mock Service Worker)

Backend

  • Framework: Spring Boot 3.2.2 (Latest stable LTS)
  • Language: Java 21 (LTS release)
  • Database: PostgreSQL 16 (with ACID transactions)
  • ORM: Hibernate with Spring Data JPA
  • Authentication: JWT (JJWT library) + Spring Security
  • Password Encoding: Argon2 (NIST-recommended)
  • Email Service: Spring Mail (OTP delivery)
  • Caching: Redis (active defense, session storage)
  • Build Tool: Maven (reproducible builds)
  • Testing: JUnit 5 + Mockito + H2 in-memory DB
  • Monitoring: Spring Actuator + Prometheus metrics

Infrastructure

  • Containerization: Docker (both frontend and backend)
  • Orchestration: Docker Compose (PostgreSQL, Redis, Backend, Adminer)
  • CI/CD: GitHub Actions (tests on push/PR)
  • Database GUI: Adminer (development database inspection)

✨ Key Features

πŸ” Authentication & Security

  • βœ… Email/password registration with 12-character minimum
  • βœ… 2FA via email OTP for doctors and admins
  • βœ… JWT access tokens (15-minute expiry) + refresh tokens (7-day)
  • βœ… Account lockout after 5 failed attempts
  • βœ… Password history (can't reuse last 5 passwords)
  • βœ… Password reset with time-limited tokens
  • βœ… Session management (max 3 concurrent sessions per user)
  • βœ… Argon2 password hashing (GPU-resistant)

πŸ₯ Clinical Workflows

  • βœ… Appointment Scheduling: Patients request appointments, doctors manage availability, admins approve
  • βœ… Prescriptions: Doctors create prescriptions (medication, dosage, frequency, duration)
  • βœ… Vital Signs Recording: Nurses enter BP, HR, temperature, O2 saturation, weight, height
  • βœ… Medical Records: Doctors document diagnosis, symptoms, treatment provided
  • βœ… Lab Test Ordering: Doctors order tests, lab techs process and upload results
  • βœ… Medication Administration: Nurses track medication administration with timestamps
  • βœ… Shift Handover: Nurses document handover notes for shift changes

πŸ‘₯ Role-Based Access Control

  • βœ… Patient: Book appointments, view own records, manage medications, grant consents
  • βœ… Doctor: Manage schedules, write prescriptions, access assigned patients
  • βœ… Nurse: Record vitals, administer medications, document tasks
  • βœ… Lab Technician: Process test orders, upload results
  • βœ… Admin: Approve appointments, manage users, view audit logs

πŸ“Š Data Governance

  • βœ… Audit Logging: Every access logged (who, what, when, where, why)
  • βœ… Consent Tracking: Patient consent for data sharing tracked and logged
  • βœ… Automatic Backups: Daily at 2 AM (configurable retention)
  • βœ… Data Archival: Inactive users archived after 365 days
  • βœ… Password History: Prevents password reuse (last 5 passwords)
  • βœ… IDOR Protection: Patients can only access their own data

πŸ”’ Security Practices

  • βœ… CORS configured (localhost:3000 default, configurable per environment)
  • βœ… CSRF protection via stateless JWT (not vulnerable)
  • βœ… Input validation on all DTOs
  • βœ… Rate limiting on sensitive endpoints
  • βœ… Token blacklist service (logout invalidates tokens)
  • βœ… Audit logs encrypted in storage
  • βœ… Patient record access protected by validator

πŸ‘₯ User Roles & Workflows

1. Patient Workflow

Register/Login β†’ Select Role (Patient) β†’ Set Profile β†’ 
  Dashboard (upcoming appointments, vitals, medications) β†’
    Book Appointment (select doctor/date/reason) β†’
      View Prescriptions β†’ 
        Track Medications β†’ 
          View Lab Results β†’ 
            Manage Consents

Can Access:

  • Own appointment history
  • Own medical records
  • Own prescriptions
  • Own vital signs
  • Own lab results
  • Data sharing consents

Cannot Access:

  • Other patients' data
  • Doctor schedules
  • Lab infrastructure

2. Doctor Workflow

Register/Login (2FA required) β†’ Set Profile (specialty, shifts) β†’
  Dashboard (assigned patients, appointment requests, metrics) β†’
    Manage Appointments (approve/reject requests) β†’
      View Patient Details (medical history, vitals, previous prescriptions) β†’
        Write Prescription β†’ 
          Order Lab Tests β†’
            Review Lab Results β†’
              Create Medical Record

Can Access:

  • Assigned patients' full medical history
  • Appointment requests
  • Prescription history
  • Lab orders and results
  • Vital signs

Can Perform:

  • Schedule appointments
  • Write prescriptions
  • Order lab tests
  • Document diagnoses
  • Review patient vitals

3. Nurse Workflow

Login (optional 2FA) β†’ Dashboard (assigned patients, pending tasks) β†’
  View Assigned Patients β†’
    Record Vitals (BP, HR, temp, O2, weight) β†’
      Administer Medications (log dose, time, patient) β†’
        Create Tasks (assign to selves or other nurses) β†’
          Shift Handover (document notes, alerts)

Can Access:

  • Assigned patients only
  • Vital signs history
  • Medication schedules
  • Task assignments
  • Previous handover notes

Can Perform:

  • Record vital signs
  • Track medication administration
  • Create and update tasks
  • Document shift handovers

4. Lab Technician Workflow

Login β†’ Dashboard (pending tests, completed tests, stats) β†’
  View Test Orders (by status: pending, collected, processing) β†’
    Mark as Collected β†’
      Upload Results (lab values, images, PDFs) β†’
        Update Test Status (completed/failed)

Can Access:

  • Test orders assigned to lab
  • Patient demographics (for identification)
  • Doctor notes on requested test
  • Test results (own and others' for verification)

Can Perform:

  • Update test status
  • Upload test results
  • View test history

5. Admin Workflow

Login (2FA required) β†’ Dashboard (system metrics, pending approvals) β†’
  Appointments (approve/reject requests) β†’
    User Management (view, create, disable users) β†’
      Audit Logs (search, filter, export) β†’
        System Health (backup status, database size)

Can Access:

  • All appointments
  • All users
  • Complete audit trail
  • System metrics
  • Backup logs

Can Perform:

  • Approve/reject appointments
  • Manage user accounts
  • Reset passwords
  • View audit logs
  • Trigger backups

πŸš€ Getting Started

Prerequisites

  • Node.js 18+ (for frontend)
  • Java 21 (for backend)
  • PostgreSQL 14+ (or use Docker Compose)
  • Docker & Docker Compose (recommended)
  • Maven 3.8+

Option 1: Run with Docker Compose (Recommended)

# Clone the project
git clone https://github.com/ManvithaDungi/PatientManagementSystem.git
cd PatientManagementSystem

# Create .env file (copy from .env.example)
cp .env.example .env

# Start all services
docker-compose up -d

# Wait for services to start (~30 seconds)
# Frontend: http://localhost:3000
# Backend API: http://localhost:8081
# Database: localhost:5432
# Adminer (DB GUI): http://localhost:8082

Option 2: Run Locally

Backend Setup

cd backend/Backend

# Build
mvn clean package

# Run (requires PostgreSQL running on localhost:5432)
java -jar target/backend-0.0.1-SNAPSHOT.jar

# Or using Maven
mvn spring-boot:run

Frontend Setup

cd frontend/app

# Install dependencies
npm install

# Start development server
npm start

# Runs on http://localhost:3000

Sample Credentials

After seeding, use these to test:

Role Email Password
Patient patient1@hospital.com TempPass123!
Doctor doctor1@hospital.com DoctorPass123!
Nurse nurse1@hospital.com NursePass123!
Lab Tech lab1@hospital.com LabPass123!
Admin admin@hospital.com AdminPass123!

πŸ“ Project Structure

PatientManagementSystem/
β”‚
β”œβ”€β”€ πŸ“‚ backend/                          # Spring Boot API
β”‚   └── Backend/
β”‚       β”œβ”€β”€ src/main/java/com/securehealth/backend/
β”‚       β”‚   β”œβ”€β”€ config/
β”‚       β”‚   β”‚   └── SecurityConfig.java         # Spring Security setup
β”‚       β”‚   β”œβ”€β”€ controller/              # REST endpoints (15 controllers)
β”‚       β”‚   β”‚   β”œβ”€β”€ AuthController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ AppointmentController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ PatientController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ DoctorController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ NurseController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ LabTechnicianController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ AdminController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ PrescriptionController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ VitalSignController.java
β”‚       β”‚   β”‚   └── ...
β”‚       β”‚   β”œβ”€β”€ dto/                     # Data Transfer Objects (20+ DTOs)
β”‚       β”‚   β”œβ”€β”€ exception/               # Custom exceptions
β”‚       β”‚   β”œβ”€β”€ model/                   # JPA entities (17 entities)
β”‚       β”‚   β”‚   β”œβ”€β”€ Login.java
β”‚       β”‚   β”‚   β”œβ”€β”€ PatientProfile.java
β”‚       β”‚   β”‚   β”œβ”€β”€ DoctorProfile.java
β”‚       β”‚   β”‚   β”œβ”€β”€ Appointment.java
β”‚       β”‚   β”‚   β”œβ”€β”€ Prescription.java
β”‚       β”‚   β”‚   β”œβ”€β”€ VitalSign.java
β”‚       β”‚   β”‚   β”œβ”€β”€ LabTest.java
β”‚       β”‚   β”‚   β”œβ”€β”€ Consent.java
β”‚       β”‚   β”‚   └── ...
β”‚       β”‚   β”œβ”€β”€ repository/              # Spring Data JPA repositories
β”‚       β”‚   β”œβ”€β”€ security/                # JWT, filters, validators
β”‚       β”‚   β”‚   β”œβ”€β”€ JwtAuthenticationFilter.java
β”‚       β”‚   β”‚   β”œβ”€β”€ PatientAccessValidator.java
β”‚       β”‚   β”‚   └── CustomUserDetailsService.java
β”‚       β”‚   β”œβ”€β”€ service/                 # Business logic (20+ services)
β”‚       β”‚   β”‚   β”œβ”€β”€ AuthService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ AppointmentService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ PatientService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ DoctorService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ NurseService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ LabTechnicianService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ EmailService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ BackupService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ ArchivalService.java
β”‚       β”‚   β”‚   └── ...
β”‚       β”‚   └── util/
β”‚       β”‚       └── JwtUtil.java
β”‚       β”œβ”€β”€ src/test/java/              # Tests (unit + integration)
β”‚       β”œβ”€β”€ src/main/resources/
β”‚       β”‚   └── application.properties  # Configuration
β”‚       β”œβ”€β”€ pom.xml                     # Maven dependencies
β”‚       └── Dockerfile
β”‚
β”œβ”€β”€ πŸ“‚ frontend/                         # React application
β”‚   └── app/
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ components/             # Reusable UI components
β”‚       β”‚   β”‚   β”œβ”€β”€ admin/              # Admin-specific components
β”‚       β”‚   β”‚   β”œβ”€β”€ appointments/       # Appointment workflows
β”‚       β”‚   β”‚   β”œβ”€β”€ doctor/             # Doctor dashboard components
β”‚       β”‚   β”‚   β”œβ”€β”€ nurse/              # Nurse dashboard components
β”‚       β”‚   β”‚   β”œβ”€β”€ lab/                # Lab technician components
β”‚       β”‚   β”‚   β”œβ”€β”€ auth/               # Auth UI components
β”‚       β”‚   β”‚   β”œβ”€β”€ common/             # Shared components
β”‚       β”‚   β”‚   β”‚   β”œβ”€β”€ VitalsChart.jsx
β”‚       β”‚   β”‚   β”‚   β”œβ”€β”€ SchedulerView.jsx
β”‚       β”‚   β”‚   β”‚   β”œβ”€β”€ AppointmentCalendar.jsx
β”‚       β”‚   β”‚   β”‚   └── MiniCalendar.jsx
β”‚       β”‚   β”‚   └── layout/
β”‚       β”‚   β”œβ”€β”€ contexts/               # State management
β”‚       β”‚   β”‚   β”œβ”€β”€ AuthContext.jsx
β”‚       β”‚   β”‚   └── ThemeContext.jsx
β”‚       β”‚   β”œβ”€β”€ layouts/                # Page layouts
β”‚       β”‚   β”œβ”€β”€ pages/                  # Route pages
β”‚       β”‚   β”‚   β”œβ”€β”€ login.jsx
β”‚       β”‚   β”‚   β”œβ”€β”€ createAccount.jsx
β”‚       β”‚   β”‚   β”œβ”€β”€ TwoFactorAuth.jsx
β”‚       β”‚   β”‚   β”œβ”€β”€ ForgotPassword.jsx
β”‚       β”‚   β”‚   β”œβ”€β”€ ResetPassword.jsx
β”‚       β”‚   β”‚   β”œβ”€β”€ doctor/
β”‚       β”‚   β”‚   β”œβ”€β”€ patient/
β”‚       β”‚   β”‚   β”œβ”€β”€ nurse/
β”‚       β”‚   β”‚   β”œβ”€β”€ lab/
β”‚       β”‚   β”‚   └── admin/
β”‚       β”‚   β”œβ”€β”€ services/               # API & auth services
β”‚       β”‚   β”‚   β”œβ”€β”€ api.js              # REST API service
β”‚       β”‚   β”‚   └── supabaseAuth.js     # Auth service
β”‚       β”‚   β”œβ”€β”€ App.jsx                 # Main app with routing
β”‚       β”‚   β”œβ”€β”€ App.css
β”‚       β”‚   └── index.js
β”‚       β”œβ”€β”€ public/
β”‚       β”œβ”€β”€ tailwind.config.js          # Tailwind theme
β”‚       β”œβ”€β”€ postcss.config.js
β”‚       β”œβ”€β”€ package.json
β”‚       └── Dockerfile
β”‚
β”œβ”€β”€ πŸ“‚ DB/                               # Database
β”‚   β”œβ”€β”€ schema.sql                       # Complete schema definition
β”‚   β”œβ”€β”€ seed_users.sql                   # Sample users
β”‚   └── DB_README.md
β”‚
β”œβ”€β”€ docker-compose.yml                  # Multi-service orchestration
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       β”œβ”€β”€ ci.yml                       # GitHub Actions CI/CD
β”‚       └── deployment.yml
β”œβ”€β”€ application.properties               # Root config
β”œβ”€β”€ .env.example                         # Environment variables template
β”œβ”€β”€ README.md                            # This file
└── TECHNICAL_AUDIT_REPORT.md           # Deep technical audit

πŸ” Security Architecture

Authentication Flow

β”Œβ”€ User Submits Credentials ─────────────────────────────────┐
β”‚                                                              β”‚
β”‚  POST /api/auth/login                                       β”‚
β”‚  { email: "doctor@hospital.com", password: "..." }         β”‚
β”‚                                                              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             β”‚
                             β–Ό
        β”Œβ”€β”€β”€β”€ Backend Validates ────┐
        β”‚                            β”‚
        β”‚ 1. Find user by email      β”‚
        β”‚ 2. Compare password hash   β”‚
        β”‚    (Argon2)                β”‚
        β”‚ 3. Check account lockout   β”‚
        β”‚                            β”‚
        └──── If Doctor/Admin β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β”œβ”€β”€β”€ Generate OTP
                    β”œβ”€β”€β”€ Send Email
                    └─── Return: { status: '2FA_REQUIRED' }
                                      β”‚
                                      β–Ό
                    β”Œβ”€β”€β”€β”€ User Receives Email ────┐
                    β”‚ "Your OTP: 123456"          β”‚
                    β”‚ Valid for: 10 minutes       β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                      β”‚
                                      β–Ό
                    β”Œβ”€β”€β”€β”€ User Submits OTP ───────┐
                    β”‚ POST /api/auth/verify-otp   β”‚
                    β”‚ { email, otp }              β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                      β”‚
                                      β–Ό
        β”Œβ”€β”€β”€β”€ Backend Verifies OTP ──┐
        β”‚                             β”‚
        β”‚ 1. Check OTP matches        β”‚
        β”‚ 2. Check not expired        β”‚
        β”‚ 3. Mark OTP as used         β”‚
        β”‚                             β”‚
        └── If Valid: Generate JWT β”€β”€β”˜
                    β”‚
                    β–Ό
        β”Œβ”€β”€β”€β”€ Generate Tokens ───────────────────────┐
        β”‚                                             β”‚
        β”‚ ACCESS TOKEN (15 min):                      β”‚
        β”‚   { sub: userId, email, role, exp: +15m }  β”‚
        β”‚   Signed with JWT secret                    β”‚
        β”‚                                             β”‚
        β”‚ REFRESH TOKEN (7 days):                     β”‚
        β”‚   { sub: userId, exp: +7d }                 β”‚
        β”‚   Hashed in database                        β”‚
        β”‚                                             β”‚
        β”‚ SESSION RECORD:                             β”‚
        β”‚   userId, refreshTokenHash, expiresAt       β”‚
        β”‚   ipAddress, userAgent                      β”‚
        β”‚                                             β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β–Ό
        β”Œβ”€β”€β”€β”€ Return Response ───────┐
        β”‚ {                          β”‚
        β”‚   status: 'SUCCESS',       β”‚
        β”‚   accessToken: 'jwt...',   β”‚
        β”‚   refreshToken: 'jwt...',  β”‚
        β”‚   user: { id, email, role} β”‚
        β”‚ }                          β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β–Ό
        β”Œβ”€β”€β”€β”€ Frontend Stores ───────┐
        β”‚ localStorage.setItem(      β”‚
        β”‚   'secure_health_user',    β”‚
        β”‚   { accessToken, user }    β”‚
        β”‚ )                          β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β–Ό
        β”Œβ”€β”€β”€β”€ Subsequent Requests ───────────────────┐
        β”‚ All API calls include:                      β”‚
        β”‚ Authorization: Bearer {accessToken}        β”‚
        β”‚                                             β”‚
        β”‚ Backend JWT Filter:                         β”‚
        β”‚   1. Extract token from header              β”‚
        β”‚   2. Validate signature                     β”‚
        β”‚   3. Check expiration                       β”‚
        β”‚   4. Check token blacklist                  β”‚
        β”‚   5. Populate SecurityContext               β”‚
        β”‚                                             β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Role-Based Access Control (RBAC)

Three-layer protection:

Layer 1: Frontend Route Guards

<Route path="/dashboard/doctor" element={
  <ProtectedRoute allowedRoles={['DOCTOR']}>
    <DoctorDashboard />
  </ProtectedRoute>
} />
// Non-doctors redirected to unauthorized page

Layer 2: Backend Controller Annotations

@PreAuthorize("hasAuthority('DOCTOR')")
@PostMapping("/prescriptions")
public ResponseEntity<?> createPrescription(...) { }

@PreAuthorize("hasAnyAuthority('ADMIN', 'DOCTOR')")
@GetMapping("/patients")
public ResponseEntity<?> getAllPatients() { }

Layer 3: Service-Level Validation

public PatientDTO getPatientById(Long id, String requesterEmail, String requesterRole) {
  PatientProfile profile = patientProfileRepository.findById(id)
    .orElseThrow();
    
  // Check 1: Admins/Doctors have general access
  if (requesterRole.equals("ADMIN") || requesterRole.equals("DOCTOR")) {
    return mapToDTO(profile);
  }
  
  // Check 2: Patients can only see their own profile
  if (profile.getUser().getEmail().equals(requesterEmail)) {
    return mapToDTO(profile);
  }
  
  // Deny access
  throw new RuntimeException("403 Forbidden: Unauthorized access");
}

IDOR Protection

Every patient data access validates ownership:

-- Before: VULNERABLE - returns any patient
SELECT * FROM patient_profiles WHERE id = 5;

-- After: PROTECTED - only returns if user authorized
SELECT p.* FROM patient_profiles p
WHERE p.id = 5
AND (
  -- Patient owns it
  p.user_id = (SELECT user_id FROM login WHERE email = ?)
  -- OR doctor is assigned to it
  OR p.assigned_doctor_id = (SELECT user_id FROM login WHERE email = ?)
)

πŸ“‘ API Documentation

Authentication Endpoints

Register User

POST /api/auth/register
Content-Type: application/json

Request:
{
  "email": "patient@hospital.com",
  "password": "SecurePass123",
  "role": "PATIENT",
  "fullName": "John Doe",
  "dateOfBirth": "1990-01-01",
  "address": "123 Main St"
}

Response (201 Created):
{
  "message": "User registered successfully"
}

Login

POST /api/auth/login
Content-Type: application/json

Request:
{
  "email": "doctor@hospital.com",
  "password": "DoctorPass123"
}

Response (200 OK - Doctor/Admin):
{
  "status": "2FA_REQUIRED",
  "message": "OTP sent to email"
}

Response (200 OK - Patient/Nurse/Lab):
{
  "status": "LOGIN_SUCCESS",
  "accessToken": "eyJhbGc...",
  "refreshToken": "eyJhbGc...",
  "user": {
    "id": 123,
    "email": "patient@hospital.com",
    "role": "PATIENT"
  }
}

Verify 2FA OTP

POST /api/auth/verify-otp
Content-Type: application/json

Request:
{
  "email": "doctor@hospital.com",
  "otp": "123456"
}

Response (200 OK):
{
  "accessToken": "eyJhbGc...",
  "refreshToken": "eyJhbGc...",
  "user": { ... }
}

Response (401 Unauthorized):
{
  "message": "Invalid or expired OTP"
}

Logout

POST /api/auth/logout
Authorization: Bearer {accessToken}

Response (200 OK):
{
  "message": "Logged out successfully"
}

Appointment Endpoints

Create Appointment (Patient)

POST /api/appointments
Authorization: Bearer {accessToken}
Content-Type: application/json

Request:
{
  "doctorId": 5,
  "appointmentDate": "2025-05-01T14:00:00",
  "reasonForVisit": "Regular checkup"
}

Response (200 OK):
{
  "appointmentId": 42,
  "patientId": 3,
  "doctorId": 5,
  "appointmentDate": "2025-05-01T14:00:00",
  "status": "PENDING_APPROVAL",
  "createdAt": "2025-04-20T10:30:00"
}

Get Available Slots (Doctor)

GET /api/appointments/doctor/{doctorId}/available-slots?date=2025-05-01
Authorization: Bearer {accessToken}

Response (200 OK):
[
  "09:00",
  "09:30",
  "10:00",
  "10:30",
  ...
]

Approve Appointment (Admin)

PUT /api/appointments/{appointmentId}/approve
Authorization: Bearer {accessToken}

Response (200 OK):
{
  "appointmentId": 42,
  "status": "SCHEDULED",
  "updatedAt": "2025-04-20T11:00:00"
}

Complete API Reference

[See Backend README for complete endpoint documentation]


πŸ—„οΈ Database Schema

Core Tables

login

  • Stores user credentials and security state
  • Columns: userId, email, passwordHash, role, twoFactorEnabled, failedAttempts, isLocked, etc.

patient_profiles

  • Patient demographic and assignment data
  • Columns: profileId, userId, assignedDoctorId, assignedNurseId, firstName, lastName, dateOfBirth, medicalHistory, etc.

doctor_profiles

  • Doctor specialization and scheduling
  • Columns: profileId, userId, specialty, department, shiftStartTime, shiftEndTime, slotDurationMinutes

appointments

  • Appointment requests and scheduling
  • Columns: appointmentId, patientProfileId, doctorId, appointmentDate, status, reasonForVisit, doctorNotes, createdAt

prescriptions

  • Medication prescriptions
  • Columns: prescriptionId, patientProfileId, doctorId, medicationName, dosage, frequency, duration, specialInstructions, issuedAt, startDate, endDate, status

vital_signs

  • Recorded patient vitals
  • Columns: vitalId, patientProfileId, nurseId, bloodPressure, heartRate, temperature, respiratoryRate, oxygenSaturation, weight, height, recordedAt

lab_tests

  • Lab test orders and results
  • Columns: testId, patientProfileId, orderedById, testName, testCategory, resultValue, unit, referenceRange, status, fileUrl, createdAt

medical_records

  • Doctor-documented clinical notes
  • Columns: recordId, patientProfileId, doctorId, diagnosis, symptoms, treatmentProvided, attachmentUrl, createdAt

Security & Audit Tables

sessions

  • Active JWT sessions
  • Columns: id, userId, refreshTokenHash, ipAddress, userAgent, expiresAt, revoked, createdAt

password_history

  • Password reuse prevention
  • Columns: id, userId, passwordHash, createdAt

password_reset_tokens

  • Time-limited password reset links
  • Columns: id, userId, tokenHash, expiresAt, used, createdAt

audit_logs

  • Complete access trail
  • Columns: id, email, action, ipAddress, userAgent, details, timestamp

consent_log

  • Patient consent tracking
  • Columns: id, patientId, consentType, sharedWith, granted, grantedAt, revokedAt

🐳 Deployment

Docker Compose (Development)

docker-compose up -d
# Starts: PostgreSQL, Redis, Backend API, Frontend, Adminer

Docker Build (Production)

# Backend
docker build -t secure-health-api:1.0 ./backend

# Frontend
docker build -t secure-health-app:1.0 ./frontend

# Push to registry
docker push your-registry/secure-health-api:1.0
docker push your-registry/secure-health-app:1.0

Environment Variables

# Database
SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/healthcare_db
SPRING_DATASOURCE_USERNAME=healthcare_user
SPRING_DATASOURCE_PASSWORD=secure_password_here

# JWT
JWT_SECRET=your_secret_key_here
JWT_EXPIRATION=900000

# Frontend
REACT_APP_API_URL=http://localhost:8081

# Email (OTP delivery)
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=app_specific_password

# Redis
REDIS_HOST=redis
REDIS_PORT=6379

# Backups
BACKUP_ENABLED=true
BACKUP_DIR=./backups
BACKUP_RETENTION=7

CI/CD Pipeline

GitHub Actions automatically:

  1. Builds backend (Maven)
  2. Runs backend tests
  3. Builds frontend (npm)
  4. Runs frontend tests
  5. (Optional) Deploys to staging

βœ… Testing

Backend Tests

cd backend/Backend

# Run all tests
mvn test

# Run specific test
mvn test -Dtest=AuthIntegrationTest

# Run with coverage
mvn test jacoco:report

Test Types:

  • Unit tests: Services in isolation
  • Controller tests: HTTP layer with MockMvc
  • Integration tests: Complete flows with H2 database

Frontend Tests

cd frontend/app

# Run all tests
npm test

# Run with coverage
npm test -- --coverage

# Run integration tests only
npm run test:integration

# Run unit tests only
npm run test:unit

🚨 Known Issues & Improvements

⚠️ Known Issues

Issue 1: Admin Workflows Not Fully Tested

Status: Low Priority
Impact: Admin features might have bugs
Fix: Complete integration testing of admin endpoints Timeline: v1.1

Issue 2: Lab File Upload Format Mismatch

Status: Medium Priority
Impact: Lab technicians can't upload results
Details: Backend expects JSON; frontend sends FormData
Fix: Update backend to accept multipart/form-data
Timeline: v1.0.1 (patch)

Issue 3: No Refresh Token Rotation

Status: Low Priority
Impact: Refresh tokens never invalidated
Fix: Implement refresh token rotation on every use
Timeline: v1.1

πŸ”„ Planned Improvements

v1.0.1 (Hotfixes)

  • Fix lab file upload FormData handling
  • Improve error messages on 401 responses
  • Add retry logic to API calls

v1.1 (Security & UX)

  • Implement refresh token rotation
  • Move tokens to HttpOnly cookies
  • Add client-side token expiry checking
  • Complete admin workflow testing
  • Add rate limiting per user

v1.2 (Performance)

  • Implement React Query for caching
  • Add pagination to patient lists
  • Lazy load components
  • Implement virtual scrolling for large lists

v2.0 (Enterprise Features)

  • OAuth2 integration (Google, Microsoft)
  • SAML for single sign-on
  • Multi-site hospital support
  • Data export/FHIR compatibility
  • Analytics dashboard
  • Mobile app (React Native)

πŸ‘¨β€πŸ’» Developer Notes

Architecture Decisions

Why React Context over Redux?

  • Project has only 2-3 global states (auth, theme)
  • Redux adds complexity without clear benefit
  • Context API is sufficient and built-in

Why Argon2 over Bcrypt?

  • NIST recommends Argon2 for new systems (as of 2024)
  • GPU-resistant (memory-hard)
  • Better for sensitive healthcare data

Why JWT over Sessions?

  • Stateless (scales horizontally)
  • No server-side session storage needed
  • Works with distributed systems/microservices

Why PostgreSQL over NoSQL?

  • ACID transactions essential for medical data
  • Healthcare data is relational (patients ↔ doctors, prescriptions, etc.)
  • Audit trail requires strong consistency

Common Development Tasks

Add New Role

  1. Add to Role.java enum
  2. Add role-specific controller (e.g., NurseController)
  3. Add role-specific service (e.g., NurseService)
  4. Create DTOs for role-specific responses
  5. Add role-specific frontend pages
  6. Add @PreAuthorize on endpoints
  7. Update routing guards
  8. Add tests

Add New Endpoint

  1. Create DTO for request/response
  2. Add method to Repository
  3. Add logic to Service
  4. Add @PostMapping/@GetMapping to Controller
  5. Add @PreAuthorize for authorization
  6. Add tests (unit + integration)
  7. Document in README

Add New Database Table

  1. Create JPA entity in model/
  2. Create repository extending JpaRepository
  3. Create service for business logic
  4. Add to schema.sql for reference
  5. Test with integration tests
  6. Update related services

Debugging

Common Issues

401 Unauthorized on all requests

  • Check JWT secret in application.properties
  • Verify token format: Authorization: Bearer {token}
  • Check token expiration: jwtUtil.isTokenExpired(token)

CORS errors on frontend

  • Check allowed origins in SecurityConfig
  • Verify frontend URL matches CORS config
  • Add credentials: 'include' to fetch calls

Patient can see other patients' data

  • IDOR vulnerability
  • Check PatientAccessValidator is being called
  • Verify service layer access checks
  • Review database queries for pre-filtering

Appointment double-booking occurs

  • Race condition in appointment creation
  • Verify unique constraint on database:
    SELECT * FROM information_schema.constraints 
    WHERE table_name='appointments' AND constraint_type='UNIQUE';

πŸ“š Additional Resources


πŸ“„ License

This project is for educational purposes and interview demonstration.


πŸ“§ Contact & Support

For questions or issues:

  1. Check the TECHNICAL_AUDIT_REPORT.md for detailed architectural documentation
  2. Review the integration testing guide in backend/Backend/INTEGRATION_TESTING_GUIDE.md
  3. Check recent PRs for current issues and solutions

Last Updated: April 20, 2026
Status: βœ… Production-Ready for Education/Interview Use
Maintained By: Manvitha Dungi

About

Comprehensive healthcare information management system that demonstrates enterprise-level security practices for handling sensitive medical data.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • JavaScript 75.2%
  • Java 23.8%
  • Other 1.0%