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

@@ -8,7 +8,7 @@ from app.utils import check_image
from .router import router
from fastapi import File
from fastapi import File, HTTPException
@router.post("/avatar/upload", name="上传头像", tags=["用户", "g0v0 API"])
@@ -30,6 +30,8 @@ async def upload_avatar(
返回:
- 头像 URL 和文件哈希值
"""
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
# check file
format_ = check_image(content, 5 * 1024 * 1024, 256, 256)

View File

@@ -38,6 +38,9 @@ async def can_rate_beatmapset(
返回:
- bool: 用户是否可以评价谱面集
"""
if await current_user.is_restricted(session):
return False
user_id = current_user.id
prev_ratings = (await session.exec(select(BeatmapRating).where(BeatmapRating.user_id == user_id))).first()
if prev_ratings is not None:
@@ -73,6 +76,9 @@ async def rate_beatmaps(
返回:
- 成功: None
"""
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
user_id = current_user.id
current_beatmapset = (await session.exec(select(exists()).where(Beatmapset.id == beatmapset_id))).first()
if not current_beatmapset:

View File

@@ -9,7 +9,7 @@ from app.utils import check_image
from .router import router
from fastapi import File
from fastapi import File, HTTPException
@router.post("/cover/upload", name="上传头图", tags=["用户", "g0v0 API"])
@@ -31,6 +31,8 @@ async def upload_cover(
返回:
- 头图 URL 和文件哈希值
"""
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
# check file
format_ = check_image(content, 10 * 1024 * 1024, 3000, 2000)

View File

@@ -1,3 +1,4 @@
from app.config import settings
from app.database.score import Score
from app.dependencies.database import Database, Redis
from app.dependencies.storage import StorageService
@@ -8,37 +9,42 @@ from .router import router
from fastapi import BackgroundTasks, HTTPException
if settings.allow_delete_scores:
@router.delete(
"/score/{score_id}",
name="删除指定ID的成绩",
tags=["成绩", "g0v0 API"],
status_code=204,
)
async def delete_score(
session: Database,
background_task: BackgroundTasks,
score_id: int,
redis: Redis,
current_user: ClientUser,
storage_service: StorageService,
):
"""删除成绩
@router.delete(
"/score/{score_id}",
name="删除指定ID的成绩",
tags=["成绩", "g0v0 API"],
status_code=204,
)
async def delete_score(
session: Database,
background_task: BackgroundTasks,
score_id: int,
redis: Redis,
current_user: ClientUser,
storage_service: StorageService,
):
"""删除成绩
删除成绩同时删除对应的统计信息、排行榜分数、pp、回放文件
删除成绩同时删除对应的统计信息、排行榜分数、pp、回放文件
参数:
- score_id: 成绩ID
参数:
- score_id: 成绩ID
错误情况:
- 404: 找不到指定成绩
"""
score = await session.get(Score, score_id)
if not score or score.user_id != current_user.id:
raise HTTPException(status_code=404, detail="找不到指定成绩")
错误情况:
- 404: 找不到指定成绩
"""
if await current_user.is_restricted(session):
# avoid deleting the evidence of cheating
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
gamemode = score.gamemode
user_id = score.user_id
await score.delete(session, storage_service)
await session.commit()
background_task.add_task(refresh_user_cache_background, redis, user_id, gamemode)
score = await session.get(Score, score_id)
if not score or score.user_id != current_user.id:
raise HTTPException(status_code=404, detail="找不到指定成绩")
gamemode = score.gamemode
user_id = score.user_id
await score.delete(session, storage_service)
await session.commit()
background_task.add_task(refresh_user_cache_background, redis, user_id, gamemode)

View File

@@ -19,7 +19,7 @@ from .router import router
from fastapi import File, Form, HTTPException, Path, Request
from pydantic import BaseModel
from sqlmodel import exists, select
from sqlmodel import col, exists, select
@router.post("/team", name="创建战队", response_model=Team, tags=["战队", "g0v0 API"])
@@ -38,6 +38,9 @@ async def create_team(
flag 限制 240x120, 2MB; cover 限制 3000x2000, 10MB
支持的图片格式: PNG、JPEG、GIF
"""
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
user_id = current_user.id
if (await current_user.awaitable_attrs.team_membership) is not None:
raise HTTPException(status_code=403, detail="You are already in a team")
@@ -98,6 +101,9 @@ async def update_team(
flag 限制 240x120, 2MB; cover 限制 3000x2000, 10MB
支持的图片格式: PNG、JPEG、GIF
"""
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
team = await session.get(Team, team_id)
user_id = current_user.id
if not team:
@@ -162,6 +168,9 @@ async def delete_team(
current_user: ClientUser,
redis: Redis,
):
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
team = await session.get(Team, team_id)
if not team:
raise HTTPException(status_code=404, detail="Team not found")
@@ -190,7 +199,14 @@ async def get_team(
session: Database,
team_id: Annotated[int, Path(..., description="战队 ID")],
):
members = (await session.exec(select(TeamMember).where(TeamMember.team_id == team_id))).all()
members = (
await session.exec(
select(TeamMember).where(
TeamMember.team_id == team_id,
~User.is_restricted_query(col(TeamMember.user_id)),
)
)
).all()
return TeamQueryResp(
team=members[0].team,
members=[await UserResp.from_db(m.user, session, include=BASE_INCLUDES) for m in members],
@@ -203,6 +219,9 @@ async def request_join_team(
team_id: Annotated[int, Path(..., description="战队 ID")],
current_user: ClientUser,
):
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
team = await session.get(Team, team_id)
if not team:
raise HTTPException(status_code=404, detail="Team not found")
@@ -233,6 +252,9 @@ async def handle_request(
current_user: ClientUser,
redis: Redis,
):
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
team = await session.get(Team, team_id)
if not team:
raise HTTPException(status_code=404, detail="Team not found")
@@ -274,6 +296,9 @@ async def kick_member(
current_user: ClientUser,
redis: Redis,
):
if await current_user.is_restricted(session):
raise HTTPException(status_code=403, detail="Your account is restricted and cannot perform this action.")
team = await session.get(Team, team_id)
if not team:
raise HTTPException(status_code=404, detail="Team not found")

View File

@@ -40,9 +40,13 @@ async def user_rename(
返回:
- 成功: None
"""
if await current_user.is_restricted(session):
# https://github.com/ppy/osu-web/blob/cae2fdf03cfb8c30c8e332cfb142e03188ceffef/app/Libraries/ChangeUsername.php#L48-L49
raise HTTPException(403, "Your account is restricted and cannot perform this action.")
samename_user = (await session.exec(select(exists()).where(User.username == new_name))).first()
if samename_user:
raise HTTPException(409, "Username Exisits")
raise HTTPException(409, "Username Exists")
errors = validate_username(new_name)
if errors:
raise HTTPException(403, "\n".join(errors))
@@ -80,6 +84,8 @@ async def update_userpage(
current_user: ClientUser,
):
"""更新用户页面内容"""
if await current_user.is_restricted(session):
raise HTTPException(403, "Your account is restricted and cannot perform this action.")
try:
# 处理BBCode内容