Skip to content

olasunkanmi-SE/MedicSync

Repository files navigation

Deployed on Vercel Built with Next.js MongoDB TypeScript

🌟 Overview

A user-centric, privacy-first centralized health application that empowers patients to control access to their medical records through secure QR code authentication, enabling seamless healthcare interactions while maintaining strict privacy controls and HIPAA compliance.

🎯 Core Vision

  • Patient-Owned Data: Patients have complete control over their health records
  • Privacy-First: Explicit consent required for all data access with granular permissions
  • Security-by-Design: Multi-layered security with field-level encryption
  • Interoperability: Standards-based healthcare data models
  • Complete Audit Trail: Every action is logged and traceable

πŸ“‹ Table of Contents

  1. Key Features
  2. Technology Stack
  3. Architecture
  4. User Roles & Dashboards
  5. Security Features
  6. Getting Started
  7. API Documentation
  8. Database Schema
  9. Testing
  10. Deployment
  11. Contributing

✨ Key Features

πŸ₯ Healthcare Workflow Management

  • Digital Medical Encounters: Complete encounter documentation with diagnoses and prescriptions
  • Prescription Management: Digital prescription issuance with secure QR codes for pharmacy verification
  • Patient Medical History: Comprehensive timeline of medical encounters and treatments
  • Drug Safety Checks: Allergy warnings and drug interaction detection
  • Pharmacy Integration: Prescription verification and dispensation tracking

πŸ” QR Code Authentication System

  • Patient Authorization: Patients generate secure QR codes for healthcare provider access
  • Time-Limited Access: Configurable access durations with automatic expiration
  • Prescription QR Codes: Digitally signed prescription QR codes for pharmacy verification
  • Tamper-Proof Security: HMAC-SHA256 digital signatures prevent QR code tampering
  • Real-Time Validation: Instant verification of QR code authenticity and validity

πŸ“Š Advanced Admin Analytics

  • Real-Time Dashboards: Comprehensive system monitoring and user activity analytics
  • Healthcare Metrics: Encounter trends, prescription patterns, and utilization statistics
  • Security Monitoring: Failed login attempts, security alerts, and compliance tracking
  • Data Quality Insights: Profile completeness, verification status, and data integrity metrics
  • Performance Analytics: System health, response times, and resource utilization

πŸ”’ Privacy & Security

  • Field-Level Encryption: AES-256-GCM encryption for all PII/PHI data
  • Role-Based Access Control: Granular permissions for different healthcare roles
  • Complete Audit Logging: Immutable logs for all data access and modifications
  • HIPAA Compliance: Healthcare industry standard security and privacy controls
  • Zero Trust Architecture: Every request authenticated and authorized

🎭 Multi-Role Support

  • Patients: Personal health management, access control, QR code generation
  • Doctors: Patient authorization, encounter creation, prescription management
  • Pharmacists: Prescription verification, dispensation tracking, patient safety checks
  • Administrators: System management, user administration, compliance monitoring

πŸ›  Technology Stack

Frontend

  • Framework: Next.js 15.2.4 with App Router
  • Language: TypeScript for type safety
  • UI Library: React 19 with Radix UI components
  • Styling: Tailwind CSS with custom design system
  • State Management: Zustand for global state
  • Forms: React Hook Form with Zod validation
  • Charts: Recharts for analytics visualization

Backend

  • Runtime: Node.js with Next.js API Routes
  • Database: MongoDB with Mongoose ODM
  • Authentication: JWT tokens with refresh token rotation
  • Security: bcryptjs for password hashing, crypto for encryption
  • File Storage: Supabase for document storage
  • Caching: Node-cache for performance optimization

Security & Compliance

  • Encryption: AES-256-GCM field-level encryption
  • Digital Signatures: HMAC-SHA256 for QR code security
  • Rate Limiting: Request throttling and abuse prevention
  • CORS: Configured for secure cross-origin requests
  • Headers: Security headers for XSS and CSRF protection

DevOps & Monitoring

  • Deployment: Vercel with serverless functions
  • CI/CD: GitHub Actions for automated testing and deployment
  • Monitoring: Built-in logging and error tracking
  • Testing: Jest for unit tests, testing library for components

πŸ— Architecture

Core Architectural Principles

  1. User-Centric Design: All data flows through the User model as the central hub
  2. Security-First Approach: Authorization checks on every API endpoint
  3. Modular Architecture: Clear separation of concerns with organized file structure
  4. Event-Driven: Asynchronous processing for audit logs and notifications
  5. Scalable Design: Optimized for horizontal scaling and high availability

System Architecture Diagram

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Patient App   β”‚    β”‚   Doctor App    β”‚    β”‚   Admin Panel   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
          β”‚                      β”‚                      β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚      API Gateway          β”‚
                    β”‚   (Next.js API Routes)    β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚                   β”‚                   β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  Authentication   β”‚ β”‚   Healthcare    β”‚ β”‚   Analytics     β”‚
    β”‚     Service       β”‚ β”‚    Workflow     β”‚ β”‚    Service      β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              β”‚                   β”‚                   β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚      MongoDB Atlas        β”‚
                    β”‚   (Encrypted Storage)     β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Data Flow Architecture

