dth-pingpong-backend/main.py

91 lines
3 KiB
Python
Raw Normal View History

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from calls import register_user, authenticate_user, reauth_user, add_friend, send_match_invite, accept_match_invite, get_all_matches, get_elo, update_elo
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace "*" with your allowed origins
allow_credentials=True,
allow_methods=["*"], # Allow all HTTP methods
allow_headers=["*"], # Allow all HTTP headers
)
class RegisterRequest(BaseModel):
email: str
display_name: str
password: str
class LoginRequest(BaseModel):
email: str
password: str
class FriendRequest(BaseModel):
user_uid: int
friend_uid: int
class MatchInviteRequest(BaseModel):
sender_uid: int
receiver_uid: int
class AcceptInviteRequest(BaseModel):
match_id: int
player2_uid: int
@app.post("/register")
def register(request: RegisterRequest):
try:
uid = register_user(request.email, request.display_name, request.password)
return {"message": "User registered successfully", "uid": uid}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/login")
def login(request: LoginRequest):
sessiontoken = authenticate_user(request.email, request.password)
if sessiontoken:
return {"message": "Login successful", "uid": sessiontoken}
else:
raise HTTPException(status_code=401, detail="Invalid credentials")
@app.post("/add_friend")
def add_friend_endpoint(request: FriendRequest):
try:
success = add_friend(request.user_uid, request.friend_uid)
return {"message": "Friend added successfully"} if success else HTTPException(400, "Failed to add friend")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/send_match_invite")
def send_invite(request: MatchInviteRequest):
try:
match_id = send_match_invite(request.sender_uid, request.receiver_uid)
return {"message": "Match invite sent successfully", "match_id": match_id}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/accept_match_invite")
def accept_invite(request: AcceptInviteRequest):
try:
success = accept_match_invite(request.match_id, request.player2_uid)
return {"message": "Match invite accepted"} if success else HTTPException(400, "Failed to accept invite")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.get("/matches")
def get_matches():
try:
matches = get_all_matches()
return {"matches": matches}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/elo")
def get_elo_endpoint(authorization: str):
print(f"Received Authorization header: {authorization}")
try:
result = get_elo(authorization)
return result
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))