Coverage for auth.py: 83.89%

318 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 17:31 +0000

1""" 

2Authentication and authorization utilities for the sports league backend. 

3""" 

4 

5import logging 

6import os 

7import secrets 

8from datetime import UTC, datetime, timedelta 

9from functools import wraps 

10from typing import Any 

11 

12import jwt 

13from dotenv import load_dotenv 

14from fastapi import Depends, HTTPException 

15from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer 

16from jwt import PyJWKClient 

17from supabase import Client 

18 

19load_dotenv() 

20 

21# JWKS client for ES256 token verification (cached) 

22_jwks_client: PyJWKClient | None = None 

23 

24logger = logging.getLogger(__name__) 

25 

26# Canonical role for each invite_type (SB-798). 

27# 

28# This mapping existed in four places and one of them disagreed: the email / 

29# OAuth signup path mapped club_fan -> "club_fan" while the other three mapped 

30# it to "club-fan". Both spellings pass user_profiles_role_check, so nothing 

31# failed — the database simply accumulated the same role under two names 

32# depending on which door a user came through, and every exact-match comparison 

33# downstream then covered only half of them. 

34# 

35# Note the asymmetry is real, not a typo to "fix": club_manager is canonically 

36# the UNDERSCORE form, and "club-manager" is not permitted by the constraint at 

37# all. The others are canonically hyphenated. 

38INVITE_TYPE_TO_ROLE: dict[str, str] = { 

39 "club_manager": "club_manager", 

40 "club_fan": "club-fan", 

41 "team_manager": "team-manager", 

42 "team_player": "team-player", 

43 "team_fan": "team-fan", 

44} 

45 

46# Role assigned when an invite carries no recognisable type. 

47DEFAULT_ROLE = "team-fan" 

48 

49 

50def role_for_invite_type(invite_type: str | None) -> str: 

51 """Canonical role for an invite_type, or the default for anything unknown.""" 

52 return INVITE_TYPE_TO_ROLE.get(invite_type or "", DEFAULT_ROLE) 

53 

54 

55def fan_age_group_for_invite(invite: dict[str, Any]) -> int | None: 

56 """The age group a team-fan invite names, which becomes the fan's "my team" pick 

57 (SB-1543). Every other type: None, so re-signing into another role clears a stale 

58 pick. Managers and players keep age groups in their own tables.""" 

59 return invite.get("age_group_id") if invite.get("invite_type") == "team_fan" else None 

60 

61 

62security = HTTPBearer() 

63 

64# API-only accounts (SB-1145): the token audience accepted on /api/ai/* only, 

65# and how long an admin may mint one for. 

66AI_API_AUDIENCE = "mt-ai-api" 

67# A short-lived token MT mints for one chat turn answered by sb-agents (SB-1529): it lets 

68# mt-agent call mt-mcp as the signed-in user. Only mt-mcp accepts this audience, and caps 

69# it to read/my/self whatever the role (mt_mcp.scopes.DELEGATED_CAP). 

70DELEGATED_AUDIENCE = "mt-mcp-delegated" 

71DELEGATED_TTL_SECONDS = 300 

72AI_API_TOKEN_DEFAULT_DAYS = 7 

73AI_API_TOKEN_MAX_DAYS = 30 

74 

75 

76# ============================================================================ 

77# Username Authentication Helper Functions 

78# ============================================================================ 

79 

80 

81def username_to_internal_email(username: str) -> str: 

82 """ 

83 Convert username to internal email format for Supabase Auth. 

84 

85 Example: gabe_ifa_35 -> gabe_ifa_35@missingtable.local 

86 """ 

87 return f"{username.lower()}@missingtable.local" 

88 

89 

90def internal_email_to_username(email: str) -> str | None: 

91 """ 

92 Extract username from internal email format. 

93 

94 Example: gabe_ifa_35@missingtable.local -> gabe_ifa_35 

95 Returns None if not an internal email. 

96 """ 

97 if email.endswith("@missingtable.local"): 

98 return email.replace("@missingtable.local", "") 

99 return None 

100 

101 

102def is_internal_email(email: str) -> bool: 

103 """Check if email is an internal format.""" 

104 return email.endswith("@missingtable.local") 

105 

106 

107async def check_username_available(supabase_client: Client, username: str) -> bool: 