Patient QR Generation β†’ Doctor Scan β†’ Authorization Grant β†’ Medical Encounter β†’ Prescription β†’ Pharmacy Verification β†’ Dispensation

πŸ‘₯ User Roles & Dashboards

🩺 Doctor Dashboard

  • Patient Authorization: QR code scanner for patient access requests
  • Medical History: Comprehensive patient history viewer
  • Encounter Management: Create and manage medical encounters
  • Prescription Workflow: Digital prescription generation with QR codes
  • Professional Profile: Medical license and specialty information

πŸ’Š Pharmacist Dashboard

  • Prescription Verification: QR code scanner for prescription validation
  • Patient Safety: Drug interaction warnings and allergy checks
  • Dispensation Management: Track filled prescriptions and inventory
  • Patient Records: Access to relevant patient information for safe dispensing
  • Organization Integration: Multi-pharmacy support

πŸ₯ Patient Dashboard

  • Personal Health: Medical profile and prescription management
  • Access Control: Manage healthcare provider permissions
  • QR Code Generation: Create secure access codes for providers
  • Medical Records: View encounter history and test results
  • Privacy Settings: Granular data sharing controls

πŸ‘¨β€πŸ’Ό Admin Dashboard

  • System Analytics: Real-time monitoring and performance metrics
  • User Management: Admin user creation and management
  • Organization Verification: Healthcare organization approval workflow
  • Security Monitoring: Failed logins, alerts, and compliance tracking
  • Data Quality: Profile completeness and system health metrics

πŸ”’ Security Features

Encryption & Data Protection

  • Field-Level Encryption: All PII/PHI encrypted using AES-256-GCM
  • Key Management: Secure key derivation with rotation support
  • Data Masking: Sensitive data masked in logs and non-production environments

Authentication & Authorization

  • JWT Tokens: Secure authentication with refresh token rotation
  • Role-Based Access: Granular permissions for healthcare roles
  • Session Management: Secure session handling with timeout controls
  • Multi-Factor Support: Ready for MFA integration

QR Code Security

  • Digital Signatures: HMAC-SHA256 signatures prevent tampering
  • Time-Limited Validity: Configurable expiration times
  • Usage Tracking: Complete audit trail for QR code scans
  • Anti-Replay Protection: Prevents QR code reuse attacks

Audit & Compliance

  • Complete Audit Logs: Every action logged with user, timestamp, and context
  • HIPAA Compliance: Healthcare industry security standards
  • Data Retention: Configurable retention policies for compliance
  • Access Monitoring: Real-time tracking of data access patterns

πŸš€ Getting Started

Prerequisites

  • Node.js 18+
  • MongoDB Atlas account
  • npm or pnpm package manager

Installation

  1. Clone the repository

    git clone https://github.com/olasunkanmi-SE/AITKL-Hackathon-App.git
    cd AITKL-Hackathon-App
  2. Install dependencies

    npm install
    # or
    pnpm install
  3. Environment Setup

    cp .env.template .env.local
  4. Configure Environment Variables

    # MongoDB Configuration
    MONGODB_URI=your_mongodb_connection_string
    MONGODB_DB_NAME=healthapp
    
    # JWT Configuration  
    JWT_SECRET=your-super-secure-secret-key
    JWT_REFRESH_SECRET=your-refresh-secret-key
    
    # Encryption Keys (32 characters)
    ENCRYPTION_MASTER_KEY=your-32-character-master-key-here
    ENCRYPTION_SALT=your-unique-salt-for-key-derivation
    
    # Feature Toggles
    ENABLE_FIELD_ENCRYPTION=true
    ENABLE_AUDIT_LOGGING=true
    ENABLE_QR_CODE_ROTATION=true
  5. Run the development server

    npm run dev
  6. Open your browser Navigate to http://localhost:3000

Initial Setup

  1. Create your first admin user through the registration flow
  2. Set up healthcare organizations in the admin panel
  3. Add practitioners and verify their credentials
  4. Test the patient-doctor-pharmacy workflow

πŸ“‘ API Documentation

Authentication Endpoints

POST /api/auth/login        # User authentication
POST /api/auth/register     # New user registration  
POST /api/auth/refresh      # Token refresh
POST /api/auth/logout       # User logout

Patient Endpoints

GET    /api/patient/medical-info           # Get patient medical information
GET    /api/patient/authorization-history  # View access grants history
POST   /api/patient/qr                     # Generate QR code for access

Doctor Endpoints

