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:
MingxuanGame
2025-10-06 11:10:25 +08:00
committed by GitHub
parent d19f82df80
commit febc1d761f
25 changed files with 354 additions and 222 deletions

View File

@@ -99,6 +99,7 @@ async def get_team_ranking(
UserStatistics.mode == ruleset,
UserStatistics.pp > 0,
col(UserStatistics.user).has(col(User.team_membership).has(col(TeamMember.team_id) == team.id)),
~User.is_restricted_query(col(UserStatistics.user_id)),
)
)
).all()
@@ -249,6 +250,7 @@ async def get_country_ranking(
UserStatistics.pp > 0,
col(UserStatistics.user).has(country_code=country),
col(UserStatistics.user).has(is_active=True),
~User.is_restricted_query(col(UserStatistics.user_id)),
)
)
).all()
@@ -363,7 +365,14 @@ async def get_user_ranking(
total_count = total_count_result.one()
statistics_list = await session.exec(
select(UserStatistics).where(*wheres).order_by(order_by).limit(50).offset(50 * (page - 1))
select(UserStatistics)
.where(
*wheres,
~User.is_restricted_query(col(UserStatistics.user_id)),
)
.order_by(order_by)
.limit(50)
.offset(50 * (page - 1))
)
# 转换为响应格式

View File

@@ -10,7 +10,7 @@ from .router import router
from fastapi import HTTPException, Path, Query, Request, Security
from pydantic import BaseModel
from sqlmodel import exists, select
from sqlmodel import col, exists, select
@router.get(
@@ -63,6 +63,7 @@ async def get_relationship(
select(Relationship).where(
Relationship.user_id == current_user.id,
Relationship.type == relationship_type,
~User.is_restricted_query(col(Relationship.target_id)),
)
)
if api_version >= 20241022 or relationship_type == RelationshipType.BLOCK:
@@ -110,7 +111,11 @@ async def add_relationship(
target: Annotated[int, Query(description="目标用户 ID")],
current_user: ClientUser,
):
if not (await db.exec(select(exists()).where(User.id == target))).first():
if await current_user.is_restricted(db):
raise HTTPException(403, "Your account is restricted and cannot perform this action.")
if not (
await db.exec(select(exists()).where((User.id == target) & ~User.is_restricted_query(col(User.id))))
).first():
raise HTTPException(404, "Target user not found")
relationship_type = RelationshipType.FOLLOW if request.url.path.endswith("/friends") else RelationshipType.BLOCK
@@ -179,7 +184,11 @@ async def delete_relationship(
target: Annotated[int, Path(..., description="目标用户 ID")],
current_user: ClientUser,
):
if not (await db.exec(select(exists()).where(User.id == target))).first():
if await current_user.is_restricted(db):
raise HTTPException(403, "Your account is restricted and cannot perform this action.")
if not (
await db.exec(select(exists()).where((User.id == target) & ~User.is_restricted_query(col(User.id))))
).first():
raise HTTPException(404, "Target user not found")
relationship_type = RelationshipType.BLOCK if "/blocks/" in request.url.path else RelationshipType.FOLLOW

View File

@@ -143,6 +143,9 @@ async def create_room(
current_user: ClientUser,
redis: Redis,
):
if await current_user.is_restricted(db):
raise HTTPException(status_code=403, detail="Your account is restricted from multiplayer.")
user_id = current_user.id
db_room = await create_playlist_room_from_api(db, room, user_id)
await _participate_room(db_room.id, user_id, db_room, db, redis)
@@ -189,6 +192,9 @@ async def delete_room(
room_id: Annotated[int, Path(..., description="房间 ID")],
current_user: ClientUser,
):
if await current_user.is_restricted(db):
raise HTTPException(status_code=403, detail="Your account is restricted from multiplayer.")
db_room = (await db.exec(select(Room).where(Room.id == room_id))).first()
if db_room is None:
raise HTTPException(404, "Room not found")
@@ -211,6 +217,9 @@ async def add_user_to_room(
redis: Redis,
current_user: ClientUser,
):
if await current_user.is_restricted(db):
raise HTTPException(status_code=403, detail="Your account is restricted from multiplayer.")
db_room = (await db.exec(select(Room).where(Room.id == room_id))).first()
if db_room is not None:
await _participate_room(room_id, user_id, db_room, db, redis)
@@ -235,6 +244,9 @@ async def remove_user_from_room(
current_user: ClientUser,
redis: Redis,
):
if await current_user.is_restricted(db):
raise HTTPException(status_code=403, detail="Your account is restricted from multiplayer.")
db_room = (await db.exec(select(Room).where(Room.id == room_id))).first()
if db_room is not None:
participated_user = (

View File

@@ -255,9 +255,6 @@ async def get_beatmap_scores(
] = LeaderboardType.GLOBAL,
limit: Annotated[int, Query(ge=1, le=200, description="返回条数 (1-200)")] = 50,
):
if legacy_only:
raise HTTPException(status_code=404, detail="this server only contains lazer scores")
all_scores, user_score, count = await get_leaderboard(
db,
beatmap_id,
@@ -355,6 +352,7 @@ async def get_user_all_beatmap_scores(
Score.beatmap_id == beatmap_id,
Score.user_id == user_id,
col(Score.passed).is_(True),
~User.is_restricted_query(col(Score.user_id)),
)
.order_by(col(Score.total_score).desc())
)
@@ -433,7 +431,9 @@ async def create_playlist_score(
current_user: ClientUser,
version_hash: Annotated[str, Form(description="谱面版本哈希")] = "",
):
# 立即获取用户ID避免懒加载问题
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="You are restricted from submitting multiplayer scores")
user_id = current_user.id
room = await session.get(Room, room_id)
@@ -499,7 +499,9 @@ async def submit_playlist_score(
redis: Redis,
fetcher: Fetcher,
):
# 立即获取用户ID避免懒加载问题
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="You are restricted from submitting multiplayer scores")
user_id = current_user.id
item = (await session.exec(select(Playlist).where(Playlist.id == playlist_id, Playlist.room_id == room_id))).first()
@@ -574,6 +576,7 @@ async def index_playlist_scores(
PlaylistBestScore.playlist_id == playlist_id,
PlaylistBestScore.room_id == room_id,
PlaylistBestScore.total_score < cursor,
~User.is_restricted_query(col(PlaylistBestScore.user_id)),
)
.order_by(col(PlaylistBestScore.total_score).desc())
.limit(limit + 1)
@@ -641,6 +644,7 @@ async def show_playlist_score(
PlaylistBestScore.score_id == score_id,
PlaylistBestScore.playlist_id == playlist_id,
PlaylistBestScore.room_id == room_id,
~User.is_restricted_query(col(PlaylistBestScore.user_id)),
)
)
).first()
@@ -658,6 +662,7 @@ async def show_playlist_score(
select(PlaylistBestScore).where(
PlaylistBestScore.playlist_id == playlist_id,
PlaylistBestScore.room_id == room_id,
~User.is_restricted_query(col(PlaylistBestScore.user_id)),
)
)
).all()
@@ -702,6 +707,7 @@ async def get_user_playlist_score(
PlaylistBestScore.user_id == user_id,
PlaylistBestScore.playlist_id == playlist_id,
PlaylistBestScore.room_id == room_id,
~User.is_restricted_query(col(PlaylistBestScore.user_id)),
)
)
).first()

View File

@@ -58,6 +58,9 @@ async def vote_beatmap_tags(
session: Database,
current_user: Annotated[User, Depends(get_client_user)],
):
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
try:
get_tag_by_id(tag_id)
beatmap = (await session.exec(select(exists()).where(Beatmap.id == beatmap_id))).first()
@@ -98,6 +101,9 @@ async def devote_beatmap_tags(
- **beatmap_id**: 谱面ID
- **tag_id**: 标签ID
"""
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
try:
tag = get_tag_by_id(tag_id)
assert tag is not None

View File

@@ -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