Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/workflows/audit-checks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
name: Audit repair checks
on: [push, pull_request]
permissions:
contents: read
jobs:
offline-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: pip install -r requirements-test.txt
- run: pytest -q
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

.env
.env.*
!.env.example
__pycache__/
*.pyc
17 changes: 17 additions & 0 deletions AUDIT_FIXES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Server-side access controls

Repair branch: `fix/internship-audit-20261010`. Changes are scoped to audit findings; no deployment or live provider action is included.

## Changed

Added server-issued JWT sessions, bcrypt account verification, doctor/nurse roles and patient-to-record binding. Browser-supplied roles/password constants no longer authorize access. Patient reads are scoped to the configured identity, and clinical writes/audits require the appropriate role. Groq calls are awaited; missing configuration does not create a fabricated successful report. Tracked environment and bytecode files were removed and safe environment examples added.

## Verification

`pytest -q; cd frontend && npm ci && npm run build`

Commands are entry points, not a claim that every live integration was executed. See the repair bundle for actual results.

## Setup and remaining evidence

Backend: copy backend/.env.example into backend/.env; use CAREFLOW_JWT_SECRET with 32+ random characters and CAREFLOW_USERS_JSON containing username, password_hash, role and patient_id for patient accounts. Generate bcrypt hashes offline (never store plaintext passwords). Start backend from its directory with uvicorn main:app; the active frontend is frontend/, not the historical backend/frontend scaffold. Frontend uses NEXT_PUBLIC_API_URL. Seed patients only with SEED_SYNTHETIC_PATIENTS=true. Previously committed credentials remain in Git history: rotate them before reuse. Real Mongo/provider integration, clinical output validation and medical accuracy remain unverified. This is a synthetic-data prototype, not a validated clinical system.
Binary file modified README.md
Binary file not shown.
9 changes: 0 additions & 9 deletions backend/.env

This file was deleted.

