File size: 2,933 Bytes
452b7a7
 
 
 
 
 
 
17f3c12
452b7a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)}")