Comprehensive AI-powered healthcare platform featuring symptom analysis, prescription digitization, family health monitoring, and intelligent medical insights.
- Overview
- Features
- System Architecture
- Database Schema
- System Flow
- User Roles
- Tech Stack
- API Documentation
- Project Structure
- Security Best Practices
- Installation
- Commands Reference
- Environment Variables
- Roadmap
- Contributing
- License
LifeDoc is a next-generation healthcare management platform that transforms how families manage their health data. By combining advanced AI (Google Gemini, OpenAI Vision), intelligent document processing, and family-centric features, LifeDoc bridges the gap between complex medical information and actionable health insights.
- 🤖 AI-Powered Health Assistant: Instant symptom analysis with personalized recommendations using Google Gemini 1.5 Flash
- 📸 Smart Document Digitization: Convert prescriptions and lab reports into structured data using Vision AI
- 👨👩👧👦 Family Health Management: Centralized health tracking for entire families with role-based access control
- 📊 Intelligent Health Analytics: Track vitals, medications, and generate AI-powered health summaries
- 🔒 Privacy-First Design: End-to-end encryption with user data sovereignty
- 🚨 Emergency Features: SOS alerts with real-time location sharing to family members
- 👨⚕️ Doctor Portal: Verified doctors can review consultations and request admin meetings
- 💳 Premium Subscriptions: Stripe-powered payment system for premium features
- 📅 Doctor Appointments: Book and manage appointments with verified healthcare professionals
- Patients: Individuals managing chronic conditions or seeking medical guidance
- Caregivers: Family members managing health records for children or elderly parents
- Doctors: Healthcare professionals needing quick access to patient history
- Seniors: Elderly users requiring simplified, voice-enabled health tracking
- Intelligent Symptom Checker: Multi-lingual AI consultation (English, Hindi, Gujarati) with urgency assessment
- Contextual Health Advice: Personalized recommendations based on user's medical history and chronic conditions
- Urgency Classification: Automatic triage (Low/Medium/High) with actionable next steps
- Lifestyle Recommendations: AI-generated wellness tips tailored to user's condition
- Token Tracking: Monitor AI usage and estimated costs for transparency
- Computer Vision OCR: Extract medicine names, dosages, and schedules from prescription photos
- Multi-Format Support: Process handwritten prescriptions, printed reports, and PDF documents
- Automated Medication Reminders: Set up schedules automatically from scanned prescriptions
- Medicine Database Integration: Auto-complete and validate medicine names
- Intelligent Document Parsing: Extract structured data from lab reports (images/PDFs)
- Reference Range Comparison: Automatic flagging of out-of-range values
- Trend Analysis: Track biomarkers over time with visual charts
- AI-Powered Insights: Plain-language explanations of lab results
- Multi-Document Upload: Submit medical license, ID, and degree certificates
- Admin Review Workflow: Pending → Approved/Rejected status management
- Professional Badge Display: Verified doctors get special badges on profile
- Automated Account Upgrade: Successful verification changes user type to 'doctor'
- Review Queue: Doctors access pending consultations that users flagged for review
- Professional Feedback: Add medical insights to AI-generated consultations
- Review Status Tracking: Monitor consultation review history
- Expert Validation: Verify or enhance AI recommendations with professional expertise
- Admin Collaboration: Doctors can request meetings with system administrators
- Urgency Levels: Normal, Urgent, or Critical priority settings
- Meeting Scheduling: Admin approves and sets meeting time with Google Meet link
- Meeting Summaries: AI-powered summarization of meeting recordings
- Duration Management: Default 60-minute meetings with customizable duration
- Secure Checkout: Stripe-powered payment processing with PCI compliance
- Subscription Management: Track active, cancelled, and expired subscriptions
- Webhook Integration: Real-time payment status updates
- Multiple Plans: Flexible pricing tiers for different user needs
- Payment History: Complete transaction logging with invoice tracking
- Customer Portal: Manage subscriptions and payment methods
- Unlimited AI Consultations: No rate limits for premium users
- Priority Support: Faster response times for premium members
- Advanced Analytics: Enhanced health insights and trend analysis
- Extended Storage: Larger file upload limits for medical documents
- Family Plan: Manage more family members with premium subscription
- Comprehensive Listings: Browse all verified doctors in the system
- Specialty Filtering: Find doctors by medical specialty
- Availability Management: Doctors set and update their availability slots
- Profile Information: View doctor credentials, specializations, and ratings
- Appointment Booking: Schedule appointments with available time slots
- Create Appointments: Book appointments with preferred doctors
- View Appointments: See all scheduled, completed, and cancelled appointments
- Doctor's Calendar: Doctors view their appointment schedule
- Status Tracking: Monitor appointment status (scheduled, completed, cancelled, rescheduled)
- Appointment History: Access past appointments for both patients and doctors
- Family Profiles: Manage health records for up to 5 family members
- Role-Based Access Control: Admin, Caregiver, Member, Child, View-Only roles
- Linked vs Managed Accounts: Support for independent accounts and dependent profiles
- Invitation System: Email-based invitations with approval workflow
- Aggregate Health Dashboard: View family-wide health trends and alerts
- Vital Signs Monitoring: Blood pressure, glucose, heart rate, weight, temperature, SpO2
- Medication Tracking: Active prescriptions with dosage schedules and reminders
- Appointment Management: Schedule and track doctor visits, lab tests
- Health Diary: AI-summarized daily health logs with mood tracking
- Document Storage: Secure cloud storage for all medical documents
- Real-Time Search: Autocomplete-enabled medicine search powered by OpenFDA
- Detailed Drug Information: Dosage, side effects, interactions, and manufacturer details
- Lab Test Reference: Comprehensive database of common lab tests and their purposes
- Health News Feed: Curated medical news from trusted sources updated daily
- SOS Alert System: One-tap emergency alerts to designated contacts
- Real-Time Location Sharing: GPS coordinates sent via SMS to emergency contacts
- Emergency Contact Management: Store and manage up to 5 emergency contacts
- Critical Threshold Alerts: Automatic notifications for dangerous vital sign readings
- JWT Authentication: Secure token-based authentication with OTP verification
- Bcrypt Password Hashing: Industry-standard password encryption
- Role-Based Authorization: Granular access control for different user types
- CORS Protection: Strict cross-origin resource sharing policies
- Input Sanitization: Prevent injection attacks and XSS vulnerabilities
- HIPAA-Ready Architecture: Designed with healthcare data protection in mind
- Audit Logging: Track all access to sensitive medical data
- Data Encryption: AES-256 encryption for data at rest
- Secure File Upload: Validated and sanitized file uploads to Cloudinary
- Responsive Design: Optimized for mobile, tablet, and desktop
- Dark Mode Support: Eye-friendly interface for night-time use
- Guided Onboarding: Interactive tour for new users using React Joyride
- Progressive Web App (PWA): Install and use offline
- Voice Navigation: Accessibility features for elderly and visually impaired users
- Language Options: English, Hindi, Gujarati interface translations
- AI Multilingual Response: Symptom analysis available in multiple languages
- Localized Date/Time: Regional formatting for dates and measurements
LifeDoc follows a modern 3-tier client-server architecture with clear separation of concerns, microservice-ready design patterns, and scalable infrastructure.
graph TB
subgraph Client["🖥️ Client Layer - Next.js 16"]
UI[User Interface]
Redux[Redux Store]
Auth[Auth Context]
end
subgraph Server["⚙️ Server Layer - Express.js"]
API[API Gateway]
AuthMW[Auth Middleware]
Controllers[Controllers]
Services[Services Layer]
end
subgraph External["☁️ External Services"]
Gemini[Google Gemini AI]
OpenAI[OpenAI Vision]
Cloud[Cloudinary CDN]
FDA[OpenFDA API]
Email[Nodemailer SMTP]
SMS[Twilio SMS]
end
subgraph Data["💾 Data Layer"]
MongoDB[(MongoDB Atlas)]
FileStore[Cloudinary Storage]
end
UI --> Redux
Redux --> API
API --> AuthMW
AuthMW --> Controllers
Controllers --> Services
Services --> MongoDB
Services --> Gemini
Services --> OpenAI
Services --> Cloud
Services --> FDA
Services --> Email
Services --> SMS
Cloud --> FileStore
style Client fill:#e3f2fd,stroke:#1565c0,stroke-width:3px,color:#000
style Server fill:#fff3e0,stroke:#e65100,stroke-width:3px,color:#000
style External fill:#f3e5f5,stroke:#6a1b9a,stroke-width:3px,color:#000
style Data fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#000
- Framework: React 18 with Next.js 16 App Router
- State Management: Redux Toolkit for global state
- Styling: Tailwind CSS v4 with custom design system
- Type Safety: Full TypeScript implementation
- HTTP Client: Axios with interceptors for auth tokens
- Framework: Express.js with RESTful API design
- Authentication: JWT-based stateless authentication
- Middleware Stack: CORS, Helmet, Compression, Multer
- Database: Mongoose ODM for MongoDB
- Validation: Request validation and sanitization
- API Gateway Pattern: Single entry point for all requests
- Service Layer Pattern: Business logic isolation
- Repository Pattern: Data access abstraction
- Middleware Chain Pattern: Modular request processing
- Webhook Pattern: Real-time payment event processing from Stripe
- Background Jobs Pattern: Scheduled tasks for news fetching and notifications
erDiagram
USER ||--o{ CONSULTATION : creates
USER ||--o{ DIARY : writes
USER ||--o{ MEASUREMENT : records
USER ||--o{ LAB_REPORT : uploads
USER ||--o{ DOCTOR_REPORT : has
USER ||--o{ APPOINTMENT : schedules
USER ||--o{ PAYMENT : makes
USER ||--o{ DOCTOR_VERIFICATION : applies
USER ||--o{ MEETING_REQUEST : requests
USER ||--o{ SAVED_POST : saves
FAMILY ||--|{ USER : contains
DOCTOR ||--o{ APPOINTMENT : has
DOCTOR ||--o{ CONSULTATION : reviews
USER {
ObjectId id PK
String name
String email UK
String password
String type "user, doctor, admin"
Number age
Boolean isVerified
Object profile
Array sosContacts
Boolean isManaged
}
FAMILY {
ObjectId id PK
ObjectId adminId FK
Array members
}
CONSULTATION {
ObjectId id PK
ObjectId userId FK
String symptoms
String aiSummary
String urgency "Low, Medium, High"
Array actions
Object tokenUsage
String reviewStatus
}
LAB_REPORT {
ObjectId id PK
ObjectId userId FK
Date reportDate
String testType
Mixed parsedResults
String fileUrl
}
DOCTOR_REPORT {
ObjectId id PK
ObjectId userId FK
Date visitDate
String doctorName
Array diagnosis
Array prescriptions
String fileUrl
}
MEASUREMENT {
ObjectId id PK
ObjectId userId FK
String type "BP, glucose, weight"
Array readings
}
DIARY {
ObjectId id PK
ObjectId userId FK
Date date
String summary
String mood
Array tags
}
APPOINTMENT {
ObjectId id PK
ObjectId userId FK
ObjectId doctorId FK
String providerName
Date date
String status
String notes
}
PAYMENT {
ObjectId id PK
ObjectId userId FK
String stripeCustomerId
String stripeInvoiceId
String stripePaymentIntentId
Number amount
String currency
String status
Date paymentDate
}
DOCTOR_VERIFICATION {
ObjectId id PK
ObjectId userId FK
String licenseNumber
String specialty
Array documents
String status
Date appliedAt
}
MEETING_REQUEST {
ObjectId id PK
ObjectId requesterId FK
String topic
String reason
String urgency
String status
String meetingLink
Date scheduledAt
Number duration
String summary
}
SAVED_POST {
ObjectId id PK
ObjectId userId FK
ObjectId articleId FK
Date savedAt
}
{
_id: ObjectId,
name: String (required),
email: String (unique, indexed),
password: String (bcrypt hashed),
age: Number,
type: String (enum: ['user', 'doctor', 'admin']),
isVerified: Boolean,
profile: {
gender: String,
height: Number,
weight: Number,
bloodGroup: String,
chronicConditions: [String]
},
sosContacts: [{ name, phone, email, relationship }],
emergencySettings: { enableAutoAlert, criticalThresholds }
}{
_id: ObjectId,
user: ObjectId (ref: 'User', indexed),
symptoms: String,
aiSummary: String,
urgency: String (enum: ['Low', 'Medium', 'High']),
actions: [String],
lifestyleAdvice: [String],
suggestedMedicines: [String],
tokenUsage: { promptTokens, completionTokens, totalTokens },
reviewStatus: String (enum: ['none', 'pending', 'reviewed']),
doctorFeedback: String,
reviewedBy: ObjectId (ref: 'User'),
reviewedAt: Date,
date: Date
}{
_id: ObjectId,
userId: ObjectId (ref: 'User', indexed),
stripeCustomerId: String (required, indexed),
stripeInvoiceId: String,
stripePaymentIntentId: String,
amount: Number (required), // in cents
currency: String (default: 'usd'),
status: String (enum: ['succeeded', 'failed', 'pending'], required),
description: String,
paymentDate: Date (default: Date.now),
metadata: Map
}{
_id: ObjectId,
userId: ObjectId (ref: 'User', indexed),
licenseNumber: String (required),
specialty: String (required),
documents: [{ fileUrl: String, documentType: String }], // Up to 5 files
status: String (enum: ['pending', 'approved', 'rejected'], default: 'pending'),
reviewedBy: ObjectId (ref: 'User'),
reviewNotes: String,
appliedAt: Date (default: Date.now),
reviewedAt: Date
}{
_id: ObjectId,
requester: ObjectId (ref: 'User', required), // Doctor requesting meeting
topic: String (required),
reason: String (required),
urgency: String (enum: ['Normal', 'Urgent', 'Critical'], default: 'Normal'),
status: String (enum: ['pending', 'approved', 'rejected'], default: 'pending'),
meetingLink: String, // Google Meet or Zoom link
scheduledAt: Date,
duration: Number (default: 60), // Minutes
summary: String, // AI-generated meeting summary
recordingLink: String, // Optional recording URL
createdAt: Date (default: Date.now)
}{
_id: ObjectId,
userId: ObjectId (ref: 'User', indexed),
doctorId: ObjectId (ref: 'User', indexed), // Doctor user ID
providerName: String,
specialty: String,
appointmentDate: Date (indexed),
status: String (enum: ['scheduled', 'completed', 'cancelled', 'rescheduled']),
notes: String,
createdAt: Date,
updatedAt: Date
}{
_id: ObjectId,
userId: ObjectId (ref: 'User', indexed),
articleId: ObjectId (ref: 'Article', indexed),
savedAt: Date (default: Date.now)
}{
_id: ObjectId,
userId: ObjectId (indexed),
reportDate: Date,
testType: String,
parsedResults: Mixed, // AI-extracted structured data
originalReport: String (Cloudinary URL),
fileUrl: String,
notes: String
}// Optimized queries
db.users.createIndex({ email: 1 }, { unique: true })
db.consultations.createIndex({ user: 1, date: -1 })
db.consultations.createIndex({ reviewStatus: 1 })
db.labreports.createIndex({ userId: 1, reportDate: -1 })
db.measurements.createIndex({ userId: 1, type: 1 })
db.payments.createIndex({ userId: 1, paymentDate: -1 })
db.payments.createIndex({ stripeCustomerId: 1 })
db.doctorverifications.createIndex({ userId: 1, status: 1 })
db.appointments.createIndex({ userId: 1, appointmentDate: -1 })
db.appointments.createIndex({ doctorId: 1, appointmentDate: -1 })
db.meetingrequests.createIndex({ requester: 1, status: 1 })
db.savedposts.createIndex({ userId: 1, articleId: 1 }, { unique: true })graph LR
subgraph UserTypes["👤 User Types"]
UT1["user"]
UT2["doctor"]
UT3["admin"]
end
subgraph ConsultationUrgency["🚨 Consultation Urgency"]
CU1["Low"]
CU2["Medium"]
CU3["High"]
end
subgraph MeasurementTypes["📊 Measurement Types"]
MT1["blood_pressure"]
MT2["glucose"]
MT3["heart_rate"]
MT4["weight"]
MT5["temperature"]
MT6["spo2"]
end
subgraph FamilyRoles["👨👩👧👦 Family Roles"]
FR1["admin"]
FR2["caregiver"]
FR3["member"]
FR4["child"]
FR5["view_only"]
end
subgraph AppointmentStatus["📅 Appointment Status"]
AS1["scheduled"]
AS2["completed"]
AS3["cancelled"]
AS4["rescheduled"]
end
subgraph VerificationStatus["✅ Verification Status"]
VS1["pending"]
VS2["approved"]
VS3["rejected"]
end
subgraph PaymentStatus["💳 Payment Status"]
PS1["succeeded"]
PS2["failed"]
PS3["pending"]
end
subgraph MeetingUrgency["🔔 Meeting Urgency"]
MU1["Normal"]
MU2["Urgent"]
MU3["Critical"]
end
subgraph ReviewStatus["📋 Review Status"]
RS1["none"]
RS2["pending"]
RS3["reviewed"]
end
style UserTypes fill:#e3f2fd,stroke:#1565c0,stroke-width:3px,color:#000
style ConsultationUrgency fill:#fff3e0,stroke:#e65100,stroke-width:3px,color:#000
style MeasurementTypes fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#000
style FamilyRoles fill:#f3e5f5,stroke:#6a1b9a,stroke-width:3px,color:#000
style AppointmentStatus fill:#fce4ec,stroke:#c2185b,stroke-width:3px,color:#000
style VerificationStatus fill:#e0f2f1,stroke:#00695c,stroke-width:3px,color:#000
style PaymentStatus fill:#fff9c4,stroke:#f57f17,stroke-width:3px,color:#000
style MeetingUrgency fill:#e1f5fe,stroke:#0277bd,stroke-width:3px,color:#000
style ReviewStatus fill:#fce4ec,stroke:#880e4f,stroke-width:3px,color:#000
style UT1 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style UT2 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style UT3 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style CU1 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style CU2 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style CU3 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style MT1 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style MT2 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style MT3 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style MT4 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style MT5 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style MT6 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style FR1 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style FR2 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style FR3 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style FR4 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style FR5 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style AS1 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style AS2 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style AS3 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style AS4 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style VS1 fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style VS2 fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style VS3 fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style PS1 fill:#fff59d,stroke:#f57f17,stroke-width:2px,color:#000
style PS2 fill:#fff59d,stroke:#f57f17,stroke-width:2px,color:#000
style PS3 fill:#fff59d,stroke:#f57f17,stroke-width:2px,color:#000
style MU1 fill:#b3e5fc,stroke:#0277bd,stroke-width:2px,color:#000
style MU2 fill:#b3e5fc,stroke:#0277bd,stroke-width:2px,color:#000
style MU3 fill:#b3e5fc,stroke:#0277bd,stroke-width:2px,color:#000
style RS1 fill:#f8bbd0,stroke:#880e4f,stroke-width:2px,color:#000
style RS2 fill:#f8bbd0,stroke:#880e4f,stroke-width:2px,color:#000
style RS3 fill:#f8bbd0,stroke:#880e4f,stroke-width:2px,color:#000
Enum Definitions:
| Category | Values | Description |
|---|---|---|
| User Types | user, doctor, admin |
System-wide role classification |
| Urgency | Low, Medium, High |
AI consultation priority levels |
| Vital Types | blood_pressure, glucose, heart_rate, weight, temperature, spo2 |
Supported vital sign measurements |
| Family Roles | admin, caregiver, member, child, view_only |
Family access control levels |
| Appointment Status | scheduled, completed, cancelled, rescheduled |
Appointment lifecycle states |
| Verification Status | pending, approved, rejected |
Doctor verification workflow |
| Payment Status | succeeded, failed, pending |
Payment transaction states |
| Meeting Urgency | Normal, Urgent, Critical |
Meeting request priority levels |
| Review Status | none, pending, reviewed |
Consultation review states |
graph TD
Start([User Visits LifeDoc]) --> Auth{Authenticated?}
Auth -->|No| Signup[Sign Up / Login]
Auth -->|Yes| Dashboard[Dashboard]
Signup --> OTP[Enter OTP]
OTP --> Verify{Valid OTP?}
Verify -->|No| OTP
Verify -->|Yes| Profile[Complete Profile]
Profile --> Dashboard
Dashboard --> Features{Select Feature}
Features --> Consult[AI Consultation]
Features --> Scan[Scan Prescription]
Features --> Labs[Upload Lab Report]
Features --> Track[Track Vitals]
Features --> Family[Family Management]
Features --> Doctors[Find Doctors]
Features --> Payment[Premium Subscription]
Consult --> SymptomInput[Enter Symptoms]
SymptomInput --> AIAnalysis[AI Analysis]
AIAnalysis --> Results[View Results]
Results --> RequestReview{Need Review?}
RequestReview -->|Yes| DoctorReview[Request Doctor Review]
RequestReview -->|No| Dashboard
DoctorReview --> Dashboard
Scan --> UploadRx[Upload Photo]
UploadRx --> OCR[Vision AI Processing]
OCR --> MedList[Extract Medicines]
MedList --> SetReminders[Set Reminders]
SetReminders --> Dashboard
Labs --> UploadLab[Upload Report]
UploadLab --> LabOCR[Extract Lab Data]
LabOCR --> LabResult[Show Results]
LabResult --> Dashboard
Track --> EnterVital[Enter Measurement]
EnterVital --> Save[(Save to DB)]
Save --> Charts[View Trends]
Charts --> Dashboard
Family --> FamilyMenu{Family Action}
FamilyMenu --> AddMember[Add Member]
FamilyMenu --> ViewMember[View Member Health]
FamilyMenu --> Analyze[AI Health Analysis]
AddMember --> Dashboard
ViewMember --> Dashboard
Analyze --> Dashboard
Doctors --> BrowseDoctors[Browse Doctors List]
BrowseDoctors --> ViewDoctor[View Doctor Profile]
ViewDoctor --> BookAppt[Book Appointment]
BookAppt --> Dashboard
Payment --> ChoosePlan[Choose Subscription Plan]
ChoosePlan --> StripeCheckout[Stripe Checkout]
StripeCheckout --> PaymentSuccess{Payment Success?}
PaymentSuccess -->|Yes| ActivatePremium[Activate Premium]
PaymentSuccess -->|No| Dashboard
ActivatePremium --> Dashboard
style AIAnalysis fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#000
style OCR fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#000
style Save fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#000
style Dashboard fill:#f3e5f5,stroke:#6a1b9a,stroke-width:2px,color:#000
Secure OTP-based authentication with email verification
- User enters email and password
- System generates 6-digit OTP (expires in 10 minutes)
- OTP sent via email (Nodemailer)
- User verifies OTP
- JWT token generated and returned
- Token stored in localStorage for subsequent requests
graph TB
subgraph UserInput["📱 User Input Layer"]
Input1["Text Symptoms"]
Input2["Prescription Image"]
Input3["Lab Report PDF"]
Input4["Diary Entry"]
end
subgraph APILayer["⚙️ API Gateway Layer"]
API1["/api/ai/analyze"]
API2["/api/ai/analyze-prescription"]
API3["/api/ai/analyze-lab-report"]
API4["/api/ai/summerizer"]
end
subgraph PreProcessing["🔄 Pre-Processing"]
PP1["Validate Input<br/>Check Length<br/>Rate Limit"]
PP2["Upload to Cloudinary<br/>Validate Image<br/>Convert Format"]
PP3["Extract PDF Text<br/>Validate File<br/>Parse Structure"]
PP4["Sanitize Text<br/>Check Context<br/>Load History"]
end
subgraph AIServices["🧠 AI Services"]
AI1["Google Gemini 1.5<br/>Symptom Analysis<br/>Medical Reasoning"]
AI2["OpenAI Vision<br/>GPT-4V OCR<br/>Text Extraction"]
AI3["OpenAI Vision<br/>Lab Data Parser<br/>Value Extraction"]
AI4["Google Gemini<br/>Text Summarization<br/>Pattern Detection"]
end
subgraph PostProcessing["✨ Post-Processing"]
Post1["Urgency Classification<br/>Action Generation<br/>Medicine Lookup"]
Post2["Structure Medicine Data<br/>Set Dosage Schedule<br/>Validate Names"]
Post3["Flag Abnormal Values<br/>Compare Ranges<br/>Generate Insights"]
Post4["Extract Keywords<br/>Mood Analysis<br/>Tag Generation"]
end
subgraph DataLayer["💾 Data Persistence"]
DB1[("Consultation<br/>Collection")]
DB2[("Prescription<br/>Collection")]
DB3[("Lab Report<br/>Collection")]
DB4[("Diary<br/>Collection")]
end
subgraph Response["📤 Response to Client"]
Res1["Summary + Actions<br/>Urgency Level<br/>Suggested Medicines"]
Res2["Medicine List<br/>Dosage Schedule<br/>Doctor Name"]
Res3["Test Results<br/>Abnormal Flags<br/>Trend Analysis"]
Res4["Summary Text<br/>Mood Score<br/>Health Tags"]
end
Input1 --> API1 --> PP1 --> AI1 --> Post1 --> DB1 --> Res1
Input2 --> API2 --> PP2 --> AI2 --> Post2 --> DB2 --> Res2
Input3 --> API3 --> PP3 --> AI3 --> Post3 --> DB3 --> Res3
Input4 --> API4 --> PP4 --> AI4 --> Post4 --> DB4 --> Res4
style UserInput fill:#e3f2fd,stroke:#1565c0,stroke-width:3px,color:#000
style APILayer fill:#fff3e0,stroke:#e65100,stroke-width:3px,color:#000
style PreProcessing fill:#f3e5f5,stroke:#6a1b9a,stroke-width:3px,color:#000
style AIServices fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#000
style PostProcessing fill:#e0f2f1,stroke:#00695c,stroke-width:3px,color:#000
style DataLayer fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#000
style Response fill:#fce4ec,stroke:#c2185b,stroke-width:3px,color:#000
style Input1 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style Input2 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style Input3 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style Input4 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style API1 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style API2 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style API3 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style API4 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style PP1 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style PP2 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style PP3 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style PP4 fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style AI1 fill:#ffcdd2,stroke:#c62828,stroke-width:2px,color:#000
style AI2 fill:#ffcdd2,stroke:#c62828,stroke-width:2px,color:#000
style AI3 fill:#ffcdd2,stroke:#c62828,stroke-width:2px,color:#000
style AI4 fill:#ffcdd2,stroke:#c62828,stroke-width:2px,color:#000
style Post1 fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style Post2 fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style Post3 fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style Post4 fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style DB1 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style DB2 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style DB3 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style DB4 fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style Res1 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style Res2 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style Res3 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style Res4 fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
Input: Text symptoms (e.g., "Fever and headache for 3 days")
Processing:
- Rate Limit Check: 20 requests per 15 minutes
- Context Loading: Fetch user's chronic conditions and medication history
- Prompt Engineering: Inject medical context into system prompt
- AI Call: Google Gemini 1.5 Flash with temperature 0.7
- Token Tracking: Monitor usage (promptTokens, completionTokens, totalTokens)
- Urgency Classification: Low/Medium/High based on symptom severity
- Action Generation: Immediate steps, lifestyle advice, medicine suggestions
Output:
{
"summary": "Analysis of symptoms...",
"urgency": "Medium",
"actions": ["Take paracetamol", "Rest for 24 hours"],
"lifestyleAdvice": ["Stay hydrated"],
"suggestedMedicines": ["Paracetamol 500mg"],
"tokenUsage": { "totalTokens": 450 }
}Input: Image URL (from Cloudinary)
Processing:
- Image Validation: Check format (JPEG, PNG), size (< 10MB)
- Vision API Call: OpenAI GPT-4 Vision with specialized prompt
- Text Extraction: Parse medicine names, dosages, frequencies
- Database Validation: Cross-reference with OpenFDA medicine database
- Schedule Generation: Convert "twice daily" → reminder schedule
Output:
{
"medicines": [
{
"name": "Metformin",
"dosage": "500mg",
"frequency": "Twice daily",
"duration": "30 days"
}
],
"doctorName": "Dr. Sarah Johnson"
}Input: PDF/Image of lab report
Processing:
- File Parsing: Extract text from PDF using pdf-parse
- Vision OCR: Use OpenAI Vision for handwritten/image reports
- Data Structuring: Extract test names, values, reference ranges
- Abnormality Detection: Flag out-of-range values
- Trend Analysis: Compare with previous reports
Output:
{
"tests": [
{
"testName": "Hemoglobin",
"value": 12.5,
"unit": "g/dL",
"referenceRange": "13-17",
"status": "low"
}
],
"abnormalTests": 1
}Input: Daily health diary entry (text)
Processing:
- Load User Context: Fetch recent health events
- Sentiment Analysis: Detect mood from text
- AI Summarization: Google Gemini condenses entry
- Tag Generation: Extract health keywords
Output:
{
"summary": "User reported mild headache...",
"mood": "neutral",
"tags": ["headache", "fatigue", "sleep"]
}Token Tracking:
- Every AI request logs token usage in
Consultationmodel - Admin dashboard shows total tokens consumed
- Estimated cost calculation:
(totalTokens / 1000) * $0.01
Optimization Strategies:
- Cache common symptom queries for 5 minutes
- Reuse extracted prescription data to avoid re-processing
- Implement prompt compression to reduce input tokens
- Use Gemini Flash (cheaper) for simple tasks, GPT-4 for complex OCR
LifeDoc implements a role-based access control (RBAC) system with three primary user types and five family role levels.
graph TD
Users[All Users] --> Regular[Regular User]
Users --> Doctor[Verified Doctor]
Users --> Admin[System Admin]
Regular --> Features1[✓ Personal Health Records<br/>✓ AI Consultations<br/>✓ Family Management<br/>✓ Vital Tracking]
Doctor --> Features2[✓ All Regular Features<br/>✓ Review Consultations<br/>✓ Meeting Requests<br/>✓ Professional Badge]
Admin --> Features3[✓ All Features<br/>✓ User Management<br/>✓ Doctor Verification<br/>✓ System Analytics<br/>✓ Medical DB Management]
style Users fill:#f5f5f5,stroke:#424242,stroke-width:3px,color:#000
style Regular fill:#e3f2fd,stroke:#1565c0,stroke-width:3px,color:#000
style Doctor fill:#fff3e0,stroke:#e65100,stroke-width:3px,color:#000
style Admin fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#000
style Features1 fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#000
style Features2 fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style Features3 fill:#ffcdd2,stroke:#c62828,stroke-width:2px,color:#000
Permissions:
- ✅ Create and manage personal health records
- ✅ Use AI consultation features
- ✅ Upload prescriptions and lab reports
- ✅ Track vitals and measurements
- ✅ Create family group (becomes admin of that family)
- ✅ Schedule appointments
- ✅ Configure emergency SOS contacts
Restrictions:
- ❌ Cannot review other users' AI consultations
- ❌ Cannot access admin dashboard
- ❌ Cannot manage doctor verification
Additional Permissions:
- ✅ All regular user permissions
- ✅ Review flagged AI consultations
- ✅ Provide professional feedback on cases
- ✅ Request admin meetings for collaboration
- ✅ Access pending consultation review queue
- ✅ Professional badge display on profile
Verification Process:
- User applies via doctor verification form
- Upload 3 documents: Medical License, ID, Degree
- Admin reviews application
- Status changes:
pending→approvedorrejected - User type automatically updated to
doctorupon approval
Full Permissions:
- ✅ All user and doctor permissions
- ✅ Access admin dashboard
- ✅ View all registered users
- ✅ Delete user accounts
- ✅ Approve/reject doctor verifications
- ✅ Manage medicines database
- ✅ View AI token usage statistics
- ✅ Generate system reports
| Role | Access Level | Permissions |
|---|---|---|
| admin | Full Control | Add/remove members, view all health data, modify settings |
| caregiver | High Access | View all health data, add measurements, upload reports |
| member | Standard | View own data, limited view of others (dashboard only) |
| child | Managed | Profile managed by admin/caregiver, no direct access |
| view_only | Read Only | View health summaries only, cannot modify any data |
| Technology | Version | Purpose |
|---|---|---|
| Next.js | 16.1.1 | React framework with App Router, SSR, and ISR |
| React | 18.3.1 | UI component library |
| TypeScript | 5.x | Type-safe development |
| Redux Toolkit | 2.11.2 | State management with slices |
| Tailwind CSS | 4.0 | Utility-first styling framework |
| Axios | 1.13.2 | HTTP client with interceptors |
| Recharts | 3.6.0 | Data visualization and charts |
| Technology | Version | Purpose |
|---|---|---|
| Node.js | 20.x | JavaScript runtime |
| Express.js | 5.2.1 | Web application framework |
| MongoDB | 9.0.2 | NoSQL database |
| Mongoose | 9.0.2 | MongoDB object modeling (ODM) |
| Google Gemini AI | 0.24.1 | Symptom analysis and health insights |
| OpenAI | 6.15.0 | Vision API for document digitization |
| JWT | 9.0.3 | Stateless authentication |
| Bcrypt | 6.0.0 | Password hashing |
| Cloudinary | 2.8.0 | Image and document CDN storage |
| Nodemailer | 7.0.12 | Email service for OTP and notifications |
| Twilio | 5.11.2 | SMS alerts for emergencies |
| Stripe | 20.1.2 | Payment processing and subscription management |
| Node-Cron | 4.2.1 | Background job scheduling for news fetching |
| Service | Purpose | Integration |
|---|---|---|
| Google Gemini 1.5 Flash | AI symptom analysis, diary summarization | Direct API via SDK |
| OpenAI GPT-4 Vision | Prescription OCR, lab report extraction | REST API |
| OpenFDA Drug API | Medicine information and search | Public REST API |
| Cloudinary | Secure media storage and CDN | Node.js SDK |
| Twilio SMS API | Emergency SOS alerts | REST API |
| Stripe API | Payment processing and subscriptions | Node.js SDK |
| RSS Feeds | Health news aggregation | rss-parser library |
LifeDoc's production infrastructure leverages modern cloud services for scalability, reliability, and global performance.
graph TB
subgraph Users["🌐 Users"]
WebUser["Web Browser"]
MobileUser["Mobile Browser"]
PWA["PWA Client"]
end
subgraph CDN["⚡ CDN Layer"]
CF["Cloudflare CDN<br/>DDoS Protection<br/>SSL/TLS"]
end
subgraph Frontend["🎨 Frontend - Vercel"]
NextJS["Next.js 16 App<br/>SSR + ISR<br/>Edge Functions"]
StaticAssets["Static Assets<br/>Images, CSS, JS"]
end
subgraph Backend["⚙️ Backend - Railway/Render"]
LoadBalancer["Load Balancer<br/>Auto-Scaling"]
API1["Express API<br/>Instance 1"]
API2["Express API<br/>Instance 2"]
API3["Express API<br/>Instance 3"]
Cron["Background Jobs<br/>Node-Cron"]
end
subgraph Database["💾 Database"]
MongoDB["MongoDB Atlas<br/>Replica Set<br/>Multi-Region"]
end
subgraph FileStorage["📁 File Storage"]
Cloudinary["Cloudinary CDN<br/>Image Optimization<br/>Video Storage"]
end
subgraph AIServices["🤖 AI Services"]
Gemini["Google Gemini<br/>Symptom Analysis<br/>Text Generation"]
OpenAIVision["OpenAI GPT-4V<br/>OCR Processing<br/>Document Analysis"]
end
subgraph ExternalAPIs["🔌 External APIs"]
Stripe["Stripe API<br/>Payment Processing"]
Twilio["Twilio SMS<br/>Emergency Alerts"]
Email["SMTP Server<br/>Email Delivery"]
OpenFDA["OpenFDA API<br/>Drug Information"]
end
subgraph Monitoring["📊 Monitoring & Logs"]
Sentry["Sentry<br/>Error Tracking"]
Analytics["Analytics<br/>Usage Metrics"]
Logs["Centralized Logs<br/>CloudWatch/Logflare"]
end
WebUser --> CF
MobileUser --> CF
PWA --> CF
CF --> NextJS
CF --> StaticAssets
NextJS --> LoadBalancer
LoadBalancer --> API1
LoadBalancer --> API2
LoadBalancer --> API3
API1 --> MongoDB
API2 --> MongoDB
API3 --> MongoDB
API1 --> Cloudinary
API2 --> Cloudinary
API3 --> Cloudinary
API1 --> Gemini
API1 --> OpenAIVision
API1 --> Stripe
API1 --> Twilio
API1 --> Email
API1 --> OpenFDA
API2 --> Gemini
API2 --> OpenAIVision
API3 --> Gemini
API3 --> OpenAIVision
Cron --> MongoDB
Cron --> OpenFDA
API1 --> Sentry
API2 --> Sentry
API3 --> Sentry
NextJS --> Analytics
API1 --> Logs
API2 --> Logs
API3 --> Logs
style Users fill:#e3f2fd,stroke:#1565c0,stroke-width:3px,color:#000
style CDN fill:#fff3e0,stroke:#e65100,stroke-width:3px,color:#000
style Frontend fill:#f3e5f5,stroke:#6a1b9a,stroke-width:3px,color:#000
style Backend fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#000
style Database fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#000
style FileStorage fill:#e0f2f1,stroke:#00695c,stroke-width:3px,color:#000
style AIServices fill:#fce4ec,stroke:#c2185b,stroke-width:3px,color:#000
style ExternalAPIs fill:#fff9c4,stroke:#f57f17,stroke-width:3px,color:#000
style Monitoring fill:#e1f5fe,stroke:#0277bd,stroke-width:3px,color:#000
style CF fill:#ffe0b2,stroke:#e65100,stroke-width:2px,color:#000
style NextJS fill:#e1bee7,stroke:#6a1b9a,stroke-width:2px,color:#000
style LoadBalancer fill:#ffcdd2,stroke:#c62828,stroke-width:2px,color:#000
style MongoDB fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style Cloudinary fill:#b2dfdb,stroke:#00695c,stroke-width:2px,color:#000
style Gemini fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style OpenAIVision fill:#f8bbd0,stroke:#c2185b,stroke-width:2px,color:#000
style Stripe fill:#fff59d,stroke:#f57f17,stroke-width:2px,color:#000
| Component | Service | Purpose | Scalability |
|---|---|---|---|
| Frontend Hosting | Vercel | Next.js deployment, automatic scaling, edge functions | Automatic horizontal scaling |
| Backend Hosting | Railway/Render | Node.js API hosting with auto-deployment | Manual/Auto scaling up to 10 instances |
| Database | MongoDB Atlas | Managed MongoDB with replica set | Vertical + Horizontal scaling |
| CDN | Cloudflare | Global content delivery, DDoS protection | Global edge network |
| File Storage | Cloudinary | Media storage and optimization | Unlimited storage with CDN |
| AI Processing | Google Cloud / OpenAI | AI inference and processing | Pay-per-request scaling |
| Monitoring | Sentry / CloudWatch | Error tracking and system metrics | Real-time monitoring |
Git Push → GitHub Actions → Build & Test → Deploy to Staging → Manual Approval → Deploy to Production → Health Check → Rollback (if failed)
- Multi-Region Database: MongoDB Atlas replica set across 3 availability zones
- Auto-Scaling: Backend automatically scales based on CPU and memory usage
- Load Balancing: Traffic distributed across multiple API instances
- CDN Caching: Static assets cached at edge locations globally
- Health Checks: Continuous monitoring with automatic instance restart
- Backup Strategy: Daily automated backups with 30-day retention
- Disaster Recovery: Point-in-time recovery within 24 hours
Complete API reference for LifeDoc healthcare platform. All endpoints follow RESTful conventions with JWT authentication.
Development: http://localhost:5000/api
Production: https://api.lifedoc.app/api
All protected routes require JWT token in header:
Authorization: Bearer <your_jwt_token>Token Details:
- Format: JWT (JSON Web Token)
- Expiry: 24 hours
- Payload:
{ id, type, iat, exp }
{
"success": true,
"data": {
// Response data
},
"message": "Operation successful"
}{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Error description",
"details": []
},
"statusCode": 400
}| Code | Description | Common Cause |
|---|---|---|
| 200 | OK | Successful request |
| 201 | Created | Resource created |
| 400 | Bad Request | Invalid input |
| 401 | Unauthorized | Invalid/missing token |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource doesn't exist |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
| Type | Limit | Window | Scope |
|---|---|---|---|
| Default | 100 req | 15 min | Per IP |
| AI Endpoints | 20 req | 15 min | Per User |
| File Upload | 10 req | 15 min | Per User |
| Auth | 5 req | 15 min | Per IP |
Headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1641024000| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /auth/signup |
Create new account & send OTP | ❌ |
| POST | /auth/verify-otp |
Verify OTP & activate account | ❌ |
| POST | /auth/login |
Login with credentials | ❌ |
| POST | /auth/forgot-password |
Request password reset | ❌ |
| POST | /auth/reset-password |
Reset password with token | ❌ |
| GET | /auth/profile |
Get current user profile | ✅ |
| PUT | /auth/profile |
Update user profile | ✅ |
| POST | /auth/profile/photo |
Upload profile photo | ✅ |
Example - Sign Up:
// Request
POST /auth/signup
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePass123",
"age": 35
}
// Response
{
"message": "OTP sent to email",
"userId": "507f1f77bcf86cd799439011"
}Example - Login:
// Request
POST /auth/login
{
"email": "john@example.com",
"password": "SecurePass123"
}
// Response
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"type": "user"
}
}| Method | Endpoint | Description | Auth | Rate Limit |
|---|---|---|---|---|
| POST | /ai/analyze |
Symptom analysis | ✅ | 20/15min |
| POST | /ai/analyze-prescription |
Extract prescription data | ✅ | 10/15min |
| POST | /ai/analyze-lab-report |
Parse lab report | ✅ | 10/15min |
| POST | /ai/summerizer |
Summarize diary entry | ✅ | 20/15min |
| POST | /ai/generate-questions |
Generate health questions | ✅ | 20/15min |
| POST | /ai/analyze-lifestyle |
Analyze lifestyle factors | ✅ | 20/15min |
| POST | /ai/guide |
Get health guidance | ✅ | 20/15min |
Example - Symptom Analysis:
// Request
POST /ai/analyze
Authorization: Bearer <token>
{
"text": "Severe headache for 3 days with dizziness",
"language": "en"
}
// Response
{
"summary": "Possible tension headaches...",
"urgency": "Medium",
"actions": ["Stay hydrated", "Rest in dark room"],
"lifestyleAdvice": ["Reduce screen time"],
"suggestedMedicines": ["Paracetamol 500mg"],
"consultationId": "65a1b2c3d4e5f6g7h8i9j0k1"
}Example - Prescription OCR:
// Request
POST /ai/analyze-prescription
Authorization: Bearer <token>
{
"imageUrl": "https://cloudinary.com/.../prescription.jpg"
}
// Response
{
"medicines": [
{
"name": "Metformin",
"dosage": "500mg",
"frequency": "Twice daily",
"duration": "30 days",
"instructions": "Take after meals"
}
],
"doctorName": "Dr. Sarah Johnson",
"prescriptionDate": "2026-01-05"
}| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /measurements |
Add new measurement | ✅ |
| GET | /measurements |
Get measurement history | ✅ |
| GET | /measurements/:id |
Get single measurement | ✅ |
| PUT | /measurements/:id |
Update measurement | ✅ |
| DELETE | /measurements/:id |
Delete measurement | ✅ |
Supported Types:
blood_pressure- Systolic/Diastolic (mmHg)glucose- Blood sugar (mg/dL)heart_rate- BPMweight- kg/lbstemperature- °C/°Fspo2- Oxygen saturation (%)
Example - Add Blood Pressure:
// Request
POST /measurements
Authorization: Bearer <token>
{
"type": "blood_pressure",
"value": { "systolic": 120, "diastolic": 80 },
"unit": "mmHg",
"timestamp": "2026-01-10T08:30:00Z",
"notes": "Morning reading"
}
// Response
{
"message": "Measurement added successfully",
"measurement": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"type": "blood_pressure",
"value": { "systolic": 120, "diastolic": 80 },
"timestamp": "2026-01-10T08:30:00Z"
}
}Example - Get Measurements:
GET /measurements?type=blood_pressure&startDate=2026-01-01&limit=10| Method | Endpoint | Description | Auth | Content-Type |
|---|---|---|---|---|
| POST | /lab-reports |
Upload lab report | ✅ | multipart/form-data |
| GET | /lab-reports |
Get all lab reports | ✅ | - |
| GET | /lab-reports/:id |
Get single report | ✅ | - |
| PUT | /lab-reports/:id |
Update report | ✅ | - |
| DELETE | /lab-reports/:id |
Delete report | ✅ | - |
Example - Upload:
POST /lab-reports
Content-Type: multipart/form-data
Authorization: Bearer <token>
file: <PDF or Image>
reportDate: "2026-01-08"
testType: "Complete Blood Count"
notes: "Annual checkup"| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /doctor-reports |
Create doctor visit report | ✅ |
| GET | /doctor-reports |
Get all reports | ✅ |
| GET | /doctor-reports/:id |
Get single report | ✅ |
| PUT | /doctor-reports/:id |
Update report | ✅ |
| DELETE | /doctor-reports/:id |
Delete report | ✅ |
Example - Create Report:
// Request
POST /doctor-reports
Authorization: Bearer <token>
{
"visitDate": "2026-01-09",
"doctorName": "Dr. Sarah Johnson",
"specialty": "Endocrinologist",
"diagnosis": ["Type 2 Diabetes"],
"prescriptions": [
{
"medicine": "Metformin",
"dosage": "500mg",
"frequency": "Twice daily",
"duration": "30 days"
}
],
"notes": "Follow-up in 4 weeks"
}| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /appointments |
Create appointment | ✅ |
| GET | /appointments |
Get all appointments | ✅ |
| GET | /appointments/:id |
Get single appointment | ✅ |
| PUT | /appointments/:id |
Update appointment | ✅ |
| DELETE | /appointments/:id |
Delete appointment | ✅ |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /diary |
Create diary entry | ✅ |
| GET | /diary |
Get all entries | ✅ |
| GET | /diary/:id |
Get single entry | ✅ |
| PUT | /diary/:id |
Update entry | ✅ |
| DELETE | /diary/:id |
Delete entry | ✅ |
| POST | /diary/:id/summarize |
Generate AI summary | ✅ |
| Method | Endpoint | Description | Auth | Role |
|---|---|---|---|---|
| POST | /family |
Create family group | ✅ | - |
| GET | /family |
Get family details | ✅ | - |
| POST | /family/members |
Add family member | ✅ | Admin |
| GET | /family/members |
Get all members | ✅ | - |
| PUT | /family/members/:id |
Update member role | ✅ | Admin |
| DELETE | /family/members/:id |
Remove member | ✅ | Admin |
| POST | /family/analyze |
AI family health analysis | ✅ | - |
| GET | /family/members/:id/health |
Get member health data | ✅ | - |
Example - Create Family:
// Request
POST /family
Authorization: Bearer <token>
{
"familyName": "The Smiths"
}
// Response
{
"family": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"adminId": "507f1f77bcf86cd799439011",
"familyName": "The Smiths",
"members": [
{
"userId": "507f1f77bcf86cd799439011",
"name": "John Doe",
"role": "admin"
}
]
}
}| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /sos/alert |
Send emergency alert | ✅ |
| GET | /sos/history |
Get SOS history | ✅ |
Example - Send SOS:
// Request
POST /sos/alert
Authorization: Bearer <token>
{
"location": {
"latitude": 37.7749,
"longitude": -122.4194,
"address": "123 Main St, San Francisco"
},
"message": "Emergency! Please help.",
"severity": "critical"
}
// Response
{
"message": "SOS alert sent successfully",
"alertsSent": 3,
"contacts": [
{
"name": "Jane Doe",
"phone": "+1234567890",
"status": "sent"
}
],
"location": {
"googleMapsUrl": "https://maps.google.com/?q=37.7749,-122.4194"
}
}| Method | Endpoint | Description | Auth |
|---|---|---|---|
| GET | /reference/medicines/search |
Search medicines | ✅ |
| GET | /reference/medicines/:id |
Get medicine details | ✅ |
| GET | /reference/lab-tests |
Get lab test reference | ✅ |
| GET | /reference/lab-tests/:id |
Get lab test details | ✅ |
Example - Search:
GET /reference/medicines/search?q=metformin&limit=10| Method | Endpoint | Description | Auth |
|---|---|---|---|
| GET | /news |
Get health news | ✅ |
| GET | /news/:id |
Get news article | ✅ |
| Method | Endpoint | Description | Auth | Content-Type |
|---|---|---|---|---|
| POST | /doctor-verification/apply |
Apply for verification | ✅ | multipart/form-data |
| GET | /doctor-verification/status |
Get application status | ✅ | - |
| GET | /doctor-verification/admin/pending |
Get pending applications | ✅ (admin) | - |
| PUT | /doctor-verification/admin/review/:id |
Review application | ✅ (admin) | - |
Example - Apply:
POST /doctor-verification/apply
Content-Type: multipart/form-data
Authorization: Bearer <token>
licenseNumber: "MD123456"
specialty: "Cardiology"
documents: [file1.pdf, file2.pdf, file3.pdf] // Up to 5 files
// Response
{
"message": "Application submitted successfully",
"application": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"status": "pending",
"appliedAt": "2026-01-10T12:00:00Z"
}
}| Method | Endpoint | Description | Auth | Role |
|---|---|---|---|---|
| GET | /doctors |
Get all verified doctors | ✅ | any |
| GET | /doctors/:id |
Get doctor profile | ✅ | any |
| PUT | /doctors/availability |
Update availability | ✅ | doctor |
| GET | /doctors/:id/slots |
Get available slots | ✅ | any |
| POST | /appointments |
Book appointment | ✅ | user |
| GET | /appointments |
Get user appointments | ✅ | user |
| GET | /appointments/doctor-appointments |
Get doctor's appointments | ✅ | doctor |
| DELETE | /appointments/:id |
Cancel appointment | ✅ | user/doctor |
Example - Get Doctors:
// Response
GET /doctors
{
"doctors": [
{
"id": "507f1f77bcf86cd799439011",
"name": "Dr. Sarah Johnson",
"email": "sarah@hospital.com",
"specialty": "Cardiology",
"type": "doctor",
"isVerified": true,
"profile": {
"qualifications": "MD, MBBS",
"experience": "15 years"
},
"availability": {
"monday": ["09:00-12:00", "14:00-17:00"],
"tuesday": ["09:00-12:00", "14:00-17:00"],
"friday": ["09:00-13:00"]
}
}
]
}Example - Book Appointment:
// Request
POST /appointments
Authorization: Bearer <token>
{
"doctorId": "507f1f77bcf86cd799439011",
"providerName": "Dr. Sarah Johnson",
"specialty": "Cardiology",
"appointmentDate": "2026-01-15T10:00:00Z",
"notes": "Follow-up consultation"
}
// Response
{
"message": "Appointment booked successfully",
"appointment": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"status": "scheduled",
"appointmentDate": "2026-01-15T10:00:00Z"
}
}| Method | Endpoint | Description | Auth | Role |
|---|---|---|---|---|
| POST | /meetings/request |
Request admin meeting | ✅ | doctor |
| GET | /meetings/pending |
Get pending requests | ✅ | admin |
| PUT | /meetings/approve/:id |
Approve/schedule meeting | ✅ | admin |
| GET | /meetings/upcoming |
Get upcoming meetings | ✅ | doctor |
| POST | /meetings/summarize/:id |
AI meeting summary | ✅ | admin |
Example - Request Meeting:
// Request
POST /meetings/request
Authorization: Bearer <token> // Doctor token
{
"topic": "New Treatment Protocol Discussion",
"reason": "Need guidance on implementing new diabetes treatment guidelines",
"urgency": "Urgent"
}
// Response
{
"message": "Meeting request submitted successfully",
"request": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"status": "pending",
"urgency": "Urgent",
"createdAt": "2026-01-10T12:00:00Z"
}
}Example - Approve Meeting:
// Request
PUT /meetings/approve/:id
Authorization: Bearer <token> // Admin token
{
"meetingLink": "https://meet.google.com/abc-defg-hij",
"scheduledAt": "2026-01-12T14:00:00Z",
"duration": 60
}
// Response
{
"message": "Meeting approved and scheduled",
"meeting": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"status": "approved",
"meetingLink": "https://meet.google.com/abc-defg-hij",
"scheduledAt": "2026-01-12T14:00:00Z"
}
}| Method | Endpoint | Description | Auth | Role |
|---|---|---|---|---|
| PUT | /consultation/:id/request-review |
Request doctor review | ✅ | user |
| GET | /consultation/history |
Get consultation history | ✅ | user |
| GET | /consultation/pending-reviews |
Get pending reviews | ✅ | doctor |
| PUT | /consultation/:id/review |
Submit professional review | ✅ | doctor |
Example - Request Review:
// Request
PUT /consultation/:id/request-review
Authorization: Bearer <token>
{
"notes": "Would like a doctor to verify this assessment"
}
// Response
{
"message": "Review requested successfully",
"consultation": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"reviewStatus": "pending"
}
}Example - Doctor Submit Review:
// Request
PUT /consultation/:id/review
Authorization: Bearer <token> // Doctor token
{
"doctorFeedback": "AI assessment is accurate. Continue with recommended treatment and monitor symptoms closely.",
"additionalRecommendations": [
"Follow up if symptoms persist beyond 48 hours",
"Consider blood pressure monitoring"
]
}
// Response
{
"message": "Review submitted successfully",
"consultation": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"reviewStatus": "reviewed",
"reviewedBy": "507f1f77bcf86cd799439011",
"reviewedAt": "2026-01-10T14:30:00Z"
}
}| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /subscription/create-checkout-session |
Create Stripe checkout | ✅ |
| GET | /subscription/status |
Get subscription status | ✅ |
| POST | /subscription/webhook |
Stripe webhook (public) | ❌ |
Example - Create Checkout:
// Request
POST /subscription/create-checkout-session
Authorization: Bearer <token>
{
"priceId": "price_1234567890",
"successUrl": "https://lifedoc.app/dashboard?success=true",
"cancelUrl": "https://lifedoc.app/pricing"
}
// Response
{
"sessionId": "cs_test_1234567890abcdef",
"url": "https://checkout.stripe.com/pay/cs_test_1234567890abcdef"
}Example - Get Status:
// Response
GET /subscription/status
{
"hasActiveSubscription": true,
"subscription": {
"id": "sub_1234567890",
"customerId": "cus_1234567890",
"status": "active",
"currentPeriodStart": "2026-01-10T00:00:00Z",
"currentPeriodEnd": "2026-02-10T00:00:00Z",
"cancelAtPeriodEnd": false,
"plan": {
"name": "Premium Monthly",
"amount": 999, // $9.99 in cents
"currency": "usd",
"interval": "month"
}
},
"payments": [
{
"amount": 999,
"status": "succeeded",
"paymentDate": "2026-01-10T10:15:00Z"
}
]
}| Method | Endpoint | Description | Auth |
|---|---|---|---|
| GET | /news |
Get health news articles | ✅ |
| POST | /saved-posts |
Save article | ✅ |
| DELETE | /saved-posts/:articleId |
Unsave article | ✅ |
| GET | /saved-posts |
Get saved articles | ✅ |
| GET | /saved-posts/ids |
Get saved article IDs | ✅ |
Example - Save Post:
// Request
POST /saved-posts
Authorization: Bearer <token>
{
"articleId": "65a1b2c3d4e5f6g7h8i9j0k1"
}
// Response
{
"message": "Article saved successfully",
"savedPost": {
"id": "65a1b2c3d4e5f6g7h8i9j0k1",
"userId": "507f1f77bcf86cd799439011",
"articleId": "65a1b2c3d4e5f6g7h8i9j0k1",
"savedAt": "2026-01-10T12:00:00Z"
}
}| Method | Endpoint | Description | Auth |
|---|---|---|---|
| GET | /share/:userId |
Get shareable health profile | ❌ |
Example:
// Response
GET /share/507f1f77bcf86cd799439011
{
"user": {
"name": "John Doe",
"age": 35,
"profile": {
"gender": "Male",
"bloodGroup": "O+",
"chronicConditions": ["Type 2 Diabetes"],
"allergies": ["Penicillin"]
}
},
"recentMeasurements": [
{
"type": "blood_pressure",
"value": {"systolic": 120, "diastolic": 80},
"timestamp": "2026-01-10T08:00:00Z"
}
],
"emergencyContacts": [
{
"name": "Jane Doe",
"relationship": "Spouse",
"phone": "+1234567890"
}
]
}| Method | Endpoint | Description | Auth | Role |
|---|---|---|---|---|
| GET | /doctor/consultations/pending |
Get pending reviews | ✅ | doctor |
| GET | /doctor/consultations/:id |
Get consultation details | ✅ | doctor |
| POST | /doctor/consultations/:id/review |
Submit review | ✅ | doctor |
| POST | /doctor/meetings/request |
Request admin meeting | ✅ | doctor |
Note: These endpoints are being moved to
/consultation/*and/meetings/*routes. Use the new routes for new integrations.
| Method | Endpoint | Description | Auth | Content-Type |
|---|---|---|---|---|
| POST | /doctor-verification |
Apply for verification | ✅ | multipart/form-data |
| GET | /doctor-verification/:id |
Get verification status | ✅ | - |
| PUT | /doctor-verification/:id |
Update application | ✅ | - |
Example - Apply:
POST /doctor-verification
Content-Type: multipart/form-data
Authorization: Bearer <token>
licenseDocument: <PDF>
idDocument: <PDF>
degreeDocument: <PDF>
specialty: "Cardiology"
licenseNumber: "MD123456"| Method | Endpoint | Description | Auth | Role |
|---|---|---|---|---|
| GET | /admin/stats |
Get system statistics | ✅ | admin |
| GET | /admin/users |
Get all users | ✅ | admin |
| DELETE | /admin/users/:id |
Delete user account | ✅ | admin |
| GET | /admin/medicines |
Get medicine database | ✅ | admin |
| POST | /admin/medicines |
Add medicine | ✅ | admin |
| PUT | /admin/medicines/:id |
Update medicine | ✅ | admin |
| DELETE | /admin/medicines/:id |
Delete medicine | ✅ | admin |
| GET | /admin/lab-tests |
Get lab tests database | ✅ | admin |
| POST | /admin/lab-tests |
Add lab test | ✅ | admin |
| PUT | /admin/lab-tests/:id |
Update lab test | ✅ | admin |
| GET | /admin/ai/stats |
Get AI usage statistics | ✅ | admin |
| GET | /admin/ai/logs |
Get AI consultation logs | ✅ | admin |
Example - System Stats:
// Response
GET /admin/stats
{
"totalUsers": 1250,
"activeUsers": 890,
"totalDoctors": 45,
"verifiedDoctors": 38,
"pendingVerifications": 7,
"totalConsultations": 3450,
"consultationsThisMonth": 456,
"totalLabReports": 890,
"totalPrescriptions": 1200,
"activeSubscriptions": 320,
"totalRevenue": 156780.00,
"revenueThisMonth": 15600.00,
"newUsersThisWeek": 67,
"averageSessionDuration": "12m 34s"
}Example - AI Stats:
// Response
GET /admin/ai/stats
{
"totalConsultations": 1250,
"totalTokensUsed": 450000,
"averageTokensPerConsultation": 360,
"estimatedCost": "$4.50",
"consultationsByUrgency": {
"Low": 500,
"Medium": 600,
"High": 150
},
"consultationsByMonth": {
"December 2025": 380,
"January 2026": 456
},
"topSymptoms": [
{"symptom": "headache", "count": 234},
{"symptom": "fever", "count": 189},
{"symptom": "fatigue", "count": 167}
]
}| Method | Endpoint | Description | Auth | Max Size |
|---|---|---|---|---|
| POST | /upload |
Upload file to Cloudinary | ✅ | 50MB |
Example:
POST /upload
Content-Type: multipart/form-data
Authorization: Bearer <token>
image: <File>
// Response
{
"message": "File uploaded successfully",
"url": "https://res.cloudinary.com/.../image.jpg",
"publicId": "lifedoc/1234567890",
"format": "jpg",
"width": 1920,
"height": 1080
}Most GET endpoints support these query parameters:
| Parameter | Example | Description | Default |
|---|---|---|---|
page |
?page=1 |
Page number | 1 |
limit |
&limit=20 |
Items per page (max: 100) | 20 |
sort |
&sort=createdAt |
Sort field | createdAt |
order |
&order=desc |
Sort order (asc/desc) | desc |
startDate |
&startDate=2026-01-01 |
Filter from date | - |
endDate |
&endDate=2026-01-10 |
Filter to date | - |
search |
&search=keyword |
Search query | - |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /webhooks |
Register webhook | ✅ |
| GET | /webhooks |
List webhooks | ✅ |
| DELETE | /webhooks/:id |
Delete webhook | ✅ |
Supported Events:
measurement.criticalconsultation.high_urgencyfamily.member_addedreport.analyzed
npm install @lifedoc/api-clientimport { LifeDocClient } from '@lifedoc/api-client';
const client = new LifeDocClient({
apiKey: 'your_jwt_token',
baseURL: 'https://api.lifedoc.app'
});
// Get measurements
const data = await client.measurements.list({
type: 'blood_pressure',
limit: 10
});Import collection: https://www.postman.com/lifedoc/collection
# Login
curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"john@example.com","password":"SecurePass123"}'
# Get Profile
curl -X GET http://localhost:5000/api/auth/profile \
-H "Authorization: Bearer YOUR_TOKEN"
# Add Measurement
curl -X POST http://localhost:5000/api/measurements \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"type":"blood_pressure","value":{"systolic":120,"diastolic":80}}'- ✅ Initial release
- ✅ JWT authentication
- ✅ All core endpoints
- ✅ Rate limiting
- ✅ AI integration
- 🔄 GraphQL endpoint
- 🔄 WebSocket support
- 🔄 Batch operations
- 🔄 Enhanced filtering
lifedoc/
├── client/ # Frontend (Next.js 16)
│ ├── src/
│ │ ├── app/ # Next.js App Router Pages
│ │ │ ├── page.tsx # Landing page
│ │ │ ├── dashboard/ # User dashboard
│ │ │ ├── lab-reports/ # Lab report management
│ │ │ ├── doctor-reports/ # Doctor visit reports
│ │ │ ├── measurements/ # Vital signs tracking
│ │ │ ├── diary/ # Health diary
│ │ │ ├── family/ # Family management
│ │ │ ├── consultation/ # AI consultation
│ │ │ ├── scan/ # Prescription scanner
│ │ │ ├── admin/ # Admin dashboard
│ │ │ └── doctor/ # Doctor portal
│ │ ├── components/ # Reusable UI Components
│ │ │ ├── Navbar.tsx
│ │ │ ├── DashboardLayout.tsx
│ │ │ ├── ProtectedRoute.tsx
│ │ │ └── ...
│ │ ├── store/ # Redux State Management
│ │ │ └── slices/
│ │ │ ├── authSlice.ts
│ │ │ ├── measurementSlice.ts
│ │ │ └── ...
│ │ └── utils/ # Helper Functions
│ ├── public/ # Static Assets
│ └── package.json
│
├── server/ # Backend (Express.js)
│ ├── controllers/ # Business Logic
│ │ ├── adminController.js
│ │ ├── consultationController.js
│ │ └── sosController.js
│ ├── models/ # Mongoose Schemas
│ │ ├── User.js
│ │ ├── Consultation.js
│ │ ├── LabReport.js
│ │ ├── DoctorReport.js
│ │ └── ...
│ ├── routes/ # API Routes
│ │ ├── auth.js
│ │ ├── ai.js
│ │ ├── measurements.js
│ │ ├── labReports.js
│ │ └── ...
│ ├── middleware/ # Express Middleware
│ │ ├── authMiddleware.js
│ │ ├── errorMiddleware.js
│ │ └── uploadMiddleware.js
│ ├── services/ # External Services
│ │ └── aiService.js
│ ├── jobs/ # Background Jobs
│ │ └── newsFetcher.js
│ ├── scripts/ # Utility Scripts
│ │ ├── createAdmin.js
│ │ └── seedMedicalData.js
│ ├── prompts/ # AI Prompts
│ │ ├── labReportAnalyzer.txt
│ │ └── diarySummerizer.txt
│ ├── test/ # Tests
│ ├── server.js # Entry point
│ └── package.json
│
├── docs/ # Documentation
│ ├── TECHNICAL_FLOWS.md
│ └── ROUND2_PLAN.md
│
└── README.md # This file
/client/src/app/- File-based routing with Next.js 16 App Router/client/src/store/slices/- Redux state management with TypeScript/server/routes/- RESTful API endpoint definitions/server/models/- MongoDB schema definitions with Mongoose/server/services/- Abstraction layer for external API integrations
// Token generation with 24-hour expiry
const token = jwt.sign(
{ id: user._id, type: user.type },
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);- Bcrypt hashing with salt rounds of 10
- Minimum password length: 8 characters
- Password validation: Must include letters and numbers
- OTP expiry: 10 minutes for email verification
// Middleware chain for protected routes
router.get('/admin/stats',
authMiddleware, // Verify JWT
adminCheck, // Verify user.type === 'admin'
getStats // Execute controller
);- Data at Rest: AES-256 encryption for sensitive fields
- Data in Transit: HTTPS/TLS for all API communications
- Password Storage: Bcrypt with automatic salt generation
// Example: Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({ message: 'Invalid email format' });
}
// Sanitize user input to prevent XSS
const sanitizedInput = input.trim().replace(/<script>/gi, '');- File type validation: Only allow images (JPEG, PNG) and PDFs
- File size limit: 10MB maximum
- Virus scanning: Integration with ClamAV (planned)
- Secure storage: Cloudinary with signed URLs
// Prevent brute force attacks
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per window
message: 'Too many requests, please try again later'
});
app.use('/api/', limiter);// Strict CORS policy
const corsOptions = {
origin: process.env.CLIENT_URL || 'http://localhost:3000',
credentials: true,
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));app.use(helmet({
contentSecurityPolicy: true,
xssFilter: true,
noSniff: true,
referrerPolicy: { policy: 'same-origin' }
}));- Connection string encryption: Store in environment variables
- Authentication required: Username and password authentication
- IP whitelisting: Restrict access to known IPs
- Connection pooling: Limit concurrent connections
// Use Mongoose to prevent NoSQL injection
const user = await User.findOne({
email: sanitize(email) // Always sanitize inputs
});# Never commit .env files
echo ".env" >> .gitignore
# Use different configs for each environment
NODE_ENV=production
JWT_SECRET=<complex-random-string-min-32-chars>- Separate keys for development and production
- Key rotation every 90 days
- Monitor usage to detect unauthorized access
- Use API key restrictions (domain, IP, referrer)
// Log all authentication attempts
logger.info('Login attempt', {
email: email,
ip: req.ip,
timestamp: new Date(),
success: true
});- Log all access to sensitive data (lab reports, prescriptions)
- Track failed login attempts (lock account after 5 failures)
- Monitor AI API usage for anomalies
- Set up alerts for suspicious activities
- Data Minimization: Collect only necessary health information
- Access Controls: Role-based access to patient data
- Audit Trails: Log all PHI access and modifications
- Data Retention: Implement retention policies (5 years for lab reports)
- Patient Rights: Allow users to export and delete their data
- Right to Access: API endpoint for data export
- Right to Erasure: Delete user and all associated data
- Data Portability: Export data in JSON format
- Consent Management: Explicit consent for data processing
cd client
npm install # Install dependencies
npm run dev # Start dev server (localhost:3000)
npm run build # Build for production
npm start # Start production server
npm test # Run tests
npm run lint # Run lintercd server
npm install # Install dependencies
npm run dev # Start with auto-reload (localhost:5000)
npm start # Start production server
npm test # Run tests
npm run test:watch # Run tests in watch modecd server
# Create admin user
node scripts/createAdmin.js
# Seed medical database
node scripts/seedMedicalData.js
# List all users
node scripts/listUsers.js
# Fetch health news
node scripts/fetchNews.js# Build and start
docker-compose up --build
# Start in background
docker-compose up -d
# Stop containers
docker-compose down
# View logs
docker-compose logs -f# Clone repository
git clone https://github.com/your-username/lifedoc.git
# Create feature branch
git checkout -b feature/new-feature
# Commit changes
git add .
git commit -m "feat: add new feature"
# Push to remote
git push origin feature/new-feature| Software | Minimum Version | Purpose |
|---|---|---|
| Node.js | 18.x | JavaScript runtime |
| npm | 8.x | Package manager |
| MongoDB | 5.x | Database |
| Git | 2.x | Version control |
git clone https://github.com/your-username/lifedoc.git
cd lifedoccd server
npm install
# Create environment file
cp .env.example .env
# Edit .env with your credentials
# Start server
npm run devcd client
npm install
# Create environment file
cp .env.local.example .env.local
# Edit .env.local
# Start client
npm run dev- Frontend: http://localhost:3000
- Backend: http://localhost:5000
Create .env file in server/ directory:
# Server
SERVER_PORT=5000
NODE_ENV=development
# Database
MONGODB_URI=mongodb://localhost:27017/lifedoc
# Security
JWT_SECRET=your_super_secret_jwt_key_minimum_32_characters
# AI Services
GEMINI_API_KEY=your_google_gemini_api_key
OPENAI_API_KEY=your_openai_api_key
# Email (Gmail example)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your_email@gmail.com
EMAIL_PASS=your_app_specific_password
# SMS (Twilio)
TWILIO_ACCOUNT_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_PHONE_NUMBER=+1234567890
# Cloud Storage (Cloudinary)
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
# Payment (Stripe)
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
# Client URL (for CORS and redirects)
CLIENT_URL=http://localhost:3000Create .env.local file in client/ directory:
NEXT_PUBLIC_API_URL=http://localhost:5000
NEXT_PUBLIC_APP_URL=http://localhost:3000- Visit Google AI Studio
- Create new project and generate API key
- Add to
.envasGEMINI_API_KEY
- Visit OpenAI Platform
- Create new secret key
- Add to
.envasOPENAI_API_KEY
- Sign up at Cloudinary
- Get credentials from Dashboard
- Add cloud name, API key, and API secret to
.env
- Sign up at Twilio
- Get Account SID and Auth Token
- Purchase phone number
- Add credentials to
.env
- Sign up at Stripe
- Get API keys from Dashboard
- Add secret key and publishable key to
.env - Set up webhook endpoint for subscription events
- Add webhook secret to
.env
| Variable | Required | Description | Example |
|---|---|---|---|
SERVER_PORT |
Yes | Backend port | 5000 |
NODE_ENV |
Yes | Environment | development |
MONGODB_URI |
Yes | MongoDB connection | mongodb://localhost:27017/lifedoc |
JWT_SECRET |
Yes | JWT secret key (32+ chars) | your_secret_key |
GEMINI_API_KEY |
Yes | Google Gemini API key | AIza... |
OPENAI_API_KEY |
Optional | OpenAI Vision API key | sk-... |
EMAIL_HOST |
Yes | SMTP server | smtp.gmail.com |
EMAIL_PORT |
Yes | SMTP port | 587 |
EMAIL_USER |
Yes | Email address | your@email.com |
EMAIL_PASS |
Yes | Email password | app_password |
TWILIO_ACCOUNT_SID |
Optional | Twilio account ID | AC... |
TWILIO_AUTH_TOKEN |
Optional | Twilio auth token | your_token |
TWILIO_PHONE_NUMBER |
Optional | Twilio phone | +1234567890 |
CLOUDINARY_CLOUD_NAME |
Yes | Cloudinary cloud name | your_cloud |
CLOUDINARY_API_KEY |
Yes | Cloudinary API key | 123456789 |
CLOUDINARY_API_SECRET |
Yes | Cloudinary secret | your_secret |
STRIPE_SECRET_KEY |
Yes | Stripe secret key | sk_test_... |
STRIPE_PUBLISHABLE_KEY |
Yes | Stripe publishable key | pk_test_... |
STRIPE_WEBHOOK_SECRET |
Yes | Stripe webhook secret | whsec_... |
CLIENT_URL |
Yes | Frontend URL for CORS | http://localhost:3000 |
| Variable | Required | Description | Example |
|---|---|---|---|
NEXT_PUBLIC_API_URL |
Yes | Backend API URL | http://localhost:5000 |
NEXT_PUBLIC_APP_URL |
Yes | Frontend URL | http://localhost:3000 |
.env files to version control!
# Add to .gitignore
echo ".env" >> .gitignore
echo ".env.local" >> client/.gitignore- User authentication with OTP verification
- AI-powered symptom analysis (Gemini 1.5 Flash)
- Prescription digitization (Vision AI)
- Lab report analysis and parsing
- Family health management with role-based access
- Vital signs tracking (BP, glucose, heart rate, weight, temp, SpO2)
- Health diary with AI summarization
- Doctor verification system with document upload
- Emergency SOS alerts with SMS integration
- Medicine and lab test reference database
- Health news aggregation with RSS feeds
- Admin dashboard with system statistics
- Doctor portal with consultation review system
- Meeting request system (doctor-admin collaboration)
- Premium subscription system with Stripe integration
- Payment webhook processing
- Doctor discovery and appointment booking
- Saved articles/posts functionality
- Public health profile sharing
- Background jobs for news fetching
- Comprehensive API documentation
- Rate limiting and security measures
-
Voice-First Interface
- Wake word activation ("Hey LifeDoc")
- Voice commands for hands-free navigation
- Text-to-speech for elderly users
-
Pharmacy Integration
- Direct prescription forwarding to local pharmacies
- Real-time stock availability
- Delivery tracking
-
Advanced Analytics
- Predictive health insights using ML models
- Trend analysis with anomaly detection
- Personalized health score calculation
- Sentiment analysis on diary entries
- Depression detection with gentle interventions
- Integration with mental health professionals
- Mood tracking with visualization
- Google Health Connect (Android)
- Apple HealthKit (iOS)
- Fitbit API integration
- Automatic vital syncing
- Video consultation with doctors
- In-app chat with healthcare professionals
- Appointment scheduling with real doctors
- E-prescription generation
- Health score and achievement system
- Daily health challenges
- Streak tracking for medication adherence
- Rewards and badges
- Health data on permissioned blockchain
- Patient-controlled data sharing
- Smart contracts for consent management
- Immutable medical record history
- Multi-modal AI (text + image + voice)
- Predictive disease risk assessment
- Personalized treatment recommendations
- Drug interaction warnings
- Mobile apps (iOS & Android - React Native)
- Progressive Web App (PWA) with offline support
- Chrome extension for quick health logging
- WhatsApp bot integration
- Dashboard for doctors to monitor patients
- Bulk patient data analysis
- Clinical decision support tools
- Integration with hospital EMR systems
- HIPAA full compliance certification
- GDPR compliance for EU users
- FDA approval for medical device classification
- ISO 27001 certification
- Health communities and support groups
- Anonymous health question forums
- Expert Q&A sessions
- Patient success story sharing
We welcome feature suggestions! Please:
- Check existing GitHub Issues
- Open a new issue with
[Feature Request]tag - Describe the feature and its benefits
- Community voting determines priority
We welcome contributions from the community! Here's how you can help:
-
Fork the Repository
git clone https://github.com/your-username/lifedoc.git cd lifedoc -
Create a Feature Branch
git checkout -b feature/amazing-feature
-
Make Your Changes
- Write clean, documented code
- Follow existing code style
- Add tests for new features
- Update documentation
-
Test Your Changes
npm test npm run lint -
Commit Your Changes
git commit -m "feat: add amazing feature"Commit Message Format:
feat:New featurefix:Bug fixdocs:Documentationstyle:Formattingrefactor:Code restructuringtest:Adding testschore:Maintenance
-
Push and Create PR
git push origin feature/amazing-feature
- TypeScript/JavaScript: Follow ESLint rules
- React: Use functional components with hooks
- Naming: camelCase for variables, PascalCase for components
- Comments: Document complex logic
- Tests: Minimum 80% coverage for new code
- Provide clear description of changes
- Reference related issues
- Include screenshots for UI changes
- Ensure all tests pass
- Update documentation as needed
This project is licensed under the MIT License.
MIT License
Copyright (c) 2024 LifeDoc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IMPORTANT: This application is for informational purposes only.
- LifeDoc is NOT a replacement for professional medical advice, diagnosis, or treatment
- Always consult qualified healthcare professionals for medical concerns
- AI-generated health insights are suggestions only, not medical diagnoses
- In case of emergency, contact local emergency services immediately (911 in US, 112 in EU, 108 in India)
- The developers assume no liability for health decisions made based on this app
- Google Gemini AI for powering intelligent health analysis
- OpenAI for Vision API document processing
- OpenFDA for comprehensive drug information database
- Cloudinary for secure media hosting and CDN
- MongoDB Atlas for reliable cloud database hosting
- Vercel for seamless frontend deployment
- Open Source Community for amazing libraries and tools
- Healthcare Professionals who provided valuable feedback
- GitHub Issues: Report Bug or Request Feature
- GitHub Discussions: Community Forum
- Email: support@lifedoc.app
- Twitter: @LifeDocApp
- Documentation: Full API Docs
Made with ❤️ for healthier families worldwide
⭐ Star this repo if you found it helpful! ⭐
View Demo • Read Docs • Join Community
Hack The Winter: The Second Wave (Angry Bird Edition)
Track: Health & Wellness | Team Name: TechBytes