108 """ 

109 Check if username is available. 

110 

111 Returns True if username is available, False if taken. 

112 """ 

113 try: 

114 result = supabase_client.table("user_profiles").select("id").eq("username", username.lower()).execute() 

115 

116 return len(result.data) == 0 

117 except Exception as e: 

118 logger.error(f"Error checking username availability: {e}") 

119 raise 

120 

121 

122class AuthManager: 

123 def __init__(self, supabase_client: Client): 

124 self.supabase = supabase_client 

125 self.jwt_secret = os.getenv("SUPABASE_JWT_SECRET") 

126 self.service_account_secret = os.getenv("SERVICE_ACCOUNT_SECRET", secrets.token_urlsafe(32)) 

127 

128 if not self.jwt_secret: 

129 raise ValueError("SUPABASE_JWT_SECRET environment variable is required. Please set it in your .env file.") 

130 

131 def verify_token(self, token: str) -> dict[str, Any] | None: 

132 """Verify JWT token and return user data.""" 

133 global _jwks_client 

134 try: 

135 # Check token header to determine algorithm 

136 unverified_header = jwt.get_unverified_header(token) 

137 alg = unverified_header.get("alg", "HS256") 

138 

139 if alg == "ES256": 139 ↛ 141line 139 didn't jump to line 141 because the condition on line 139 was never true

140 # Use JWKS for ES256 tokens (new Supabase CLI) 

141 supabase_url = os.getenv("SUPABASE_URL", "http://127.0.0.1:55321") 

142 jwks_url = f"{supabase_url}/auth/v1/.well-known/jwks.json" 

143 

144 if _jwks_client is None: 

145 _jwks_client = PyJWKClient(jwks_url) 

146 

147 signing_key = _jwks_client.get_signing_key_from_jwt(token) 

148 payload = jwt.decode( 

149 token, 

150 signing_key.key, 

151 algorithms=["ES256"], 

152 audience="authenticated", 

153 ) 

154 else: 

155 # Use symmetric secret for HS256 tokens (legacy/cloud) 

156 payload = jwt.decode( 

157 token, 

158 self.jwt_secret, 

159 algorithms=["HS256"], 

160 audience="authenticated", 

161 ) 

162 

163 user_id = payload.get("sub") 

164 if not user_id: 

165 return None 

166 

167 # Get user profile with role 

168 logger.debug(f"Querying user_profiles for user_id: {user_id}") 

169 profile_response = self.supabase.table("user_profiles").select("*").eq("id", user_id).execute() 

170 

171 if not profile_response.data or len(profile_response.data) == 0: 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true

172 logger.warning(f"No profile found for user {user_id}") 

173 return None 

174 

175 # If multiple profiles exist, take the first one (should be fixed by cleanup script) 

176 profile = profile_response.data[0] 

177 if len(profile_response.data) > 1: 

178 logger.warning(f"Multiple profiles found for user {user_id}, using first one") 

179 

180 # An API account's auth user has no password and is banned, so no 

181 # session token should ever name one (SB-1150). Refuse it anyway: 

182 # their only credential is the /api/ai/* token (SB-1145), and it must 

183 # not become a general-purpose one. 

184 if profile.get("is_api_account"): 

185 logger.warning(f"Session token names API account {user_id}; refused") 

186 return None 

187 

188 # Extract username from profile (primary identifier) 

189 username = profile.get("username") 

190 

191 # Get email from JWT payload (might be internal email format) 

192 jwt_email = payload.get("email") 

193 

194 # Distinguish between internal email (username@missingtable.local) and real email 

195 # Real email is stored in profile.email, internal email is in JWT 

196 if jwt_email and is_internal_email(jwt_email): 

197 # This is an internal email, extract username if not in profile 

198 if not username: 

199 username = internal_email_to_username(jwt_email) 

200 real_email = profile.get("email") # Optional real email from profile 

201 else: 

202 # Legacy user with real email in JWT 

203 real_email = jwt_email 

204 

205 return { 

206 "user_id": user_id, 

207 "username": username, # Primary identifier for username auth users 

208 "email": real_email, # Real email (optional, for notifications) 

209 "role": profile["role"], 

210 "team_id": profile.get("team_id"), 

211 "club_id": profile.get("club_id"), # For club managers 

212 "assigned_age_group_id": profile.get("assigned_age_group_id"), # a fan's pick (SB-1543) 

213 "display_name": profile.get("display_name"), 

214 "is_test": profile.get("is_test", False), # SB-85 test partition 

215 } 