8 changes: 8 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
MONGO_URL=mongodb://localhost:27017
GROQ_API_KEY=
# Generate a unique secret; do not use this file's comments as credentials.
CAREFLOW_JWT_SECRET=
# JSON array of username, bcrypt password_hash, role and optional bound patient_id.
CAREFLOW_USERS_JSON=[]
FRONTEND_ORIGIN=http://localhost:3000
SEED_SYNTHETIC_PATIENTS=false
Binary file removed backend/__pycache__/ai_service.cpython-314.pyc
Binary file not shown.
Binary file removed backend/__pycache__/main.cpython-314.pyc
Binary file not shown.
76 changes: 76 additions & 0 deletions backend/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Server-verified accounts for this single-instance synthetic-data demo."""
import json
import os
from datetime import datetime, timedelta, timezone
from typing import Literal

import bcrypt
import jwt
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field

bearer = HTTPBearer()


class Account(BaseModel):
username: str
password_hash: str
role: Literal["doctor", "nurse", "patient"]
patient_id: str | None = None


class LoginRequest(BaseModel):
username: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=1, max_length=72)


def signing_key():
value = os.getenv("CAREFLOW_JWT_SECRET", "")
if len(value) < 32:
raise HTTPException(503, "Authentication has not been configured")
return value


def accounts():
try:
result = {row.username: row for row in (Account.model_validate(item) for item in json.loads(os.getenv("CAREFLOW_USERS_JSON", "[]")))}
except (ValueError, TypeError):
raise HTTPException(503, "Authentication configuration is invalid")
if any(row.role == "patient" and not row.patient_id for row in result.values()):
raise HTTPException(503, "Patient accounts require a patient_id binding")
return result


def login(payload: LoginRequest):
key = signing_key()
account = accounts().get(payload.username)
try:
valid = account is not None and bcrypt.checkpw(payload.password.encode(), account.password_hash.encode())
except ValueError:
valid = False
if not valid:
raise HTTPException(401, "Invalid credentials")
token = jwt.encode({"sub": account.username, "exp": datetime.now(timezone.utc) + timedelta(hours=1)}, key, algorithm="HS256")
return {"access_token": token, "role": account.role, "patient_id": account.patient_id}


def current_account(credentials: HTTPAuthorizationCredentials = Depends(bearer)):
try:
claims = jwt.decode(credentials.credentials, signing_key(), algorithms=["HS256"], options={"require": ["exp", "sub"]})
except jwt.InvalidTokenError:
raise HTTPException(401, "Invalid or expired session")
account = accounts().get(claims["sub"])
if account is None:
raise HTTPException(401, "Account no longer active")
return account


def require_role(account, *roles):
if account.role not in roles:
raise HTTPException(403, "Access denied for this role")


def require_patient_access(account, patient_id):
if account.role == "patient" and account.patient_id != patient_id:
raise HTTPException(403, "Access denied to this patient")
58 changes: 38 additions & 20 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@
import json
from datetime import datetime
from typing import List
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
from motor.motor_asyncio import AsyncIOMotorClient
from bson import ObjectId
from groq import Groq
from groq import AsyncGroq
from faker import Faker

# 1. Setup & Environment
load_dotenv()
from auth import Account, LoginRequest, current_account, login, require_role, require_patient_access
app = FastAPI()
fake = Faker()

# CORS logic - Taaki frontend connect ho sake
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_origins=[os.getenv("FRONTEND_ORIGIN", "http://localhost:3000")],
allow_methods=["*"],
allow_headers=["*"],
)
Expand All @@ -32,7 +33,7 @@
db = client.careflow
tasks_collection = db.get_collection("tasks")
patients_collection = db.get_collection("patients")
groq_client = Groq(api_key=GROQ_API_KEY)
groq_client = AsyncGroq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None

# 2. Models
class AnalysisRequest(BaseModel):
Expand All @@ -57,18 +58,26 @@ async def seed_patients():

@app.on_event("startup")
async def startup_event():
await seed_patients()
if os.getenv("SEED_SYNTHETIC_PATIENTS", "false").lower() == "true":
await seed_patients()

@app.post("/api/auth/login")
def authenticate(request: LoginRequest):
return login(request)

# 4. API ENDPOINTS (Step 2)

# A. Get All Patients (Real Database se)
@app.get("/api/patients")
async def get_patients():
async def get_patients(account: Account = Depends(current_account)):
patients = []
cursor = patients_collection.find({}).limit(50)
query = {"$or": [{"id": account.patient_id}]} if account.role == "patient" else {}
if account.role == "patient" and ObjectId.is_valid(account.patient_id):
query["$or"].append({"_id": ObjectId(account.patient_id)})
cursor = patients_collection.find(query).limit(50)
async for doc in cursor:
patients.append({
"id": str(doc["_id"]), # MongoDB ID ko string banana zaroori hai
"id": doc.get("id") or str(doc["_id"]), # MongoDB ID ko string banana zaroori hai
"name": doc["name"],
"status": doc["status"],
"diagnosis": doc["diagnosis"],
Expand All @@ -78,7 +87,8 @@ async def get_patients():

# B. Get Tasks for Specific Patient
@app.get("/api/tasks/{patient_id}")
async def get_tasks(patient_id: str):
async def get_tasks(patient_id: str, account: Account = Depends(current_account)):
require_patient_access(account, patient_id)
tasks = []
cursor = tasks_collection.find({"patient_id": patient_id}).sort("created_at", -1)
async for doc in cursor:
Expand Down Expand Up @@ -119,7 +129,10 @@ async def get_tasks(patient_id: str):


@app.post("/api/analyze/{patient_id}")
async def analyze(patient_id: str, request: AnalysisRequest):
async def analyze(patient_id: str, request: AnalysisRequest, account: Account = Depends(current_account)):
require_role(account, "doctor")
if groq_client is None:
raise HTTPException(503, "AI provider is not configured")
try:
# Prompt ko aur strict kar diya taaki AI faltu bakwas na kare
#prompt = f"Return ONLY a JSON object with a key 'tasks' containing a list of objects. Each object must have 'task' and 'category'. Note: {request.note}"
Expand All @@ -136,15 +149,14 @@ async def analyze(patient_id: str, request: AnalysisRequest):
The JSON must be complete.
Format strictly as JSON: {{"tasks": [{{"task": "Exact text from note", "category": "Medication/Test/Vital"}}]}}
Doctor's Note: {request.note} """
completion = groq_client.chat.completion = groq_client.chat.completions.create(
completion = await groq_client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama-3.1-8b-instant",
response_format={"type": "json_object"},
temperature=0.1, # Taaki AI faltu ki baatein na kare, strictly logic par rahe
max_tokens=3072 # Taaki lamba list hone par bhi response pura aaye
)
raw_content = completion.choices[0].message.content
print(f"🤖 AI Response: {raw_content}") # Terminal mein check karo ye kya aa raha hai

res = json.loads(raw_content)

Expand All @@ -168,12 +180,14 @@ async def analyze(patient_id: str, request: AnalysisRequest):
return {"status": "no tasks found"}

except Exception as e:
print(f"❌ ERROR: {str(e)}") # Ye terminal mein asli error dikhayega
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail="Request failed")

