File size: 16,161 Bytes
c6abe34 | 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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | """
Authentication API endpoints.
"""
from datetime import datetime, timedelta
import os
from uuid import uuid4
from pydantic import BaseModel
from fastapi import APIRouter, Depends, HTTPException, Request, status
from slowapi import Limiter
from slowapi.util import get_remote_address
from app.config import get_settings
from app.core.security import (
create_access_token,
create_refresh_token,
get_password_hash,
verify_password,
decode_access_token,
)
from app.dependencies import get_current_user, get_supabase
from app.models.user import (
UserCreate,
UserLogin,
UserUpdate,
User,
TokenResponse,
RefreshTokenRequest,
AccountType,
)
from app.services.supabase_client import SupabaseService
router = APIRouter()
def _get_limiter(request: Request) -> Limiter:
# Helper to get the global limiter attached in app.main
return request.app.state.limiter
@router.post(
"/register",
response_model=TokenResponse,
status_code=status.HTTP_201_CREATED,
)
async def register(
user_data: UserCreate,
supabase: SupabaseService = Depends(get_supabase),
):
"""
Register a new user account.
- **email**: Valid email address
- **password**: Minimum 8 characters
- **account_type**: 'team', 'coach', or 'player'
"""
settings = get_settings()
# Check if user already exists
existing = await supabase.select("users", filters={"email": user_data.email})
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
# Create user
user_id = str(uuid4())
hashed_password = get_password_hash(user_data.password)
user_record = {
"id": user_id,
"email": user_data.email,
"hashed_password": hashed_password,
"account_type": user_data.account_type.value,
"full_name": user_data.full_name,
}
try:
await supabase.insert("users", user_record)
# If team account, check for org or create one?
# Schema says organizations(owner_id).
org_id = None
if user_data.account_type == AccountType.TEAM:
org_id = str(uuid4())
await supabase.insert("organizations", {
"id": org_id,
"name": f"{user_data.full_name or user_id}'s Team",
"owner_id": user_id
})
# Link org back to user record
await supabase.update("users", user_id, {"organization_id": org_id})
except Exception as e:
# Log the detailed error for debugging but return a clear message
print(f"Registration Database Error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Database error during registration: {str(e)}"
)
# Create tokens
token_data = {
"sub": user_id,
"email": user_data.email,
"account_type": user_data.account_type.value,
"organization_id": org_id
}
access_token = create_access_token(token_data)
refresh_token = create_refresh_token(user_id)
user = User(
id=user_id,
email=user_data.email,
account_type=user_data.account_type,
full_name=user_data.full_name,
organization_id=org_id,
created_at=datetime.now()
)
return TokenResponse(
access_token=access_token,
refresh_token=refresh_token,
expires_in=settings.jwt_expiration_minutes * 60,
user=user
)
@router.post("/login", response_model=TokenResponse)
async def login(
request: Request,
credentials: UserLogin,
supabase: SupabaseService = Depends(get_supabase),
):
"""
Authenticate and get access tokens.
"""
settings = get_settings()
# Apply a stricter rate limit on login to protect against brute force.
limiter = _get_limiter(request)
# The decorated function must accept a 'request' argument for slowapi inspection
limiter.limit("60/minute")(lambda request: None)(request)
# Find user
try:
users = await supabase.select("users", filters={"email": credentials.email})
except Exception as e:
print(f"Login Database Error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Database error during login: {str(e)}"
)
if not users:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials"
)
user = users[0]
# Verify password
if not verify_password(credentials.password, user.get("hashed_password", "")):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials"
)
# Fetch organization_id if applicable
org_id = user.get("organization_id")
if not org_id and user["account_type"] == AccountType.TEAM.value:
orgs = await supabase.select("organizations", filters={"owner_id": user["id"]})
if orgs:
org_id = orgs[0]["id"]
elif not org_id and user["account_type"] == AccountType.COACH.value:
# For coaches, we expect organization_id to be set in users table already via linking
pass
# Create tokens
token_data = {
"sub": user["id"],
"email": user["email"],
"account_type": user["account_type"],
"organization_id": org_id
}
access_token = create_access_token(token_data)
refresh_token = create_refresh_token(user["id"])
return TokenResponse(
access_token=access_token,
refresh_token=refresh_token,
expires_in=settings.jwt_expiration_minutes * 60,
user=User(
id=user["id"],
email=user["email"],
account_type=AccountType(user["account_type"]),
full_name=user.get("full_name"),
organization_id=org_id,
created_at=user.get("created_at") or datetime.now()
)
)
@router.post("/refresh", response_model=TokenResponse)
async def refresh_token(
body: RefreshTokenRequest,
supabase: SupabaseService = Depends(get_supabase),
):
"""
Refresh access token using a valid refresh token.
"""
settings = get_settings()
payload = decode_access_token(body.refresh_token)
if not payload or payload.get("type") != "refresh":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid refresh token"
)
user_id = payload.get("sub")
user = await supabase.select_one("users", user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found"
)
token_data = {
"sub": user["id"],
"email": user["email"],
"account_type": user["account_type"],
}
new_access_token = create_access_token(token_data)
new_refresh_token = create_refresh_token(user["id"])
return TokenResponse(
access_token=new_access_token,
refresh_token=new_refresh_token,
expires_in=settings.jwt_expiration_minutes * 60,
)
@router.post("/refresh-token", response_model=TokenResponse)
async def refresh_token_alias(
body: RefreshTokenRequest,
supabase: SupabaseService = Depends(get_supabase),
):
"""
Alias for /refresh to support frontend expectations.
"""
return await refresh_token(body, supabase)
@router.get("/me", response_model=User)
async def get_current_user_profile(
current_user: dict = Depends(get_current_user),
supabase: SupabaseService = Depends(get_supabase),
):
"""
Get the currently authenticated user's profile.
"""
try:
user = await supabase.select_one("users", current_user["id"])
except Exception as e:
print(f"Profile Retrieval Error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Database error while fetching profile: {str(e)}"
)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
# Fetch org info
org_id = user.get("organization_id")
if not org_id and user["account_type"] == AccountType.TEAM.value:
orgs = await supabase.select("organizations", filters={"owner_id": user["id"]})
if orgs:
org_id = orgs[0]["id"]
elif not org_id and user["account_type"] == AccountType.COACH.value:
pass
return User(
id=user["id"],
email=user["email"],
account_type=AccountType(user["account_type"]),
full_name=user.get("full_name"),
avatar_url=user.get("avatar_url"),
organization_id=org_id,
created_at=user.get("created_at"),
updated_at=user.get("updated_at"),
)
@router.put("/me", response_model=User)
async def update_current_user_profile(
update_data: UserUpdate,
current_user: dict = Depends(get_current_user),
supabase: SupabaseService = Depends(get_supabase),
):
"""
Update the currently authenticated user's profile.
"""
update_dict = update_data.model_dump(exclude_unset=True)
if not update_dict:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="No fields to update"
)
updated = await supabase.update("users", current_user["id"], update_dict)
return User(
id=updated["id"],
email=updated["email"],
account_type=AccountType(updated["account_type"]),
full_name=updated.get("full_name"),
avatar_url=updated.get("avatar_url"),
created_at=updated.get("created_at"),
updated_at=updated.get("updated_at"),
)
class MagicLinkCallbackRequest(BaseModel):
supabase_token: str
account_type: str = "player"
@router.post("/magic-link-callback", response_model=TokenResponse)
async def magic_link_callback(
body: MagicLinkCallbackRequest,
supabase: SupabaseService = Depends(get_supabase),
):
"""
Exchange a valid Supabase session token (from a magic link click) for a BakoAI JWT.
Creates a new user record automatically if this is their first sign-in.
"""
settings = get_settings()
# Decode the Supabase JWT to get the user's email & id
# Supabase tokens are standard JWTs - we can decode the payload without verifying
# the signature here since Supabase already validated it before issuing.
try:
import base64, json as _json
parts = body.supabase_token.split(".")
# Add padding if needed
padded = parts[1] + "=" * (4 - len(parts[1]) % 4)
payload = _json.loads(base64.urlsafe_b64decode(padded))
email = payload.get("email")
supabase_uid = payload.get("sub")
if not email or not supabase_uid:
raise ValueError("Missing email or sub in token")
except Exception as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid Supabase token: {str(e)}"
)
# Find or create user in our database
existing = await supabase.select("users", filters={"email": email})
if existing:
user_record = existing[0]
user_id = user_record["id"]
org_id = user_record.get("organization_id")
account_type_val = user_record.get("account_type", "player")
else:
# Auto-create user on first magic link sign-in
user_id = str(uuid4())
account_type_val = body.account_type
org_id = None
user_record = {
"id": user_id,
"email": email,
"hashed_password": "", # No password for magic link users
"account_type": account_type_val,
"full_name": email.split("@")[0].replace(".", " ").title(),
}
try:
await supabase.insert("users", user_record)
if account_type_val == AccountType.TEAM.value:
org_id = str(uuid4())
await supabase.insert("organizations", {
"id": org_id,
"name": f"{user_record['full_name']}'s Team",
"owner_id": user_id,
})
await supabase.update("users", user_id, {"organization_id": org_id})
except Exception as e:
print(f"Magic link auto-create error: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to create user account"
)
# Issue BakoAI tokens
token_data = {
"sub": user_id,
"email": email,
"account_type": account_type_val,
"organization_id": org_id,
}
access_token = create_access_token(token_data)
refresh_token_str = create_refresh_token(user_id)
return TokenResponse(
access_token=access_token,
refresh_token=refresh_token_str,
expires_in=settings.jwt_expiration_minutes * 60,
user=User(
id=user_id,
email=email,
account_type=AccountType(account_type_val),
full_name=user_record.get("full_name"),
organization_id=org_id,
created_at=datetime.now(),
),
)
@router.post("/logout")
async def logout():
"""
Log out the current user.
Since we use stateless JWT, this is primarily for client-side cleanup.
"""
return {"message": "Successfully logged out"}
@router.delete("/account", status_code=status.HTTP_204_NO_CONTENT)
async def delete_current_user_account(
current_user: dict = Depends(get_current_user),
supabase: SupabaseService = Depends(get_supabase),
):
"""
Permanently delete the current user's account and all associated data.
"""
user_id = current_user["id"]
# 1. Cleanup Videos and physical files
# Get all videos uploaded by this user
videos = await supabase.select("videos", filters={"uploader_id": user_id})
for video in videos:
video_id = str(video.get("id"))
storage_path = video.get("storage_path")
# Delete physical file
if storage_path and os.path.exists(storage_path):
try:
os.remove(storage_path)
except Exception as e:
print(f"Error removing file {storage_path}: {e}")
# Also check for annotated video
annotated_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
"output_videos", "annotated", f"{video_id}.mp4"
)
if os.path.exists(annotated_path):
try:
os.remove(annotated_path)
except Exception:
pass
# Cleanup related DB records (best effort)
for table in ["analysis_results", "detections", "analytics", "clips"]:
try:
await supabase.delete_where(table, {"video_id": video_id})
except Exception:
pass
# Delete video record
await supabase.delete("videos", video_id)
# 2. Cleanup Organization if Owner
if current_user.get("account_type") == AccountType.TEAM.value:
orgs = await supabase.select("organizations", filters={"owner_id": user_id})
for org in orgs:
org_id = str(org.get("id"))
# Unlink staff/players or delete them?
# For now, let's just delete the organization.
await supabase.delete("organizations", org_id)
# 3. Delete Profile (from users table)
await supabase.delete("users", user_id)
# 4. Delete from Supabase Auth
success = await supabase.delete_user_auth(user_id)
if not success:
print(f"CRITICAL: Failed to delete user {user_id} from Supabase Auth")
return None
|