216 

217 except jwt.ExpiredSignatureError: 

218 logger.warning("Token has expired") 

219 return None 

220 except jwt.InvalidTokenError as e: 

221 logger.warning(f"Invalid token: {e}") 

222 return None 

223 except Exception as e: 

224 logger.error(f"Error verifying token: {e}") 

225 return None 

226 

227 def create_service_account_token(self, service_name: str, permissions: list[str], expires_days: int = 365) -> str: 

228 """Create a service account JWT token for automated systems.""" 

229 expiration = datetime.now(UTC) + timedelta(days=expires_days) 

230 

231 payload = { 

232 "sub": f"service-{service_name}", 

233 "iss": "missing-table", 

234 "aud": "service-account", 

235 "exp": int(expiration.timestamp()), 

236 "iat": int(datetime.now(UTC).timestamp()), 

237 "service_name": service_name, 

238 "permissions": permissions, 

239 "role": "service_account", 

240 } 

241 

242 return jwt.encode(payload, self.service_account_secret, algorithm="HS256") 

243 

244 def verify_service_account_token(self, token: str) -> dict[str, Any] | None: 

245 """Verify service account JWT token and return service data.""" 

246 try: 

247 payload = jwt.decode(token, self.service_account_secret, algorithms=["HS256"], audience="service-account") 

248 

249 service_name = payload.get("service_name") 

250 permissions = payload.get("permissions", []) 

251 

252 if not service_name: 

253 return None 

254 

255 return { 

256 "service_id": payload.get("sub"), 

257 "service_name": service_name, 

258 "permissions": permissions, 

259 "role": "service_account", 

260 "is_service_account": True, 

261 } 

262 

263 except jwt.ExpiredSignatureError: 

264 logger.warning("Service account token has expired") 

265 return None 

266 except jwt.InvalidTokenError as e: 

267 logger.warning(f"Invalid service account token: {e}") 

268 return None 

269 except Exception as e: 

270 logger.error(f"Error verifying service account token: {e}") 

271 return None 

272 

273 def create_delegated_token(self, user_id: str, ttl_seconds: int = DELEGATED_TTL_SECONDS) -> str: 

274 """A token for mt-mcp, acting as `user_id`, for one sb-agents chat turn (SB-1529). 

275 

276 The audience confines it: every other endpoint decodes with another audience and 

277 rejects it. Five minutes covers one turn; nothing refreshes it. 

278 """ 

279 now = datetime.now(UTC) 

280 payload = { 

281 "sub": user_id, 

282 "iss": "missing-table", 

283 "aud": DELEGATED_AUDIENCE, 

284 "azp": "sb-agents", 

285 "exp": int((now + timedelta(seconds=ttl_seconds)).timestamp()), 

286 "iat": int(now.timestamp()), 

287 "jti": secrets.token_hex(8), 

288 } 

289 return jwt.encode(payload, self.service_account_secret, algorithm="HS256") 

290 

291 def verify_delegated_token(self, token: str) -> dict[str, Any] | None: 

292 """A delegated token → the person's user data (marked `delegated`), or None. 

293 

294 The profile is re-read, so a deleted user or changed role takes effect at once. 

295 API accounts are refused: delegation is for people. 

296 """ 

297 try: 

298 payload = jwt.decode(token, self.service_account_secret, algorithms=["HS256"], audience=DELEGATED_AUDIENCE) 

299 except jwt.InvalidTokenError: # expired, wrong audience or signature, malformed 

300 return None 

301 user_id = payload.get("sub") 

302 if not user_id: 302 ↛ 303line 302 didn't jump to line 303 because the condition on line 302 was never true

303 return None 

304 try: 

305 response = self.supabase.table("user_profiles").select("*").eq("id", user_id).execute() 

306 except Exception as e: 

307 logger.error(f"Error verifying delegated token: {e}") 

308 return None 

309 profile = response.data[0] if response.data else None 

310 if not profile or profile.get("is_api_account"): 

311 return None 

312 return { 

313 "user_id": user_id, 

314 "username": profile.get("username"), 

315 "email": None, 

316 "role": profile.get("role"), 

317 "team_id": profile.get("team_id"), 

318 "club_id": profile.get("club_id"), 

319 "assigned_age_group_id": profile.get("assigned_age_group_id"), 

320 "display_name": profile.get("display_name"), 

321 "is_test": profile.get("is_test", False), 

322 "is_api_account": False, 

323 "delegated": True, 

324 } 

