from fastapi import FastAPI, HTTPException, Body from pydantic import BaseModel import hashlib import asyncpg from datetime import datetime # PostgreSQL connection setup DB_URL = "postgresql://brain_tumor_qhzg_user:denneCiODQcljrmEBjUFfIOWXaOsTtuu@dpg-d0apaopr0fns73cp87s0-a.oregon-postgres.render.com/brain_tumor_qhzg" app = FastAPI() # Hash password for storage def hash_password(password: str) -> str: return hashlib.sha256(password.encode()).hexdigest() # Function to connect to the PostgreSQL database using asyncpg async def get_db_connection(): conn = await asyncpg.connect(DB_URL) return conn # Pydantic models for user data class UserRegistration(BaseModel): email: str username: str password: str phone: str dob: str # Date of birth in the format YYYY-MM-DD class UserLogin(BaseModel): email: str password: str @app.post("/register") async def register_user(user: UserRegistration): try: # Parse date of birth dob = datetime.strptime(user.dob, "%Y-%m-%d") password_hash = hash_password(user.password) conn = await get_db_connection() existing_user = await conn.fetchrow("SELECT * FROM users WHERE email = $1", user.email) if existing_user: await conn.close() raise HTTPException(status_code=400, detail="Email already registered.") # Insert new user into the database await conn.execute( "INSERT INTO users (email, username, password_hash, phone, dob) VALUES ($1, $2, $3, $4, $5)", user.email, user.username, password_hash, user.phone, dob ) await conn.close() return {"message": "Registration successful!"} except Exception as e: raise HTTPException(status_code=500, detail=f"Error: {str(e)}") @app.post("/login") async def login_user(user: UserLogin): try: conn = await get_db_connection() user_data = await conn.fetchrow("SELECT * FROM users WHERE email = $1", user.email) if user_data and user_data['password_hash'] == hash_password(user.password): await conn.close() return {"message": "Login successful!"} else: await conn.close() raise HTTPException(status_code=400, detail="Invalid email or password.") except Exception as e: raise HTTPException(status_code=500, detail=f"Error: {str(e)}") @app.post("/update_user") async def update_user(user: UserRegistration): try: conn = await get_db_connection() # Update user data await conn.execute( "UPDATE users SET username = $1, phone = $2, dob = $3 WHERE email = $4", user.username, user.phone, user.dob, user.email ) await conn.close() return {"message": "User updated successfully!"} except Exception as e: raise HTTPException(status_code=500, detail=f"Error: {str(e)}")