Coverage for api/moderation.py: 86.44%
92 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2Live chat moderation API (SB-1309, App Store guideline 1.2).
4Endpoints:
5- POST /api/matches/{match_id}/live/events/{event_id}/report — report a chat message
6 (also blocks its author)
7- POST /api/users/{user_id}/block — block a user
8- DELETE /api/users/{user_id}/block — unblock
9- GET /api/users/me/blocks — who I have blocked
10- GET /api/admin/content-reports — review queue (admin)
11- PATCH /api/admin/content-reports/{report_id} — act on a report (admin)
13The other halves live with the chat endpoints in app.py: the word filter and
14the ban check on POST /live/message, and hiding blocked authors on the reads.
15"""
17from __future__ import annotations
19from typing import Any, Literal
21import structlog
22from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
23from pydantic import BaseModel, Field
25from auth import get_current_user_required, require_admin
26from dao.match_dao import SupabaseConnection
27from dao.match_event_dao import MatchEventDAO
28from dao.moderation_dao import ModerationDAO, UnknownUserError
29from notifications.moderation_alerts import alert_content_report
31logger = structlog.get_logger(__name__)
33router = APIRouter(prefix="/api", tags=["moderation"])
36# ---------------------------------------------------------------------------
37# Lazy connection + DAO singletons
38# ---------------------------------------------------------------------------
40_connection: SupabaseConnection | None = None
43def _conn() -> SupabaseConnection:
44 global _connection
45 if _connection is None:
46 _connection = SupabaseConnection()
47 return _connection
50def _moderation_dao() -> ModerationDAO:
51 return ModerationDAO(_conn())
54def _event_dao() -> MatchEventDAO:
55 return MatchEventDAO(_conn())
58def _user_id(user: dict[str, Any]) -> str:
59 """auth.py's current_user dict uses either 'user_id' or 'id'."""
60 uid = user.get("user_id") or user.get("id")
61 if not uid: 61 ↛ 62line 61 didn't jump to line 62 because the condition on line 61 was never true
62 raise HTTPException(status_code=401, detail="Missing user identity")
63 return str(uid)
66# ---------------------------------------------------------------------------
67# Pydantic models
68# ---------------------------------------------------------------------------
71class ReportIn(BaseModel):
72 """Body of POST /api/matches/{match_id}/live/events/{event_id}/report."""
74 reason: Literal["spam", "harassment", "hate", "sexual", "other"]
75 details: str | None = Field(None, max_length=500)
78class ReportActionIn(BaseModel):
79 """Body of PATCH /api/admin/content-reports/{report_id}."""
81 action: Literal["dismiss", "delete_message", "ban_user"]
84# An action's resulting report status.
85_ACTION_STATUS = {"dismiss": "dismissed", "delete_message": "actioned", "ban_user": "actioned"}
88# ---------------------------------------------------------------------------
89# Report
90# ---------------------------------------------------------------------------
93@router.post(
94 "/matches/{match_id}/live/events/{event_id}/report",
95 status_code=status.HTTP_201_CREATED,
96)
97def report_event(
98 match_id: int,
99 event_id: int,
100 payload: ReportIn,
101 current_user: dict[str, Any] = Depends(get_current_user_required),
102) -> dict[str, Any]:
103 """Report a chat message, and block its author for the reporter.
105 Reporting the same message twice is not an error: the second call records
106 nothing new, sends no alert, and answers the same way.
107 """
108 reporter_id = _user_id(current_user)
110 event = _event_dao().get_event_by_id(event_id)
111 if not event or event.get("match_id") != match_id:
112 raise HTTPException(status_code=404, detail="Event not found")
113 if event.get("event_type") != "message":
114 raise HTTPException(status_code=400, detail="Only chat messages can be reported")
116 author_id = event.get("created_by")
117 if author_id and str(author_id) == reporter_id:
118 raise HTTPException(status_code=400, detail="You cannot report your own message")
120 dao = _moderation_dao()
121 report = dao.create_report(event=event, reporter_id=reporter_id, reason=payload.reason, details=payload.details)
123 if author_id: 123 ↛ 130line 123 didn't jump to line 130 because the condition on line 123 was always true
124 try:
125 dao.block_user(reporter_id, str(author_id))
126 except UnknownUserError:
127 # The author's account is gone; their messages go with it.
128 logger.info("report_author_has_no_profile", event_id=event_id)
130 if report:
131 logger.info("content_reported", report_id=report.get("id"), event_id=event_id, reason=payload.reason)
132 alert_content_report(dao, report, current_user.get("username"))
134 return {"reported": True, "blocked_user_id": str(author_id) if author_id else None}
137# ---------------------------------------------------------------------------
138# Blocks
139# ---------------------------------------------------------------------------
142@router.post("/users/{user_id}/block", status_code=status.HTTP_204_NO_CONTENT)
143def block_user(
144 user_id: str,
145 current_user: dict[str, Any] = Depends(get_current_user_required),
146) -> Response:
147 blocker_id = _user_id(current_user)
148 if user_id == blocker_id:
149 raise HTTPException(status_code=400, detail="You cannot block yourself")
150 try:
151 _moderation_dao().block_user(blocker_id, user_id)
152 except UnknownUserError as exc:
153 raise HTTPException(status_code=404, detail="User not found") from exc
154 return Response(status_code=status.HTTP_204_NO_CONTENT)
157@router.delete("/users/{user_id}/block", status_code=status.HTTP_204_NO_CONTENT)
158def unblock_user(
159 user_id: str,
160 current_user: dict[str, Any] = Depends(get_current_user_required),
161) -> Response:
162 _moderation_dao().unblock_user(_user_id(current_user), user_id)
163 return Response(status_code=status.HTTP_204_NO_CONTENT)
166@router.get("/users/me/blocks")
167def list_blocks(
168 current_user: dict[str, Any] = Depends(get_current_user_required),
169) -> list[dict[str, Any]]:
170 return _moderation_dao().list_blocks(_user_id(current_user))
173# ---------------------------------------------------------------------------
174# Admin review
175# ---------------------------------------------------------------------------
178@router.get("/admin/content-reports")
179def list_content_reports(
180 status_filter: Literal["pending", "actioned", "dismissed"] | None = Query(None, alias="status"),
181 _admin: dict[str, Any] = Depends(require_admin),
182) -> list[dict[str, Any]]:
183 return _moderation_dao().list_reports(status_filter)
186@router.patch("/admin/content-reports/{report_id}")
187def act_on_content_report(
188 report_id: int,
189 payload: ReportActionIn,
190 admin: dict[str, Any] = Depends(require_admin),
191) -> dict[str, Any]:
192 """Dismiss a report, delete the message, or delete it and ban its author.
194 The message may already be gone — expired, or deleted by its author or a
195 manager — in which case deleting it is skipped and the report still
196 resolves.
197 """
198 admin_id = _user_id(admin)
199 dao = _moderation_dao()
201 report = dao.get_report(report_id)
202 if not report:
203 raise HTTPException(status_code=404, detail="Report not found")
205 if payload.action == "ban_user" and not report.get("reported_user_id"): 205 ↛ 206line 205 didn't jump to line 206 because the condition on line 205 was never true
206 raise HTTPException(status_code=400, detail="The author's account no longer exists")
208 if payload.action in ("delete_message", "ban_user") and report.get("event_id"):
209 _event_dao().soft_delete_event(report["event_id"], deleted_by=admin_id)
211 if payload.action == "ban_user":
212 dao.ban_from_chat(report["reported_user_id"])
214 updated = dao.resolve_report(
215 report_id, status=_ACTION_STATUS[payload.action], action=payload.action, resolved_by=admin_id
216 )
217 if not updated: 217 ↛ 218line 217 didn't jump to line 218 because the condition on line 217 was never true
218 raise HTTPException(status_code=500, detail="Failed to update report")
220 logger.info("content_report_resolved", report_id=report_id, action=payload.action, admin_id=admin_id)
221 return updated