325 

326 def create_ai_api_token(self, user_id: str, expires_days: int = AI_API_TOKEN_DEFAULT_DAYS) -> str: 

327 """Create a short-lived token for an API-only account, valid on /api/ai/* only (SB-1145). 

328 

329 The audience is what confines it: every other endpoint decodes with 

330 "authenticated" or "service-account" and so rejects this token. 

331 """ 

332 if not 0 < expires_days <= AI_API_TOKEN_MAX_DAYS: 

333 raise ValueError(f"expires_days must be between 1 and {AI_API_TOKEN_MAX_DAYS}") 

334 now = datetime.now(UTC) 

335 payload = { 

336 "sub": user_id, 

337 "iss": "missing-table", 

338 "aud": AI_API_AUDIENCE, 

339 "exp": int((now + timedelta(days=expires_days)).timestamp()), 

340 "iat": int(now.timestamp()), 

341 } 

342 return jwt.encode(payload, self.service_account_secret, algorithm="HS256") 

343 

344 def verify_ai_api_token(self, token: str) -> dict[str, Any] | None: 

345 """Verify an /api/ai/* token and return the API account's user data, or None. 

346 

347 The profile is re-read on every request, so clearing is_api_account (or 

348 deleting the row) revokes outstanding tokens immediately. 

349 """ 

350 try: 

351 payload = jwt.decode(token, self.service_account_secret, algorithms=["HS256"], audience=AI_API_AUDIENCE) 

352 user_id = payload.get("sub") 

353 if not user_id: 353 ↛ 354line 353 didn't jump to line 354 because the condition on line 353 was never true

354 return None 

355 response = self.supabase.table("user_profiles").select("*").eq("id", user_id).execute() 

356 profile = response.data[0] if response.data else None 

357 if not profile or not profile.get("is_api_account"): 

358 logger.warning(f"AI API token names {user_id}, which is not an API account") 

359 return None 

360 return { 

361 "user_id": user_id, 

362 "username": profile.get("username"), 

363 "email": None, 

364 "role": profile["role"], 

365 "team_id": profile.get("team_id"), 

366 "club_id": profile.get("club_id"), 

367 "assigned_age_group_id": profile.get("assigned_age_group_id"), # a fan's pick (SB-1543) 

368 "display_name": profile.get("display_name"), 

369 "is_test": profile.get("is_test", False), 

370 "is_api_account": True, 

371 } 

372 except jwt.ExpiredSignatureError: 

373 logger.warning("AI API token has expired") 

374 return None 

375 except jwt.InvalidTokenError: 

376 return None 

377 except Exception as e: 

378 logger.error(f"Error verifying AI API token: {e}") 

379 return None 

380 

381 def get_ai_user(self, credentials: HTTPAuthorizationCredentials) -> dict[str, Any]: 

382 """The caller of /api/ai/*: a logged-in person or an API account. 

383 

384 Service accounts authenticate but are not allowed to chat: MT AI needs a 

385 user_profiles row to own the conversation and to decide test visibility. 

386 """ 

387 token = credentials.credentials 

388 user = self.verify_token(token) or self.verify_ai_api_token(token) 

389 if user: 

390 return user 

391 if self.verify_service_account_token(token): 

392 raise HTTPException(status_code=403, detail="Service accounts cannot use MT AI.") 

393 raise HTTPException(status_code=401, detail="Invalid or expired token") 

394 

395 def create_password_reset_token(self, user_id: str) -> str: 

396 """Create a short-lived JWT for password reset (1 hour).""" 

397 expiration = datetime.now(UTC) + timedelta(hours=1) 

398 

399 payload = { 

400 "sub": user_id, 

401 "iss": "missing-table", 

402 "aud": "password-reset", 

403 "exp": int(expiration.timestamp()), 

404 "iat": int(datetime.now(UTC).timestamp()), 

405 } 

406 

407 return jwt.encode(payload, self.service_account_secret, algorithm="HS256") 

408 

409 def verify_password_reset_token(self, token: str) -> str | None: 

410 """Verify a password reset JWT and return the user_id, or None if invalid/expired.""" 

