icybluelemon/User_authentication
0
1from fastapi import FastAPI, HTTPException, Body2from pydantic import BaseModel3import hashlib4import asyncpg5from datetime import datetime6 7# PostgreSQL connection setup8#DB_URL = "postgresql://new_hor:R99oQ4CtlfuYx6gBepBfxC78EnRAjuFB@dpg-cudg8a2j1k6c73cnc310-a.oregon-postgres.render.com/user_db_ron3?sslmode=require"9DB_URL="postgresql://brain_tumor_user:kseDs5BA3SLoZNbW4xjuTMbElUjBB3UV@dpg-cudknml6l47c73af4r40-a.oregon-postgres.render.com/brain_tumor_lywa"10 11app = FastAPI()12 13# Hash password for storage14def hash_password(password: str) -> str:15 return hashlib.sha256(password.encode()).hexdigest()16 17# Function to connect to the PostgreSQL database using asyncpg18async def get_db_connection():19 conn = await asyncpg.connect(DB_URL)20 return conn21 22# Pydantic models for user data23class UserRegistration(BaseModel):24 email: str25 username: str26 password: str27 phone: str28 dob: str # Date of birth in the format YYYY-MM-DD29 30class UserLogin(BaseModel):31 email: str32 password: str33 34@app.post("/register")35async def register_user(user: UserRegistration):36 try:37 # Parse date of birth38 dob = datetime.strptime(user.dob, "%Y-%m-%d")39 password_hash = hash_password(user.password)40 41 conn = await get_db_connection()42 existing_user = await conn.fetchrow("SELECT * FROM users WHERE email = $1", user.email)43 44 if existing_user:45 await conn.close()46 raise HTTPException(status_code=400, detail="Email already registered.")47 48 # Insert new user into the database49 await conn.execute(50 "INSERT INTO users (email, username, password_hash, phone, dob) VALUES ($1, $2, $3, $4, $5)",51 user.email, user.username, password_hash, user.phone, dob52 )53 54 await conn.close()55 return {"message": "Registration successful!"}56 57 except Exception as e:58 raise HTTPException(status_code=500, detail=f"Error: {str(e)}")59 60@app.post("/login")61async def login_user(user: UserLogin):62 try:63 conn = await get_db_connection()64 user_data = await conn.fetchrow("SELECT * FROM users WHERE email = $1", user.email)65 66 if user_data and user_data['password_hash'] == hash_password(user.password):67 await conn.close()68 return {"message": "Login successful!"}69 else:70 await conn.close()71 raise HTTPException(status_code=400, detail="Invalid email or password.")72 73 except Exception as e:74 raise HTTPException(status_code=500, detail=f"Error: {str(e)}")75 76@app.post("/update_user")77async def update_user(user: UserRegistration):78 try:79 conn = await get_db_connection()80 81 # Update user data82 await conn.execute(83 "UPDATE users SET username = $1, phone = $2, dob = $3 WHERE email = $4",84 user.username, user.phone, str(user.dob), user.email85 )86 87 await conn.close()88 return {"message": "User updated successfully!"}89 90 except Exception as e:91 raise HTTPException(status_code=500, detail=f"Error: {str(e)}")92 93 