Sportans / main.py
krrishsinha's picture
addme
d65dc51
from fastapi import FastAPI, HTTPException
from passlib.hash import sha256_crypt
from database import get_db
from schemas import RegisterRequest, LoginRequest, UserResponse
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(title="Sportans API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # tighten later
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/auth/register")
def register(data: RegisterRequest):
db = get_db()
cursor = db.cursor()
cursor.execute("SELECT id FROM users WHERE email = %s", (data.email,))
if cursor.fetchone():
raise HTTPException(status_code=400, detail="User already exists")
hashed_password = sha256_crypt.hash(data.password)
cursor.execute(
"INSERT INTO users (name, email, password, role) VALUES (%s, %s, %s, %s)",
(data.name, data.email, hashed_password, data.role)
)
db.commit()
user_id = cursor.lastrowid
if data.role == "player":
cursor.execute(
"INSERT INTO players (name, contact_email) VALUES (%s, %s)",
(data.name, data.email)
)
db.commit()
cursor.close()
db.close()
return {
"message": "Registration successful",
"user_id": user_id,
"role": data.role
}
@app.post("/auth/login", response_model=UserResponse)
def login(data: LoginRequest):
db = get_db()
cursor = db.cursor()
cursor.execute(
"SELECT id, name, email, password, role FROM users WHERE email = %s",
(data.email,)
)
user = cursor.fetchone()
if not user:
raise HTTPException(status_code=404, detail="User not found")
if not sha256_crypt.verify(data.password, user[3]):
raise HTTPException(status_code=401, detail="Invalid credentials")
cursor.close()
db.close()
return {
"id": user[0],
"name": user[1],
"email": user[2],
"role": user[4]
}