411 try: 

412 payload = jwt.decode( 

413 token, 

414 self.service_account_secret, 

415 algorithms=["HS256"], 

416 audience="password-reset", 

417 ) 

418 user_id = payload.get("sub") 

419 return user_id if user_id else None 

420 except jwt.ExpiredSignatureError: 

421 logger.warning("Password reset token has expired") 

422 return None 

423 except jwt.InvalidTokenError as e: 

424 logger.warning(f"Invalid password reset token: {e}") 

425 return None 

426 except Exception as e: 

427 logger.error(f"Error verifying password reset token: {e}") 

428 return None 

429 

430 def get_current_user(self, credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict[str, Any]: 

431 """FastAPI dependency to get current authenticated user or service account.""" 

432 if not credentials: 

433 logger.warning("auth_failed: no_credentials") 

434 raise HTTPException(status_code=401, detail="Authentication required") 

435 

436 # Try regular user token first 

437 user_data = self.verify_token(credentials.credentials) 

438 if user_data: 

439 logger.debug(f"auth_success: user={user_data.get('username')}") 

440 return user_data 

441 

442 # Try service account token 

443 service_data = self.verify_service_account_token(credentials.credentials) 

444 if service_data: 

445 logger.debug(f"auth_success: service={service_data.get('service_name')}") 

446 return service_data 

447 

448 logger.warning("auth_failed: invalid_token") 

449 raise HTTPException(status_code=401, detail="Invalid or expired token") 

450 

451 def require_role(self, required_roles: list): 

452 """Decorator to require specific roles.""" 

453 

454 def decorator(func): 

455 @wraps(func) 

456 async def wrapper(*args, **kwargs): 

457 # Get current user from kwargs (injected by FastAPI dependency) 

458 current_user = None 

459 for _key, value in kwargs.items(): 

460 if isinstance(value, dict) and "role" in value: 

461 current_user = value 

462 break 

463 

464 if not current_user: 

465 raise HTTPException(status_code=401, detail="Authentication required") 

466 

467 user_role = current_user.get("role") 

468 if user_role not in required_roles: 

469 raise HTTPException(status_code=403, detail=f"Access denied. Required roles: {required_roles}") 

470 

471 return await func(*args, **kwargs) 

472 

473 return wrapper 

474 

475 return decorator 

476 

477 def can_manage_team(self, user_data: dict[str, Any], team_id: int) -> bool: 

478 """Check if user can manage a specific team.""" 

479 role = user_data.get("role") 

480 user_team_id = user_data.get("team_id") 

481 user_club_id = user_data.get("club_id") 

482 

483 # Admins can manage any team 

484 if role == "admin": 

485 return True 

486 

487 # Team managers can only manage their own team 

488 if role == "team-manager" and user_team_id == team_id: 

489 return True 

490 

491 # Club managers can manage any team in their club 

492 if role == "club_manager" and user_club_id: 

493 team_club_id = self._get_team_club_id(team_id) 

494 if team_club_id and team_club_id == user_club_id: 

495 return True 

496 

497 return False 

498 

499 def _get_team_club_id(self, team_id: int) -> int | None: 

500 """Get the club_id for a team.""" 

501 try: 

502 result = self.supabase.table("teams").select("club_id").eq("id", team_id).execute() 

503 if result.data and len(result.data) > 0: 

504 return result.data[0].get("club_id") 

505 return None 

506 except Exception as e: 

507 logger.error(f"Error getting team club_id: {e}") 

508 return None 

509 

510 def can_edit_match(self, user_data: dict[str, Any], home_team_id: int, away_team_id: int) -> bool: 

511 """Check if user can edit a match between specific teams.""" 

512 role = user_data.get("role") 

513 user_team_id = user_data.get("team_id") 

514 user_club_id = user_data.get("club_id") 

515 username = user_data.get("username", "unknown") 

516 

517 logger.debug( 

518 f"can_edit_match check - User: {username}, Role: {role}, " 

519 f"user_team_id: {user_team_id}, user_club_id: {user_club_id}, " 

520 f"home_team_id: {home_team_id}, away_team_id: {away_team_id}" 

521 ) 

522 

523 # Admins can edit any match 

524 if role == "admin": 

525 logger.debug(f"can_edit_match: GRANTED - {username} is admin") 

526 return True 

527 

528 # Service accounts with manage_matches permission can edit any match 

529 if role == "service_account": 

530 permissions = user_data.get("permissions", []) 

531 if "manage_matches" in permissions: 

532 logger.debug("can_edit_match: GRANTED - service account has manage_matches") 

533 return True 

534 

535 # Team managers can edit matches involving their team 

536 if role == "team-manager" and user_team_id in [home_team_id, away_team_id]: 

537 logger.debug(f"can_edit_match: GRANTED - team manager's team ({user_team_id}) is in match") 

538 return True 

539 

540 # Club managers can edit matches involving any team in their club 

541 if role == "club_manager" and user_club_id: 

542 home_club_id = self._get_team_club_id(home_team_id) 

543 away_club_id = self._get_team_club_id(away_team_id) 

544 logger.debug( 

545 f"can_edit_match: club_manager check - user_club_id: {user_club_id}, " 

546 f"home_team ({home_team_id}) club: {home_club_id}, " 

547 f"away_team ({away_team_id}) club: {away_club_id}" 

548 ) 

549 if user_club_id in [home_club_id, away_club_id]: 

550 logger.debug("can_edit_match: GRANTED - club manager's club matches") 

551 return True 

552 else: 

553 logger.warning( 

554 f"can_edit_match: DENIED - club_manager {username} (club {user_club_id}) " 

555 f"cannot edit match between teams {home_team_id} (club {home_club_id}) " 

556 f"and {away_team_id} (club {away_club_id})" 

557 ) 

558 elif role == "club_manager" and not user_club_id: 

559 logger.warning(f"can_edit_match: DENIED - club_manager {username} has no club_id set") 

560 

561 logger.debug(f"can_edit_match: DENIED - {username} ({role}) lacks permission") 

562 return False 

563 

564 

565def can_manage_match( 

566 user_data: dict[str, Any] | None, 

567 home_team_id: int | None, 

568 away_team_id: int | None, 

569 home_club_id: int | None, 

570 away_club_id: int | None, 

571) -> bool: 

572 """Whether a user may manage (score, edit) a match — the same rules as 

573 AuthManager.can_edit_match, for a match whose teams' clubs are known. 

574 

575 Pure and silent (SB-1454): the match list stamps every row with this, so 

576 it must neither query a team's club per row nor log a denial for each of a 

577 fan's hundreds of matches. can_edit_match stays the enforcement point. 

578 """ 

579 if not user_data: 

580 return False 

581 role = user_data.get("role") 

582 if role == "admin": 

583 return True 

584 if role == "service_account" and "manage_matches" in (user_data.get("permissions") or []): 

585 return True 

586 if role == "team-manager" and user_data.get("team_id") in (home_team_id, away_team_id): 

587 return True 

588 club_id = user_data.get("club_id") 

589 return role == "club_manager" and bool(club_id) and club_id in (home_club_id, away_club_id) 

590 

591 

592# Auth dependency functions for FastAPI 

593# 

594# There is deliberately no optional variant (SB-1768): MT is invite-only, so no 

595# route serves data to a caller who is not logged in. 

596# tests/unit/test_route_auth_guard.py enforces it. 

597def get_current_user_required( 

598 credentials: HTTPAuthorizationCredentials = Depends(security), 

599) -> dict[str, Any]: 

600 """Get current user, raise exception if not authenticated.""" 

601 # This will be injected by the main app 

602 from app import auth_manager 

603 

604 return auth_manager.get_current_user(credentials) 

605 

606 

607def get_ai_user( 

608 credentials: HTTPAuthorizationCredentials = Depends(security), 

609) -> dict[str, Any]: 

610 """The caller of /api/ai/*: a person or an API account; service accounts get 403.""" 

611 from app import auth_manager 

612 

613 return auth_manager.get_ai_user(credentials) 

614 

615 

616def viewer_sees_test_content(user: dict[str, Any] | None) -> bool: 

617 """Whether a viewer may see is_test content (SB-85 prod test partition). 

618 

619 True for admins and flagged test users; False for anonymous and real users. 

620 Used by the public list endpoints to hide the TSC test world from real 

621 users while keeping it visible to test users + admins. 

622 """ 

623 return bool(user) and (user.get("role") == "admin" or bool(user.get("is_test"))) 

624 

625 

626def require_admin( 

627 current_user: dict[str, Any] = Depends(get_current_user_required), 

628) -> dict[str, Any]: 

629 """Require admin role.""" 

630 if current_user.get("role") != "admin": 

631 raise HTTPException(status_code=403, detail="Admin access required") 

632 return current_user 

633 

634 

635MANAGE_MOTW = "manage_motw" 

636 

637 

638def can_set_motw(user: dict[str, Any] | None) -> bool: 

639 """Admins, and service accounts granted `manage_motw` (SB-1553). 

640 

641 The MOTW agent's account is a service-account JWT with only this permission: 

642 it may pick the Match of the Week and nothing else. Every other admin route 

643 checks `role == "admin"`, which a service account never has. 

644 """ 

645 if not user: 

646 return False 

647 if user.get("role") == "admin": 

648 return True 

649 return user.get("role") == "service_account" and MANAGE_MOTW in (user.get("permissions") or []) 

650 

651 

652def require_motw_editor( 

653 current_user: dict[str, Any] = Depends(get_current_user_required), 

654) -> dict[str, Any]: 

655 """Require admin, or a service account with the `manage_motw` permission.""" 

656 if not can_set_motw(current_user): 

657 raise HTTPException(status_code=403, detail="Admin access required") 

658 return current_user 

659 

660 

661def require_team_manager_or_admin( 

662 current_user: dict[str, Any] = Depends(get_current_user_required), 

663) -> dict[str, Any]: 

664 """Require team-manager, club_manager, or admin role.""" 

665 role = current_user.get("role") 

666 if role not in ["admin", "club_manager", "team-manager"]: 666 ↛ 667line 666 didn't jump to line 667 because the condition on line 666 was never true

667 raise HTTPException(status_code=403, detail="Team manager, club manager, or admin access required") 

668 return current_user 

669 

670 

671def require_admin_or_service_account( 

672 current_user: dict[str, Any] = Depends(get_current_user_required), 

673) -> dict[str, Any]: 

674 """Require admin role or service account with appropriate permissions.""" 

675 role = current_user.get("role") 

676 

677 # Allow admin users 

678 if role == "admin": 678 ↛ 679line 678 didn't jump to line 679 because the condition on line 678 was never true

679 return current_user 

680 

681 # Allow service accounts with match management permissions 

682 if role == "service_account": 

683 permissions = current_user.get("permissions", []) 

684 if "manage_matches" in permissions: 684 ↛ 685line 684 didn't jump to line 685 because the condition on line 684 was never true

685 return current_user 

686 else: 

687 raise HTTPException(status_code=403, detail="Service account requires 'manage_matches' permission") 

688 

689 raise HTTPException(status_code=403, detail="Admin or authorized service account access required") 

690 

691 

692def require_match_management_permission( 

693 current_user: dict[str, Any] = Depends(get_current_user_required), 

694) -> dict[str, Any]: 

695 """Require permission to manage matches (admin, club_manager, team-manager, or service account).""" 

696 import logging 

697 

698 logger = logging.getLogger(__name__) 

699 

700 role = current_user.get("role") 

701 # Use username for regular users, service_name for service accounts 

702 user_identifier = current_user.get("username") or current_user.get("service_name", "unknown") 

703 

704 logger.info(f"Match management permission check - User: {user_identifier}, Role: {role}, User data: {current_user}") 

705 

706 # Allow admin, club managers, and team managers 

707 if role in ["admin", "club_manager", "team-manager"]: 

708 logger.info(f"Access granted - User {user_identifier} has role {role}") 

709 return current_user 

710 

711 # Allow service accounts with match management permissions 

712 if role == "service_account": 712 ↛ 713line 712 didn't jump to line 713 because the condition on line 712 was never true

713 permissions = current_user.get("permissions", []) 

714 if "manage_matches" in permissions: 

715 logger.info(f"Access granted - Service account {user_identifier} has manage_matches permission") 

716 return current_user 

717 else: 

718 logger.warning( 

719 f"Access denied - Service account {user_identifier} missing manage_matches permission. " 

720 f"Has: {permissions}" 

721 ) 

722 raise HTTPException(status_code=403, detail="Service account requires 'manage_matches' permission") 

723 

724 logger.warning(f"Access denied - User {user_identifier} has insufficient role: {role}") 

725 raise HTTPException( 

726 status_code=403, 

727 detail="Admin, club manager, team manager, or authorized service account access required", 

728 )