feat(user): implement user restrictions
## APIs Restricted for Restricted Users
A restricted user is blocked from performing the following actions, and will typically receive a `403 Forbidden` error:
* **Chat & Notifications:**
* Sending any chat messages (public or private).
* Joining or leaving chat channels.
* Creating new PM channels.
* **User Profile & Content:**
* Uploading a new avatar.
* Uploading a new profile cover image.
* Changing their username.
* Updating their userpage content.
* **Scores & Gameplay:**
* Submitting scores in multiplayer rooms.
* Deleting their own scores (to prevent hiding evidence of cheating).
* **Beatmaps:**
* Rating beatmaps.
* Taging beatmaps.
* **Relationship:**
* Adding friends or blocking users.
* Removing friends or unblocking users.
* **Teams:**
* Creating, updating, or deleting a team.
* Requesting to join a team.
* Handling join requests for a team they manage.
* Kicking a member from a team they manage.
* **Multiplayer:**
* Creating or deleting multiplayer rooms.
* Joining or leaving multiplayer rooms.
## What is Invisible to Normal Users
* **Leaderboards:**
* Beatmap leaderboards.
* Multiplayer (playlist) room leaderboards.
* **User Search/Lists:**
* Restricted users will not appear in the results of the `/api/v2/users` endpoint.
* They will not appear in the list of a team's members.
* **Relationship:**
* They will not appear in a user's friend list (`/friends`).
* **Profile & History:**
* Attempting to view a restricted user's profile, events, kudosu history, or score history will result in a `404 Not Found` error, effectively making their profile invisible (unless the user viewing the profile is the restricted user themselves).
* **Chat:**
* Normal users cannot start a new PM with a restricted user (they will get a `404 Not Found` error).
* **Ranking:**
* Restricted users are excluded from any rankings.
### How to Restrict a User
Insert into `user_account_history` with `type=restriction`.
```sql
-- length is in seconds
INSERT INTO user_account_history (`description`, `length`, `permanent`, `timestamp`, `type`, `user_id`) VALUE ('some description', 86400, 0, '2025-10-05 01:00:00', 'RESTRICTION', 1);
```
---
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -15,10 +15,10 @@ from app.database import (
|
||||
from app.database.best_scores import BestScore
|
||||
from app.database.events import Event
|
||||
from app.database.score import LegacyScoreResp, Score, ScoreResp, get_user_first_scores
|
||||
from app.database.user import SEARCH_INCLUDED
|
||||
from app.database.user import ALL_INCLUDED, SEARCH_INCLUDED
|
||||
from app.dependencies.api_version import APIVersion
|
||||
from app.dependencies.database import Database, get_redis
|
||||
from app.dependencies.user import get_current_user
|
||||
from app.dependencies.user import get_current_user, get_optional_user
|
||||
from app.helpers.asset_proxy_helper import asset_proxy_response
|
||||
from app.log import log
|
||||
from app.models.mods import API_MODS
|
||||
@@ -52,6 +52,14 @@ def _get_difficulty_reduction_mods() -> set[str]:
|
||||
return mods
|
||||
|
||||
|
||||
async def visible_to_current_user(user: User, current_user: User | None, session: Database) -> bool:
|
||||
if user.id == BANCHOBOT_ID:
|
||||
return False
|
||||
if current_user and current_user.id == user.id:
|
||||
return True
|
||||
return not await user.is_restricted(session)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/users/",
|
||||
response_model=BatchUserResponse,
|
||||
@@ -90,7 +98,11 @@ async def get_users(
|
||||
|
||||
# 查询未缓存的用户
|
||||
if uncached_user_ids:
|
||||
searched_users = (await session.exec(select(User).where(col(User.id).in_(uncached_user_ids)))).all()
|
||||
searched_users = (
|
||||
await session.exec(
|
||||
select(User).where(col(User.id).in_(uncached_user_ids), ~User.is_restricted_query(col(User.id)))
|
||||
)
|
||||
).all()
|
||||
|
||||
# 将查询到的用户添加到缓存并返回
|
||||
for searched_user in searched_users:
|
||||
@@ -107,7 +119,9 @@ async def get_users(
|
||||
response = BatchUserResponse(users=cached_users)
|
||||
return response
|
||||
else:
|
||||
searched_users = (await session.exec(select(User).limit(50))).all()
|
||||
searched_users = (
|
||||
await session.exec(select(User).limit(50).where(~User.is_restricted_query(col(User.id))))
|
||||
).all()
|
||||
users = []
|
||||
for searched_user in searched_users:
|
||||
if searched_user.id == BANCHOBOT_ID:
|
||||
@@ -139,7 +153,7 @@ async def get_user_events(
|
||||
offset: Annotated[int | None, Query(description="活动日志的偏移量")] = None,
|
||||
):
|
||||
db_user = await session.get(User, user_id)
|
||||
if db_user is None or db_user.id == BANCHOBOT_ID:
|
||||
if db_user is None or not await visible_to_current_user(db_user, None, session):
|
||||
raise HTTPException(404, "User Not found")
|
||||
events = (
|
||||
await session.exec(
|
||||
@@ -174,7 +188,7 @@ async def get_user_kudosu(
|
||||
"""
|
||||
# 验证用户是否存在
|
||||
db_user = await session.get(User, user_id)
|
||||
if db_user is None or db_user.id == BANCHOBOT_ID:
|
||||
if db_user is None or not await visible_to_current_user(db_user, None, session):
|
||||
raise HTTPException(404, "User not found")
|
||||
|
||||
# TODO: 实现 kudosu 记录获取逻辑
|
||||
@@ -214,7 +228,7 @@ async def get_user_beatmaps_passed(
|
||||
raise HTTPException(status_code=413, detail="beatmapset_ids cannot exceed 50 items")
|
||||
|
||||
user = await session.get(User, user_id)
|
||||
if not user or user.id == BANCHOBOT_ID:
|
||||
if user is None or not await visible_to_current_user(user, current_user, session):
|
||||
raise HTTPException(404, detail="User not found")
|
||||
|
||||
allowed_mode: GameMode | None = None
|
||||
@@ -282,7 +296,7 @@ async def get_user_info_ruleset(
|
||||
background_task: BackgroundTasks,
|
||||
user_id: Annotated[str, Path(description="用户 ID 或用户名")],
|
||||
ruleset: Annotated[GameMode | None, Path(description="指定 ruleset")],
|
||||
# current_user: User = Security(get_current_user, scopes=["public"]),
|
||||
current_user: User | None = Security(get_optional_user, scopes=["public"]),
|
||||
):
|
||||
redis = get_redis()
|
||||
cache_service = get_user_cache_service(redis)
|
||||
@@ -303,11 +317,18 @@ async def get_user_info_ruleset(
|
||||
).first()
|
||||
if not searched_user or searched_user.id == BANCHOBOT_ID:
|
||||
raise HTTPException(404, detail="User not found")
|
||||
searched_is_self = current_user is not None and current_user.id == searched_user.id
|
||||
should_not_show = not searched_is_self and await searched_user.is_restricted(session)
|
||||
if should_not_show:
|
||||
raise HTTPException(404, detail="User not found")
|
||||
|
||||
include = SEARCH_INCLUDED
|
||||
if searched_is_self:
|
||||
include = ALL_INCLUDED
|
||||
user_resp = await UserResp.from_db(
|
||||
searched_user,
|
||||
session,
|
||||
include=SEARCH_INCLUDED,
|
||||
include=include,
|
||||
ruleset=ruleset,
|
||||
)
|
||||
|
||||
@@ -331,7 +352,7 @@ async def get_user_info(
|
||||
session: Database,
|
||||
request: Request,
|
||||
user_id: Annotated[str, Path(description="用户 ID 或用户名")],
|
||||
# current_user: User = Security(get_current_user, scopes=["public"]),
|
||||
current_user: User | None = Security(get_optional_user, scopes=["public"]),
|
||||
):
|
||||
redis = get_redis()
|
||||
cache_service = get_user_cache_service(redis)
|
||||
@@ -352,11 +373,18 @@ async def get_user_info(
|
||||
).first()
|
||||
if not searched_user or searched_user.id == BANCHOBOT_ID:
|
||||
raise HTTPException(404, detail="User not found")
|
||||
searched_is_self = current_user is not None and current_user.id == searched_user.id
|
||||
should_not_show = not searched_is_self and await searched_user.is_restricted(session)
|
||||
if should_not_show:
|
||||
raise HTTPException(404, detail="User not found")
|
||||
|
||||
include = SEARCH_INCLUDED
|
||||
if searched_is_self:
|
||||
include = ALL_INCLUDED
|
||||
user_resp = await UserResp.from_db(
|
||||
searched_user,
|
||||
session,
|
||||
include=SEARCH_INCLUDED,
|
||||
include=include,
|
||||
)
|
||||
|
||||
# 异步缓存结果
|
||||
@@ -411,7 +439,7 @@ async def get_user_beatmapsets(
|
||||
|
||||
elif type == BeatmapsetType.FAVOURITE:
|
||||
user = await session.get(User, user_id)
|
||||
if not user:
|
||||
if user is None or not await visible_to_current_user(user, current_user, session):
|
||||
raise HTTPException(404, detail="User not found")
|
||||
favourites = await user.awaitable_attrs.favourite_beatmapsets
|
||||
resp = [
|
||||
@@ -419,6 +447,10 @@ async def get_user_beatmapsets(
|
||||
]
|
||||
|
||||
elif type == BeatmapsetType.MOST_PLAYED:
|
||||
user = await session.get(User, user_id)
|
||||
if user is None or not await visible_to_current_user(user, current_user, session):
|
||||
raise HTTPException(404, detail="User not found")
|
||||
|
||||
most_played = await session.exec(
|
||||
select(BeatmapPlaycounts)
|
||||
.where(BeatmapPlaycounts.user_id == user_id)
|
||||
@@ -484,7 +516,7 @@ async def get_user_scores(
|
||||
return cached_scores
|
||||
|
||||
db_user = await session.get(User, user_id)
|
||||
if not db_user or db_user.id == BANCHOBOT_ID:
|
||||
if db_user is None or not await visible_to_current_user(db_user, current_user, session):
|
||||
raise HTTPException(404, detail="User not found")
|
||||
|
||||
gamemode = mode or db_user.playmode
|
||||
|
||||
Reference in New Issue
Block a user