GET    /api/doctor/encounters                               # List encounters
POST   /api/doctor/encounters                               # Create encounter
GET    /api/doctor/encounters/[encounterId]                 # Get encounter details
GET    /api/doctor/patients/[digitalId]/medical-history     # Patient history

Pharmacist Endpoints

POST   /api/pharmacist/prescriptions/verify                 # Verify prescription QR
GET    /api/pharmacist/patient/[digitalId]/records          # Patient records
POST   /api/pharmacist/patient/[digitalId]/dispense         # Dispense medication

Admin Endpoints

GET    /api/admin/analytics        # System analytics
GET    /api/admin/users            # User management
GET    /api/admin/organizations    # Organization management

Response Format

// Success Response
{
  success: true,
  data: any,
  message?: string
}

// Error Response  
{
  success: false,
  error: string,
  code?: number
}

πŸ—„ Database Schema

Core Models

User (Patient)

{
  _id: ObjectId,
  digitalIdentifier: string,     // Public QR identifier
  personalInfo: {                // Encrypted fields
    firstName: EncryptedField,
    lastName: EncryptedField,
    dateOfBirth: Date,
    contact: {
      email: EncryptedField,
      phone: EncryptedField
    }
  },
  medicalInfo: {
    bloodType: string,
    knownAllergies: string[],
    emergencyContact: Object
  },
  auth: {
    hashedPassword: string,
    role: 'patient' | 'doctor' | 'pharmacist' | 'admin',
    accountLocked: boolean
  }
}

Encounter (Medical Visit)

{
  _id: ObjectId,
  userId: ObjectId,              // Patient reference
  organizationId: ObjectId,       // Healthcare facility
  attendingPractitionerId: ObjectId,
  encounter: {
    encounterDate: Date,
    encounterType: string,
    chiefComplaint: string,
    vitals: Object
  },
  diagnoses: [{
    code: string,                // ICD-10 code
    description: string,
    notes: string,
    isChronic: boolean
  }],
  prescriptions: [{
    medicationName: string,
    dosage: string,
    frequency: string,
    status: 'ISSUED' | 'FILLED' | 'CANCELLED'
  }]
}

Organization (Healthcare Facility)

{
  _id: ObjectId,
  organizationInfo: {
    name: string,
    type: 'HOSPITAL' | 'CLINIC' | 'PHARMACY',
    registrationNumber: string
  },
  address: Object,
  verification: {
    isVerified: boolean,
    verifiedAt: Date
  }
}

πŸ§ͺ Testing

Running Tests

# Unit tests
npm test

# Watch mode
npm run test:watch

# Coverage report
npm run test:coverage

Test Structure

__tests__/
β”œβ”€β”€ api/              # API endpoint tests
β”œβ”€β”€ components/       # Component tests  
β”œβ”€β”€ hooks/           # Custom hook tests
β”œβ”€β”€ lib/             # Utility function tests
└── services/        # Service layer tests

Testing Strategy

  • Unit Tests: Individual functions and components
  • Integration Tests: API endpoints and database operations
  • Security Tests: Authentication, authorization, and encryption
  • Performance Tests: Database queries and API response times

πŸš€ Deployment

Vercel Deployment (Recommended)

  1. Connect GitHub repository to Vercel
  2. Configure environment variables in Vercel dashboard
  3. Deploy automatically on push to main branch

Environment Variables Setup

Required variables for production:

MONGODB_URI=mongodb+srv://...
JWT_SECRET=production-secret-key
ENCRYPTION_MASTER_KEY=production-encryption-key
NEXTAUTH_URL=https://yourdomain.com

Build Commands

# Production build
npm run build

# Start production server
npm start

# Run database migrations
npm run migrate:encrypt

Monitoring & Maintenance

  • Health Checks: /api/health endpoint for monitoring
  • Analytics: Built-in admin dashboard for system monitoring
  • Logging: Structured logging for debugging and audit
  • Backup: Regular MongoDB backups recommended

🀝 Contributing

Development Workflow

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes with tests
  4. Commit with conventional commits: git commit -m 'feat: add amazing feature'
  5. Push to your branch: git push origin feature/amazing-feature
  6. Open a Pull Request

Code Standards

  • TypeScript: Strict type checking enabled
  • ESLint: Code linting with healthcare-specific rules
  • Prettier: Code formatting for consistency
  • Tests: Required for all new features

Security Guidelines

  • Never commit secrets or credentials
  • Follow OWASP security guidelines
  • Encrypt all PII/PHI data
  • Implement proper input validation
  • Add audit logging for sensitive operations

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™‹β€β™‚οΈ Support

For support, email support@example.com or join our Discord community.

Documentation


πŸ† Acknowledgments

  • Healthcare Community for feedback and requirements
  • Open Source Contributors for the amazing tools and libraries
  • Security Researchers for vulnerability assessments and improvements

Built with ❀️ for Healthcare Innovation

Empowering patients, enabling providers, ensuring security.

Releases

No releases published

Packages

 
 
 

Contributors

Languages