Spaces:
Sleeping
Sleeping
File size: 19,271 Bytes
a0abca2 c6dfde3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | import json
import sqlite3
import time
import jwt
from datetime import date, datetime, timedelta, timezone
from enum import Enum
# pyrefly: ignore [missing-import]
from argon2 import PasswordHasher
# pyrefly: ignore [missing-import]
from fastapi import Depends, HTTPException, Request, APIRouter
# pyrefly: ignore [missing-import]
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
# pyrefly: ignore [missing-import]
from pydantic import BaseModel, Field, EmailStr
# pyrefly: ignore [missing-import]
from sqlalchemy import Column, Integer, String, Text, cast, create_engine, select
# pyrefly: ignore [missing-import]
from sqlalchemy.orm import Session, declarative_base, sessionmaker
# pyrefly: ignore [missing-import]
from sqlalchemy.types import TypeDecorator
# Constants
SERVER_ERROR_MESSAGE = "We couldn't handle your request at this time - kindly contact support or try again much later"
import os
# Load the repo-root .env so DATABASE_URL / JWT_SECRET_KEY / API keys are honored
# locally too (in production these come from the real container environment).
# Only fills vars that aren't already set in the real environment. Public name
# (`load_repo_env`) so other backend modules reuse it instead of copy-pasting.
def load_repo_env() -> None:
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env_path = os.path.join(root, ".env")
if not os.path.exists(env_path):
return
try:
with open(env_path, encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, val = line.split("=", 1)
key, val = key.strip(), val.strip().strip('"').strip("'")
if key and val and key not in os.environ:
os.environ[key] = val
except Exception:
pass
load_repo_env()
# SQLite file path — used when DATABASE_URL is unset, and kept defined either way
# because other modules import DB_PATH.
DB_PATH = os.environ.get("DB_PATH")
if not DB_PATH:
DB_PATH = "/content/drive/MyDrive/neonatal/database.db"
if not os.path.exists("/content/drive/MyDrive/neonatal"):
DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "database.db")
# Database URL precedence: DATABASE_URL (production: Neon Postgres) > SQLite file.
DATABASE_URL = os.environ.get("DATABASE_URL")
if DATABASE_URL:
# Normalize the "postgres://"/"postgresql://" forms to the psycopg (v3)
# driver SQLAlchemy expects.
if DATABASE_URL.startswith("postgres://"):
DATABASE_URL = "postgresql+psycopg://" + DATABASE_URL[len("postgres://"):]
elif DATABASE_URL.startswith("postgresql://"):
DATABASE_URL = "postgresql+psycopg://" + DATABASE_URL[len("postgresql://"):]
SQLALCHEMY_DATABASE_URL = DATABASE_URL
else:
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_PATH}"
# JWT Configuration
# JWT_SECRET_KEY signs auth tokens, so it MUST be a strong, private value in
# production. A committed fallback would let anyone forge a token for any uid, so
# there is none: in production a missing key is a hard boot failure, and in
# development we mint a random per-process key (tokens simply don't survive a
# restart — acceptable locally, never a shared secret).
#
# "Production" is inferred from an explicit APP_ENV/ENVIRONMENT flag or from the
# presence of DATABASE_URL (the managed Postgres only exists in deployed envs).
def _is_production() -> bool:
env = (os.environ.get("APP_ENV") or os.environ.get("ENVIRONMENT") or "").strip().lower()
if env in ("production", "prod", "staging"):
return True
if env in ("development", "dev", "local", "test"):
return False
# No explicit flag: treat a configured managed database as production.
return bool(os.environ.get("DATABASE_URL"))
def _resolve_secret_key() -> str:
key = os.environ.get("JWT_SECRET_KEY")
if key:
return key
if _is_production():
raise RuntimeError(
"JWT_SECRET_KEY is not set. Refusing to start in production with an "
"insecure signing key — set JWT_SECRET_KEY (Space secret / container env)."
)
# Development: use a machine-local, gitignored key file. It is generated once
# and reused, so it is stable across restarts (a fresh random key every boot
# would invalidate every issued token and silently log the developer out).
# It is never committed and never used in production.
import secrets
key_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".dev_jwt_secret")
try:
if os.path.exists(key_path):
existing = open(key_path, encoding="utf-8").read().strip()
if existing:
return existing
generated = secrets.token_urlsafe(64)
with open(key_path, "w", encoding="utf-8") as fh:
fh.write(generated)
print(
"[shared] No JWT_SECRET_KEY set; generated a local dev key at "
"backend/.dev_jwt_secret (gitignored, stable across restarts). "
"Set JWT_SECRET_KEY to override."
)
return generated
except OSError:
# Read-only filesystem etc. — fall back to an ephemeral key (tokens won't
# survive a restart, but the server still boots).
print(
"[shared] WARNING: could not persist a dev JWT key; using an ephemeral "
"one. Set JWT_SECRET_KEY for stable sessions."
)
return secrets.token_urlsafe(64)
SECRET_KEY = _resolve_secret_key()
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7
# Database Setup
if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
else:
# Neon (and managed Postgres generally) drop idle connections; pre-ping
# discards a dead connection instead of handing it out from the pool.
engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Columns below were defined as String but receive bools/ints (and epoch-int
# dates) at write time. SQLite coerces these silently; Postgres rejects them.
# CoercedString restores the loose behavior by stringifying on write — bools as
# "1"/"0" to match how SQLite previously stored them.
class CoercedString(TypeDecorator):
impl = String
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
return None
if isinstance(value, bool):
return "1" if value else "0"
if isinstance(value, Enum):
# Store the underlying value ("high"), not str(member) which renders
# as "EnergyLevel.high" for a (str, Enum). Native sqlite persisted the
# value (str subclass); explicit str() here would otherwise corrupt
# every enum column (energy, flow_intensity, urine_protein, …).
return str(value.value)
return str(value)
# All model String columns below use the coercing variant.
String = CoercedString
# Models
class UserTable(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(255), nullable=False)
email = Column(String(255), nullable=False)
password = Column(String(255), nullable=False)
class PatientInfoTable(Base):
__tablename__ = "patient_info"
id = Column(Integer, primary_key=True, autoincrement=True)
uid = Column(String(50), nullable=False)
stage = Column(String(255), nullable=False)
due_date = Column(String(100), nullable=False)
baby_dob = Column(String(100), nullable=False)
invite_code = Column(String(100), nullable=False)
partner_stage = Column(String(255), nullable=False)
partner_due_date = Column(String(100), nullable=False)
partner_baby_dob = Column(String(100), nullable=False)
emergency_contacts = Column(Text, nullable=False)
goals = Column(Text, nullable=False)
sub_goals = Column(Text, nullable=False)
birth_intention = Column(String(255), nullable=False)
feeding_intention = Column(String(255), nullable=False)
personal_intentions = Column(Text, nullable=False)
ttc_start_date = Column(String(100), nullable=False)
known_conditions = Column(Text, nullable=False)
irregular_cycles = Column(String(100), nullable=False)
# Doctor / visit profile fields. Added after the table first shipped, so an
# existing DB needs run_migrations() (below) to ALTER them in; fresh DBs get
# them from create_all(). Defaults keep them populated for old rows/inserts.
doctor_name = Column(String(255), nullable=False, default="", server_default="")
doctor_phone = Column(String(100), nullable=False, default="", server_default="")
last_visit_date = Column(String(100), nullable=False, default="", server_default="")
next_appointment_date = Column(String(100), nullable=False, default="", server_default="")
visit_prep_questions = Column(Text, nullable=False, default="[]", server_default="[]")
class CycleLogTable(Base):
__tablename__ = "cycle_logs"
id = Column(Integer, primary_key=True, autoincrement=True)
uid = Column(String(50), nullable=False)
date_key = Column(String(100), nullable=False)
is_period_start = Column(String(100), nullable=False)
is_period_flow = Column(String(100), nullable=False)
flow_intensity = Column(String(100), nullable=False)
bbt_temp = Column(String(100), nullable=False)
cm_type = Column(String(100), nullable=False)
# OPK and HPT results can be string versions of Enums
opk_result = Column(String(100), nullable=False)
hpt_result = Column(String(100), nullable=False)
had_sex = Column(String(100), nullable=False)
used_protection = Column(String(100), nullable=False)
mood = Column(Text, nullable=False)
symptoms = Column(Text, nullable=False)
notes = Column(Text, nullable=False)
class ANCVisitsTable(Base):
__tablename__ = "anc_visits"
id = Column(Integer, primary_key=True, autoincrement=True)
uid = Column(String(50), nullable=False)
visit_date = Column(String(100), nullable=False)
gestational_week = Column(String(100), nullable=False)
weight = Column(String(100), nullable=False)
blood_pressure_sys = Column(String(100), nullable=False)
blood_pressure_dia = Column(String(100), nullable=False)
fundal_height = Column(String(100), nullable=False)
baby_heart_rate = Column(String(100), nullable=False)
urine_protein = Column(String(100), nullable=False)
urine_glucose = Column(String(100), nullable=False)
pcv = Column(String(100), nullable=False)
malaria_test = Column(String(100), nullable=False)
blood_group = Column(String(100), nullable=False)
hiv_status = Column(String(100), nullable=False)
hbs_ag = Column(String(100), nullable=False)
vdrl = Column(String(100), nullable=False)
genotype = Column(String(100), nullable=False)
class_topics = Column(Text, nullable=False)
prescriptions = Column(Text, nullable=False)
concern_flagged = Column(String(100), nullable=False)
referred_to_doctor = Column(String(100), nullable=False)
next_appointment_date = Column(String(100), nullable=False)
notes = Column(Text, nullable=False)
added_at = Column(String(100), nullable=False)
class DailyLogTable(Base):
__tablename__ = "daily_logs"
id = Column(Integer, primary_key=True, autoincrement=True)
uid = Column(String(50), nullable=False)
date_key = Column(String(100), nullable=False)
last_updated = Column(String(100), nullable=False)
stage = Column(String(100), nullable=False)
mood = Column(String(100), nullable=False)
energy = Column(String(100), nullable=False)
symptoms = Column(Text, nullable=False)
symptom_severity = Column(String(100), nullable=False)
medications = Column(Text, nullable=False)
sleep_hours = Column(String(100), nullable=False)
sleep_quality = Column(String(100), nullable=False)
kick_count = Column(String(100), nullable=False)
baby_feedings = Column(String(100), nullable=False)
baby_nappies = Column(String(100), nullable=False)
baby_sleep_hours = Column(String(100), nullable=False)
baby_mood = Column(String(100), nullable=False)
baby_symptoms = Column(Text, nullable=False)
baby_symptom_severity = Column(String(100), nullable=False)
water_glasses = Column(String(100), nullable=False)
notes = Column(Text, nullable=False)
created_at = Column(String(100), nullable=False)
updated_at = Column(String(100), nullable=False)
# Shared Enums and Schemas
class PregnancyStage(str, Enum):
ttc = "ttc"
pregnancy = "pregnancy"
newmom = "newmom"
partner = "partner"
class PartnerStage(str, Enum):
ttc = "ttc"
pregnancy = "pregnancy"
newmom = "newmom"
class BirthIntentions(str, Enum):
natural = "natural"
caesarean = "caesarean"
undecided = "undecided"
class FeedingIntentions(str, Enum):
breast = "breast"
formula = "formula"
undecided = "undecided"
class EmergencyContact(BaseModel):
name: str
phone: str
relation: str
id: str
# Helper Functions
pass_hash = PasswordHasher()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Columns added to patient_info after it first shipped. Each entry is the
# portable DDL for an additive ALTER (valid on both SQLite and Postgres). Kept
# next to run_migrations() so the two stay in sync with the model above.
_PATIENT_INFO_ADDED_COLUMNS = [
("doctor_name", "VARCHAR(255) NOT NULL DEFAULT ''"),
("doctor_phone", "VARCHAR(100) NOT NULL DEFAULT ''"),
("last_visit_date", "VARCHAR(100) NOT NULL DEFAULT ''"),
("next_appointment_date", "VARCHAR(100) NOT NULL DEFAULT ''"),
("visit_prep_questions", "TEXT NOT NULL DEFAULT '[]'"),
]
def run_migrations() -> None:
"""Additive, idempotent schema migrations.
Base.metadata.create_all() creates missing TABLES but never adds COLUMNS to
a table that already exists, so columns introduced after a table was first
created must be added by hand. This adds any patient_info columns the model
declares but the live table is missing. Safe to run on every boot and on
both SQLite and Postgres (no Alembic dependency).
"""
from sqlalchemy import inspect as sa_inspect, text
inspector = sa_inspect(engine)
if "patient_info" not in inspector.get_table_names():
return # fresh DB: create_all already built it with every column
existing = {c["name"] for c in inspector.get_columns("patient_info")}
missing = [(n, ddl) for n, ddl in _PATIENT_INFO_ADDED_COLUMNS if n not in existing]
if not missing:
return
with engine.begin() as conn:
for name, ddl in missing:
conn.execute(text(f"ALTER TABLE patient_info ADD COLUMN {name} {ddl}"))
def dateToEpoch(d: date | None):
if d is None:
return ""
return int(time.mktime(d.timetuple()))
def createAccessToken(data: dict):
to_encode = data.copy()
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def verifyPassword(saved_hash: str, test_pass: str):
try:
return pass_hash.verify(saved_hash, test_pass)
except:
return False
def formatReturnedUserData(data: dict):
ret_data = {}
date_cols = ["due_date", "baby_dob", "partner_due_date", "partner_baby_dob", "ttc_start_date",
"last_visit_date", "next_appointment_date"]
ignore = ["id"]
json_columns = ["emergency_contacts", "goals", "sub_goals", "known_conditions", "personal_intentions",
"visit_prep_questions"]
for key, val in data.items():
if key in date_cols:
# Unset dates are stored as "" (see dateToEpoch); keep them null
# instead of crashing on float("").
if val is None or val == "":
ret_data.update({key: None})
else:
# Return ISO YYYY-MM-DD — the format the client (and API_SPEC)
# expects. A human-readable string like "1 September 2026" can't
# be parsed back by the app, so dueDate/babyDOB/ttcStartDate were
# silently dropped on login (after logout clears the local cache),
# blanking the profile and the dashboard content derived from them.
dt = datetime.fromtimestamp(float(val))
ret_data.update({key: dt.strftime("%Y-%m-%d")})
elif key in json_columns:
ret_data.update({key: json.loads(val) if val else []})
elif key not in ignore:
ret_data.update({key: val})
return ret_data
# Auth Dependency
security_scheme = HTTPBearer()
async def checkUserValidity(request: Request, db: Session = Depends(get_db), token: HTTPAuthorizationCredentials = Depends(security_scheme)):
jwt_cred = token.credentials
try:
payload = jwt.decode(jwt_cred, SECRET_KEY, algorithms=[ALGORITHM])
uid = payload.get("sub")
if uid and uid.strip().isdigit():
patient_cols = [
col for col in PatientInfoTable.__table__.columns
if col.name != "id"
]
# users.id is Integer but patient_info.uid is a String holding the
# same value; Postgres won't compare the two without an explicit cast
# (SQLite does it implicitly).
stm = select(
UserTable.id, UserTable.email, UserTable.name, *patient_cols
).join(
PatientInfoTable, UserTable.id == cast(PatientInfoTable.uid, Integer)
).where(UserTable.id == int(uid))
res = db.execute(stm).first()
if res:
user_data = formatReturnedUserData(res._asdict())
return {
"status": "success",
"data": user_data
}
else:
return {"status": "error"}
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token has expired")
except jwt.PyJWTError:
raise HTTPException(status_code=401, detail="Could not validate credentials")
return {"status": "error"}
auth_router= APIRouter(prefix= "/auth", tags= ["Authentication"])
user_router= APIRouter(
prefix= "/user",
tags= ["Users"],
dependencies= [Depends(checkUserValidity)]
) |