# D. Toggle Task Status
@app.patch("/api/tasks/{task_id}")
async def toggle_task(task_id: str):
async def toggle_task(task_id: str, account: Account = Depends(current_account)):
require_role(account, "nurse")
if not ObjectId.is_valid(task_id):
raise HTTPException(422, "Invalid task ID")
task = await tasks_collection.find_one({"_id": ObjectId(task_id)})
if not task:
raise HTTPException(status_code=404, detail="Task not found")
Expand All @@ -192,20 +206,25 @@ async def toggle_task(task_id: str):
import uuid

@app.post("/api/patients")
async def register_patient(patient: dict):
async def register_patient(patient: dict, account: Account = Depends(current_account)):
require_role(account, "doctor")
try:
# Unique ID aur default Ward assign karna
patient["id"] = str(uuid.uuid4())[:8].upper() # Short Unique ID e.g. CF72A1
if "ward_id" not in patient:
patient["ward_id"] = "WARD-01"

await patients_collection.insert_one(patient)
patient.pop("_id", None)
return {"status": "success", "patient": patient}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail="Request failed")

@app.post("/api/agent-audit/{patient_id}")
async def agent_audit(patient_id: str, request: AnalysisRequest):
async def agent_audit(patient_id: str, request: AnalysisRequest, account: Account = Depends(current_account)):
require_role(account, "doctor")
if groq_client is None:
raise HTTPException(503, "AI provider is not configured")
try:
# 1. Alag Prompt jo sirf 3 points nikalega
audit_prompt = f"""
Expand All @@ -219,7 +238,7 @@ async def agent_audit(patient_id: str, request: AnalysisRequest):
"""

# 2. Groq Call (Alag variable names ke saath taaki purana code na phate)
audit_completion = groq_client.chat.completions.create(
audit_completion = await groq_client.chat.completions.create(
messages=[{"role": "user", "content": audit_prompt}],
model="llama-3.1-8b-instant",
response_format={"type": "json_object"},
Expand All @@ -230,7 +249,6 @@ async def agent_audit(patient_id: str, request: AnalysisRequest):
return audit_data

except Exception as e:
print(f"Audit Error: {e}")
raise HTTPException(status_code=500, detail="Audit failed")

if __name__ == "__main__":
Expand Down
3 changes: 3 additions & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,6 @@ uvicorn==0.42.0
Werkzeug==3.1.3
wheel==0.45.1
yt-dlp==2026.3.3

PyJWT>=2.9,<3
bcrypt>=4,<6
15 changes: 6 additions & 9 deletions frontend/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@
// <div className="flex h-screen bg-[#F8FAFC] overflow-hidden font-sans antialiased text-slate-900">

// {/* 1. Sidebar Component (Self-contained data fetching) */}
// <PatientSidebar onSelectPatient={(p: any) => setSelectedPatient(p)} />
// <PatientSidebar key={isAuthenticated ? role : "unauthenticated"} onSelectPatient={(p: any) => setSelectedPatient(p)} />

// {/* 2. Main Workspace */}
// <main className="flex-1 flex flex-col p-8 overflow-y-auto bg-slate-50/50">
Expand Down Expand Up @@ -839,6 +839,7 @@ import {
Calendar, Clock, ClipboardList, User, FileText
} from "lucide-react";
import AuthOverlay from '@/components/AuthOverlay';
import { generateAudit } from '@/lib/api';
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
Expand Down Expand Up @@ -901,7 +902,7 @@ export default function Dashboard() {
};

const handleToggleTask = async (taskId: string) => {
if (role === 'doctor') return alert("Only Nurses can update status.");
if (role !== 'nurse') return alert("Only Nurses can update status.");
try {
await toggleTaskStatus(taskId);
fetchLatestTasks();
Expand Down Expand Up @@ -955,12 +956,8 @@ const generateAgenticReport = async () => {
if (!selectedPatient) return;
setIsGeneratingReport(true);
try {
const res = await fetch(`https://careflow-backend-4l8t.onrender.com/api/agent-audit/${selectedPatient.id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ note: "Generate report" })
});
const data = await res.json();
if (!note.trim()) throw new Error("Enter a source note before generating an audit");
const data = await generateAudit(selectedPatient.id, note);

let reportText = "CAREFLOW CLINICAL AUDIT\n";
reportText += "=======================\n\n";
Expand Down Expand Up @@ -1012,7 +1009,7 @@ return (
{/* Yahan Condition dalo: Agar role 'patient' nahi hai tabhi ye dikhao */}
{role !== 'patient' && (
// <div className="w-80 h-full border-r border-slate-200 overflow-y-auto bg-white shrink-0">
<PatientSidebar onSelectPatient={(p: any) => setSelectedPatient(p)} />
<PatientSidebar key={isAuthenticated ? role : "unauthenticated"} onSelectPatient={(p: any) => setSelectedPatient(p)} />


)}
Expand Down
Loading
Loading