Skip to content

Commit

Permalink
use pydantic for validation
Browse files Browse the repository at this point in the history
  • Loading branch information
H-Shay committed Oct 7, 2024
1 parent 48b7754 commit b2f9ba4
Showing 1 changed file with 16 additions and 28 deletions.
44 changes: 16 additions & 28 deletions synapse/rest/admin/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

import attr

from synapse._pydantic_compat import StrictBool
from synapse._pydantic_compat import StrictBool, StrictInt, StrictStr
from synapse.api.constants import Direction, UserTypes
from synapse.api.errors import Codes, NotFoundError, SynapseError
from synapse.http.servlet import (
Expand Down Expand Up @@ -1421,42 +1421,30 @@ def __init__(self, hs: "HomeServer"):
self._store = hs.get_datastores().main
self.admin_handler = hs.get_admin_handler()

class PostBody(RequestBodyModel):
rooms: List[StrictStr]
reason: Optional[StrictStr]
limit: Optional[StrictInt]

async def on_POST(
self, request: SynapseRequest, user_id: str
) -> Tuple[int, JsonDict]:
requester = await self._auth.get_user_by_req(request)
await assert_user_is_admin(self._auth, requester)

if not user_id:
raise SynapseError(
HTTPStatus.BAD_REQUEST, f"Must provide a valid username: {user_id}"
)
# parse provided user id to check that it is valid
UserID.from_string(user_id)

body = parse_json_object_from_request(request, allow_empty_body=True)
rooms = body.get("rooms")
if rooms is None:
body = parse_and_validate_json_object_from_request(request, self.PostBody)

limit = body.limit
if limit and limit <= 0:
raise SynapseError(
HTTPStatus.BAD_REQUEST, "Must provide a value for rooms."
HTTPStatus.BAD_REQUEST,
"If limit is provided it must be a non-negative integer greater than 0.",
)
if not isinstance(rooms, list):
raise SynapseError(HTTPStatus.BAD_REQUEST, "Rooms must be a list.")

reason = body.get("reason")
if reason:
if not isinstance(reason, str):
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"If a reason is provided it must be a string.",
)

limit = body.get("limit")
if limit:
if not isinstance(limit, int) or limit <= 0:
raise SynapseError(
HTTPStatus.BAD_REQUEST,
"If limit is provided it must be a non-negative integer greater than 0.",
)

rooms = body.rooms
if not rooms:
current_rooms = list(await self._store.get_rooms_for_user(user_id))
banned_rooms = list(
Expand All @@ -1465,7 +1453,7 @@ async def on_POST(
rooms = current_rooms + banned_rooms

redact_id = await self.admin_handler.start_redact_events(
user_id, rooms, requester.serialize(), reason, limit
user_id, rooms, requester.serialize(), body.reason, limit
)

return HTTPStatus.OK, {"redact_id": redact_id}
Expand Down

0 comments on commit b2f9ba4

Please sign in to comment.