659 lines
27 KiB
Python
659 lines
27 KiB
Python
from __future__ import annotations
|
|||
|
|
|
||
|
|
import math
|
||
|
|
import time
|
||
|
|
from collections import defaultdict, deque
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
from fastapi import APIRouter, HTTPException, Query, Request, status
|
||
|
|
from sqlalchemy import func, or_, select, text
|
||
|
|
|
||
|
|
from sakura_cloud.api.deps import AdminUser, DbSession, SuperAdminUser
|
||
|
|
from sakura_cloud.core.config import settings
|
||
|
|
from sakura_cloud.core.security import create_access_token, create_refresh_token, hash_password, verify_password
|
||
|
|
from sakura_cloud.models.admin import AdminAuditLog
|
||
|
|
from sakura_cloud.models.artwork import Artwork
|
||
|
|
from sakura_cloud.models.file import FileBlob, UploadSession, UserFile
|
||
|
|
from sakura_cloud.models.follow import CreatorFollow, UpdateAlert
|
||
|
|
from sakura_cloud.models.novel import Novel
|
||
|
|
from sakura_cloud.models.ocr import ArtworkOcrText
|
||
|
|
from sakura_cloud.models.push import PushDeviceToken
|
||
|
|
from sakura_cloud.models.user import User, UserRole
|
||
|
|
from sakura_cloud.models.mixins import utc_now
|
||
|
|
from sakura_cloud.schemas.admin import (
|
||
|
|
AdminAlertStatOut,
|
||
|
|
AdminAlertOut,
|
||
|
|
AdminAuditLogOut,
|
||
|
|
AdminArtworkOut,
|
||
|
|
AdminFileOut,
|
||
|
|
AdminFileStatOut,
|
||
|
|
AdminHealthOut,
|
||
|
|
AdminListResponse,
|
||
|
|
AdminLogLineOut,
|
||
|
|
AdminLoginRequest,
|
||
|
|
AdminMigrationOut,
|
||
|
|
AdminNovelOut,
|
||
|
|
AdminOcrTaskOut,
|
||
|
|
AdminPage,
|
||
|
|
AdminPushDeviceOut,
|
||
|
|
AdminStatsOut,
|
||
|
|
AdminTaskOut,
|
||
|
|
AdminUserOut,
|
||
|
|
AdminUserStatusUpdate,
|
||
|
|
AdminUserRoleUpdate,
|
||
|
|
AdminUserPasswordReset,
|
||
|
|
)
|
||
|
|
from sakura_cloud.schemas.auth import TokenPair
|
||
|
|
from sakura_cloud.schemas.common import ApiResponse
|
||
|
|
from sakura_cloud.services.audit import write_admin_audit_log
|
||
|
|
from sakura_cloud.services.ocr import run_ocr_for_artwork
|
||
|
|
from sakura_cloud.services.push import send_push_to_user
|
||
|
|
|
||
|
|
|
||
|
|
router = APIRouter()
|
||
|
|
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/login", response_model=ApiResponse[TokenPair])
|
||
|
|
def admin_login(payload: AdminLoginRequest, request: Request, db: DbSession) -> ApiResponse[TokenPair]:
|
||
|
|
_check_login_rate_limit(request)
|
||
|
|
login_id = payload.username_or_email.strip()
|
||
|
|
user = db.scalar(
|
||
|
|
select(User).where(
|
||
|
|
or_(
|
||
|
|
func.lower(User.username) == login_id.lower(),
|
||
|
|
func.lower(User.email) == login_id.lower(),
|
||
|
|
)
|
||
|
|
)
|
||
|
|
)
|
||
|
|
if (
|
||
|
|
user is None
|
||
|
|
or user.role not in {UserRole.ADMIN, UserRole.SUPER_ADMIN}
|
||
|
|
or not user.is_active
|
||
|
|
or not verify_password(payload.password, user.password_hash)
|
||
|
|
):
|
||
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid admin credentials")
|
||
|
|
write_admin_audit_log(db, user, action="admin_login", target_type="user", target_id=user.id, request=request)
|
||
|
|
return ApiResponse(
|
||
|
|
data=TokenPair(
|
||
|
|
access_token=create_access_token(user.id, user.token_version),
|
||
|
|
refresh_token=create_refresh_token(user.id, user.token_version),
|
||
|
|
)
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/dashboard", response_model=ApiResponse[AdminStatsOut])
|
||
|
|
def dashboard(_: AdminUser, db: DbSession) -> ApiResponse[AdminStatsOut]:
|
||
|
|
storage_used = int(db.scalar(select(func.coalesce(func.sum(FileBlob.file_size), 0))) or 0)
|
||
|
|
data = AdminStatsOut(
|
||
|
|
users=_count(db, User),
|
||
|
|
active_users=int(db.scalar(select(func.count()).select_from(User).where(User.is_active.is_(True))) or 0),
|
||
|
|
artworks=_count(db, Artwork),
|
||
|
|
novels=_count(db, Novel),
|
||
|
|
files=_count(db, FileBlob),
|
||
|
|
storage_used=storage_used,
|
||
|
|
uploads_pending=int(db.scalar(select(func.count()).select_from(UploadSession).where(UploadSession.status != "completed")) or 0),
|
||
|
|
ocr_pending=int(db.scalar(select(func.count()).select_from(ArtworkOcrText).where(ArtworkOcrText.status.in_(["pending", "running"]))) or 0),
|
||
|
|
ocr_failed=int(db.scalar(select(func.count()).select_from(ArtworkOcrText).where(ArtworkOcrText.status == "failed")) or 0),
|
||
|
|
push_devices=_count(db, PushDeviceToken),
|
||
|
|
follows=_count(db, CreatorFollow),
|
||
|
|
alerts=_count(db, UpdateAlert),
|
||
|
|
)
|
||
|
|
return ApiResponse(data=data)
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/users", response_model=ApiResponse[AdminListResponse[AdminUserOut]])
|
||
|
|
def list_users(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
q: str | None = Query(default=None, max_length=100),
|
||
|
|
role: str | None = Query(default=None, pattern="^(user|admin|super_admin)$"),
|
||
|
|
sort: str = Query(default="created_at", pattern="^(created_at|updated_at|username|storage_used)$"),
|
||
|
|
order: str = Query(default="desc", pattern="^(asc|desc)$"),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminUserOut]]:
|
||
|
|
query = select(User)
|
||
|
|
count_query = select(func.count()).select_from(User)
|
||
|
|
filters = []
|
||
|
|
if q:
|
||
|
|
like = f"%{q.strip()}%"
|
||
|
|
filters.append(or_(User.username.ilike(like), User.email.ilike(like)))
|
||
|
|
if role:
|
||
|
|
filters.append(User.role == _role_from_value(role))
|
||
|
|
for item in filters:
|
||
|
|
query = query.where(item)
|
||
|
|
count_query = count_query.where(item)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
order_col = getattr(User, sort)
|
||
|
|
if order == "desc":
|
||
|
|
order_col = order_col.desc()
|
||
|
|
rows = db.scalars(query.order_by(order_col).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
return ApiResponse(data=_page([AdminUserOut.model_validate(row) for row in rows], page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/users/{user_id}", response_model=ApiResponse[AdminUserOut])
|
||
|
|
def get_user(user_id: str, _: AdminUser, db: DbSession) -> ApiResponse[AdminUserOut]:
|
||
|
|
user = db.get(User, user_id)
|
||
|
|
if user is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||
|
|
return ApiResponse(data=AdminUserOut.model_validate(user))
|
||
|
|
|
||
|
|
|
||
|
|
@router.patch("/users/{user_id}/status", response_model=ApiResponse[AdminUserOut])
|
||
|
|
def set_user_status(
|
||
|
|
user_id: str,
|
||
|
|
payload: AdminUserStatusUpdate,
|
||
|
|
request: Request,
|
||
|
|
current_admin: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
) -> ApiResponse[AdminUserOut]:
|
||
|
|
user = db.get(User, user_id)
|
||
|
|
if user is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||
|
|
_ensure_can_operate_user(current_admin, user, desired_active=payload.is_active)
|
||
|
|
user.is_active = payload.is_active
|
||
|
|
user.disabled_at = None if payload.is_active else utc_now()
|
||
|
|
user.disabled_reason = None if payload.is_active else payload.reason
|
||
|
|
user.token_version += 1
|
||
|
|
db.commit()
|
||
|
|
db.refresh(user)
|
||
|
|
write_admin_audit_log(
|
||
|
|
db,
|
||
|
|
current_admin,
|
||
|
|
action="enable_user" if payload.is_active else "disable_user",
|
||
|
|
target_type="user",
|
||
|
|
target_id=user.id,
|
||
|
|
request=request,
|
||
|
|
detail={"is_active": payload.is_active, "reason": payload.reason},
|
||
|
|
)
|
||
|
|
return ApiResponse(data=AdminUserOut.model_validate(user))
|
||
|
|
|
||
|
|
|
||
|
|
@router.patch("/users/{user_id}/role", response_model=ApiResponse[AdminUserOut])
|
||
|
|
def set_user_role(
|
||
|
|
user_id: str,
|
||
|
|
payload: AdminUserRoleUpdate,
|
||
|
|
request: Request,
|
||
|
|
current_admin: SuperAdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
) -> ApiResponse[AdminUserOut]:
|
||
|
|
user = db.get(User, user_id)
|
||
|
|
if user is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||
|
|
new_role = _role_from_value(payload.role)
|
||
|
|
if user.id == current_admin.id and new_role != UserRole.SUPER_ADMIN:
|
||
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot demote yourself")
|
||
|
|
if new_role != UserRole.SUPER_ADMIN and user.role == UserRole.SUPER_ADMIN and _super_admin_count(db) <= 1:
|
||
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="At least one super admin is required")
|
||
|
|
user.role = new_role
|
||
|
|
user.token_version += 1
|
||
|
|
db.commit()
|
||
|
|
db.refresh(user)
|
||
|
|
write_admin_audit_log(db, current_admin, action="change_user_role", target_type="user", target_id=user.id, request=request, detail={"role": payload.role})
|
||
|
|
return ApiResponse(data=AdminUserOut.model_validate(user))
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/users/{user_id}/reset-password", response_model=ApiResponse[dict[str, bool]])
|
||
|
|
def reset_user_password(
|
||
|
|
user_id: str,
|
||
|
|
payload: AdminUserPasswordReset,
|
||
|
|
request: Request,
|
||
|
|
current_admin: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
) -> ApiResponse[dict[str, bool]]:
|
||
|
|
user = db.get(User, user_id)
|
||
|
|
if user is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||
|
|
_ensure_can_operate_user(current_admin, user)
|
||
|
|
user.password_hash = hash_password(payload.new_password)
|
||
|
|
user.token_version += 1
|
||
|
|
db.commit()
|
||
|
|
write_admin_audit_log(db, current_admin, action="reset_user_password", target_type="user", target_id=user.id, request=request)
|
||
|
|
return ApiResponse(data={"ok": True})
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/users/{user_id}/files", response_model=ApiResponse[AdminListResponse[AdminFileOut]])
|
||
|
|
def user_files(user_id: str, _: AdminUser, db: DbSession, page: int = Query(default=1, ge=1), limit: int = Query(default=30, ge=1, le=100)):
|
||
|
|
if db.get(User, user_id) is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||
|
|
return _list_files(db, page=page, limit=limit, user_id=user_id)
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/files/stats", response_model=ApiResponse[list[AdminFileStatOut]])
|
||
|
|
def file_stats(_: AdminUser, db: DbSession) -> ApiResponse[list[AdminFileStatOut]]:
|
||
|
|
rows = db.execute(
|
||
|
|
select(FileBlob.mime_type, func.count(FileBlob.sha256), func.coalesce(func.sum(FileBlob.file_size), 0)).group_by(FileBlob.mime_type)
|
||
|
|
).all()
|
||
|
|
return ApiResponse(data=[AdminFileStatOut(mime_type=row[0], files=int(row[1]), bytes=int(row[2] or 0)) for row in rows])
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/files", response_model=ApiResponse[AdminListResponse[AdminFileOut]])
|
||
|
|
def list_files(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
user_id: str | None = Query(default=None, max_length=36),
|
||
|
|
mime_type: str | None = Query(default=None, max_length=50),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminFileOut]]:
|
||
|
|
return _list_files(db, page=page, limit=limit, user_id=user_id, mime_type=mime_type)
|
||
|
|
|
||
|
|
|
||
|
|
@router.delete("/files/{file_id}", response_model=ApiResponse[dict[str, bool]])
|
||
|
|
def delete_file(file_id: str, request: Request, current_admin: AdminUser, db: DbSession) -> ApiResponse[dict[str, bool]]:
|
||
|
|
row = db.get(UserFile, file_id)
|
||
|
|
if row is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="File not found")
|
||
|
|
db.delete(row)
|
||
|
|
db.commit()
|
||
|
|
write_admin_audit_log(db, current_admin, action="delete_file", target_type="file", target_id=file_id, request=request)
|
||
|
|
return ApiResponse(data={"ok": True})
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/gallery", response_model=ApiResponse[AdminListResponse[AdminArtworkOut]])
|
||
|
|
def admin_gallery(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
user_id: str | None = Query(default=None, max_length=36),
|
||
|
|
platform: str | None = Query(default=None, max_length=20),
|
||
|
|
content_type: str | None = Query(default=None, max_length=20),
|
||
|
|
q: str | None = Query(default=None, max_length=100),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminArtworkOut]]:
|
||
|
|
query = select(Artwork)
|
||
|
|
count_query = select(func.count()).select_from(Artwork)
|
||
|
|
filters = []
|
||
|
|
if user_id:
|
||
|
|
filters.append(Artwork.user_id == user_id)
|
||
|
|
if platform:
|
||
|
|
filters.append(Artwork.source_platform == platform)
|
||
|
|
if content_type:
|
||
|
|
filters.append(Artwork.content_type == content_type)
|
||
|
|
if q:
|
||
|
|
like = f"%{q.strip()}%"
|
||
|
|
filters.append(or_(Artwork.title.ilike(like), Artwork.author.ilike(like)))
|
||
|
|
for item in filters:
|
||
|
|
query = query.where(item)
|
||
|
|
count_query = count_query.where(item)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
rows = db.scalars(query.order_by(Artwork.updated_at.desc()).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
return ApiResponse(data=_page([AdminArtworkOut.model_validate(row) for row in rows], page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/novels", response_model=ApiResponse[AdminListResponse[AdminNovelOut]])
|
||
|
|
def admin_novels(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
user_id: str | None = Query(default=None, max_length=36),
|
||
|
|
q: str | None = Query(default=None, max_length=100),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminNovelOut]]:
|
||
|
|
query = select(Novel)
|
||
|
|
count_query = select(func.count()).select_from(Novel)
|
||
|
|
filters = []
|
||
|
|
if user_id:
|
||
|
|
filters.append(Novel.user_id == user_id)
|
||
|
|
if q:
|
||
|
|
like = f"%{q.strip()}%"
|
||
|
|
filters.append(or_(Novel.title.ilike(like), Novel.author.ilike(like), Novel.series_title.ilike(like)))
|
||
|
|
for item in filters:
|
||
|
|
query = query.where(item)
|
||
|
|
count_query = count_query.where(item)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
rows = db.scalars(query.order_by(Novel.updated_at.desc()).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
return ApiResponse(data=_page([AdminNovelOut.model_validate(row) for row in rows], page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/uploads", response_model=ApiResponse[AdminListResponse[AdminTaskOut]])
|
||
|
|
def upload_tasks(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
status_filter: str | None = Query(default=None, alias="status", max_length=30),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminTaskOut]]:
|
||
|
|
query = select(UploadSession)
|
||
|
|
count_query = select(func.count()).select_from(UploadSession)
|
||
|
|
if status_filter:
|
||
|
|
query = query.where(UploadSession.status == status_filter)
|
||
|
|
count_query = count_query.where(UploadSession.status == status_filter)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
rows = db.scalars(query.order_by(UploadSession.updated_at.desc()).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
items = [
|
||
|
|
AdminTaskOut(
|
||
|
|
id=row.id,
|
||
|
|
user_id=row.user_id,
|
||
|
|
status=row.status,
|
||
|
|
file_name=Path(row.file_name).name if row.file_name else None,
|
||
|
|
resource_type=row.resource_type,
|
||
|
|
file_size=row.file_size,
|
||
|
|
updated_at=row.updated_at,
|
||
|
|
)
|
||
|
|
for row in rows
|
||
|
|
]
|
||
|
|
return ApiResponse(data=_page(items, page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/ocr/tasks", response_model=ApiResponse[AdminListResponse[AdminOcrTaskOut]])
|
||
|
|
def ocr_tasks(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
status_filter: str | None = Query(default=None, alias="status", pattern="^(pending|running|done|failed)$"),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminOcrTaskOut]]:
|
||
|
|
query = select(ArtworkOcrText)
|
||
|
|
count_query = select(func.count()).select_from(ArtworkOcrText)
|
||
|
|
if status_filter:
|
||
|
|
query = query.where(ArtworkOcrText.status == status_filter)
|
||
|
|
count_query = count_query.where(ArtworkOcrText.status == status_filter)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
rows = db.scalars(query.order_by(ArtworkOcrText.updated_at.desc()).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
items = [
|
||
|
|
AdminOcrTaskOut(
|
||
|
|
id=row.id,
|
||
|
|
user_id=row.user_id,
|
||
|
|
artwork_id=row.artwork_id,
|
||
|
|
status=row.status,
|
||
|
|
language=row.language,
|
||
|
|
confidence=row.confidence,
|
||
|
|
engine=row.engine,
|
||
|
|
attempts=row.attempts,
|
||
|
|
error=row.error,
|
||
|
|
text_length=len(row.ocr_text or ""),
|
||
|
|
updated_at=row.updated_at,
|
||
|
|
)
|
||
|
|
for row in rows
|
||
|
|
]
|
||
|
|
return ApiResponse(data=_page(items, page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/ocr/tasks/{task_id}/retry", response_model=ApiResponse[AdminOcrTaskOut])
|
||
|
|
def retry_ocr_task(task_id: str, request: Request, current_admin: AdminUser, db: DbSession) -> ApiResponse[AdminOcrTaskOut]:
|
||
|
|
task = db.get(ArtworkOcrText, task_id)
|
||
|
|
if task is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="OCR task not found")
|
||
|
|
artwork = db.get(Artwork, task.artwork_id)
|
||
|
|
if artwork is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Artwork not found")
|
||
|
|
task.status = "pending"
|
||
|
|
task.error = None
|
||
|
|
db.commit()
|
||
|
|
row = run_ocr_for_artwork(db, artwork)
|
||
|
|
write_admin_audit_log(db, current_admin, action="retry_ocr", target_type="ocr_task", target_id=task_id, request=request)
|
||
|
|
return ApiResponse(data=_ocr_out(row))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/push/devices", response_model=ApiResponse[AdminListResponse[AdminPushDeviceOut]])
|
||
|
|
def push_devices(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminPushDeviceOut]]:
|
||
|
|
total = int(db.scalar(select(func.count()).select_from(PushDeviceToken)) or 0)
|
||
|
|
rows = db.scalars(select(PushDeviceToken).order_by(PushDeviceToken.updated_at.desc()).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
items = [_push_device_out(row) for row in rows]
|
||
|
|
return ApiResponse(data=_page(items, page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/push/logs", response_model=ApiResponse[list[AdminLogLineOut]])
|
||
|
|
def push_logs(_: AdminUser, limit: int = Query(default=100, ge=1, le=500)) -> ApiResponse[list[AdminLogLineOut]]:
|
||
|
|
return ApiResponse(data=_read_filtered_log_lines(("FCM", "push"), limit=limit))
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/push/test", response_model=ApiResponse[dict[str, int]])
|
||
|
|
def send_test_push(request: Request, current_admin: AdminUser, db: DbSession, user_id: str = Query(max_length=36)) -> ApiResponse[dict[str, int]]:
|
||
|
|
user = db.get(User, user_id)
|
||
|
|
if user is None:
|
||
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||
|
|
summary = send_push_to_user(db, user_id, "Sakura Cloud test push", "Admin test push has been sent.", {"kind": "admin_test"})
|
||
|
|
write_admin_audit_log(db, current_admin, action="send_test_push", target_type="user", target_id=user_id, request=request)
|
||
|
|
return ApiResponse(data={"attempted": summary.attempted, "sent": summary.sent, "disabled": summary.disabled, "failed": summary.failed})
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/alerts/stats", response_model=ApiResponse[list[AdminAlertStatOut]])
|
||
|
|
def alert_stats(_: AdminUser, db: DbSession) -> ApiResponse[list[AdminAlertStatOut]]:
|
||
|
|
rows = db.execute(
|
||
|
|
select(UpdateAlert.platform, func.count(UpdateAlert.id)).group_by(UpdateAlert.platform)
|
||
|
|
).all()
|
||
|
|
data = []
|
||
|
|
for platform, total in rows:
|
||
|
|
unread = int(db.scalar(select(func.count()).select_from(UpdateAlert).where(UpdateAlert.platform == platform, UpdateAlert.is_read.is_(False))) or 0)
|
||
|
|
data.append(AdminAlertStatOut(platform=platform, alerts=int(total), unread=unread))
|
||
|
|
return ApiResponse(data=data)
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/alerts", response_model=ApiResponse[AdminListResponse[AdminAlertOut]])
|
||
|
|
def admin_alerts(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
user_id: str | None = Query(default=None, max_length=36),
|
||
|
|
platform: str | None = Query(default=None, max_length=20),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminAlertOut]]:
|
||
|
|
query = select(UpdateAlert)
|
||
|
|
count_query = select(func.count()).select_from(UpdateAlert)
|
||
|
|
filters = []
|
||
|
|
if user_id:
|
||
|
|
filters.append(UpdateAlert.user_id == user_id)
|
||
|
|
if platform:
|
||
|
|
filters.append(UpdateAlert.platform == platform)
|
||
|
|
for item in filters:
|
||
|
|
query = query.where(item)
|
||
|
|
count_query = count_query.where(item)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
rows = db.scalars(query.order_by(UpdateAlert.created_at.desc()).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
return ApiResponse(data=_page([AdminAlertOut.model_validate(row) for row in rows], page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/system/health", response_model=ApiResponse[AdminHealthOut])
|
||
|
|
def admin_system_health(current_admin: AdminUser) -> ApiResponse[AdminHealthOut]:
|
||
|
|
return admin_health(current_admin)
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/health", response_model=ApiResponse[AdminHealthOut])
|
||
|
|
def admin_health(_: AdminUser) -> ApiResponse[AdminHealthOut]:
|
||
|
|
return ApiResponse(
|
||
|
|
data=AdminHealthOut(
|
||
|
|
ok=True,
|
||
|
|
debug=settings.debug,
|
||
|
|
auto_migrate_on_startup=settings.auto_migrate_on_startup,
|
||
|
|
database=_redact_url(settings.database_url),
|
||
|
|
storage_root=str(Path(settings.storage_root).name or "storage"),
|
||
|
|
log_dir=str(Path(settings.log_dir).name or "logs"),
|
||
|
|
app_version=settings.app_version,
|
||
|
|
)
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/logs/errors", response_model=ApiResponse[list[AdminLogLineOut]])
|
||
|
|
def error_logs(
|
||
|
|
_: AdminUser,
|
||
|
|
file: str = Query(default="error.log", pattern=r"^[A-Za-z0-9_.-]+$"),
|
||
|
|
limit: int = Query(default=100, ge=1, le=500),
|
||
|
|
) -> ApiResponse[list[AdminLogLineOut]]:
|
||
|
|
path = (Path(settings.log_dir) / file).resolve()
|
||
|
|
root = Path(settings.log_dir).resolve()
|
||
|
|
if not str(path).startswith(str(root)) or not path.is_file():
|
||
|
|
return ApiResponse(data=[])
|
||
|
|
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()[-limit:]
|
||
|
|
return ApiResponse(data=[AdminLogLineOut(line_no=index + 1, text=_redact_log_line(line)) for index, line in enumerate(lines)])
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/migrations/version", response_model=ApiResponse[AdminMigrationOut])
|
||
|
|
def migration_version(_: AdminUser, db: DbSession) -> ApiResponse[AdminMigrationOut]:
|
||
|
|
try:
|
||
|
|
version = db.execute(text("SELECT version_num FROM alembic_version LIMIT 1")).scalar()
|
||
|
|
except Exception:
|
||
|
|
version = None
|
||
|
|
return ApiResponse(data=AdminMigrationOut(version=str(version) if version else None))
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/audit-logs", response_model=ApiResponse[AdminListResponse[AdminAuditLogOut]])
|
||
|
|
def audit_logs(
|
||
|
|
_: AdminUser,
|
||
|
|
db: DbSession,
|
||
|
|
page: int = Query(default=1, ge=1),
|
||
|
|
limit: int = Query(default=30, ge=1, le=100),
|
||
|
|
action: str | None = Query(default=None, max_length=100),
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminAuditLogOut]]:
|
||
|
|
query = select(AdminAuditLog)
|
||
|
|
count_query = select(func.count()).select_from(AdminAuditLog)
|
||
|
|
if action:
|
||
|
|
query = query.where(AdminAuditLog.action == action)
|
||
|
|
count_query = count_query.where(AdminAuditLog.action == action)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
rows = db.scalars(query.order_by(AdminAuditLog.created_at.desc()).offset((page - 1) * limit).limit(limit)).all()
|
||
|
|
return ApiResponse(data=_page([AdminAuditLogOut.model_validate(row) for row in rows], page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
def _count(db: DbSession, model: object) -> int:
|
||
|
|
return int(db.scalar(select(func.count()).select_from(model)) or 0)
|
||
|
|
|
||
|
|
|
||
|
|
def _page(items: list, page: int, limit: int, total: int) -> AdminListResponse:
|
||
|
|
return AdminListResponse(items=items, pagination=AdminPage(page=page, limit=limit, total=total))
|
||
|
|
|
||
|
|
|
||
|
|
def _role_from_value(value: str) -> UserRole:
|
||
|
|
return {
|
||
|
|
"user": UserRole.USER,
|
||
|
|
"admin": UserRole.ADMIN,
|
||
|
|
"super_admin": UserRole.SUPER_ADMIN,
|
||
|
|
}[value]
|
||
|
|
|
||
|
|
|
||
|
|
def _ensure_can_operate_user(admin: User, target: User, *, desired_active: bool | None = None) -> None:
|
||
|
|
if target.role == UserRole.SUPER_ADMIN and admin.role != UserRole.SUPER_ADMIN:
|
||
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Cannot operate super admin")
|
||
|
|
if target.id == admin.id and desired_active is False:
|
||
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot disable yourself")
|
||
|
|
|
||
|
|
|
||
|
|
def _super_admin_count(db: DbSession) -> int:
|
||
|
|
return int(db.scalar(select(func.count()).select_from(User).where(User.role == UserRole.SUPER_ADMIN)) or 0)
|
||
|
|
|
||
|
|
|
||
|
|
def _list_files(
|
||
|
|
db: DbSession,
|
||
|
|
*,
|
||
|
|
page: int,
|
||
|
|
limit: int,
|
||
|
|
user_id: str | None = None,
|
||
|
|
mime_type: str | None = None,
|
||
|
|
) -> ApiResponse[AdminListResponse[AdminFileOut]]:
|
||
|
|
query = select(UserFile, FileBlob).join(FileBlob, UserFile.file_sha256 == FileBlob.sha256)
|
||
|
|
count_query = select(func.count()).select_from(UserFile).join(FileBlob, UserFile.file_sha256 == FileBlob.sha256)
|
||
|
|
filters = []
|
||
|
|
if user_id:
|
||
|
|
filters.append(UserFile.user_id == user_id)
|
||
|
|
if mime_type:
|
||
|
|
filters.append(FileBlob.mime_type == mime_type)
|
||
|
|
for item in filters:
|
||
|
|
query = query.where(item)
|
||
|
|
count_query = count_query.where(item)
|
||
|
|
total = int(db.scalar(count_query) or 0)
|
||
|
|
rows = db.execute(
|
||
|
|
query.order_by(UserFile.uploaded_at.desc())
|
||
|
|
.offset((page - 1) * limit)
|
||
|
|
.limit(limit)
|
||
|
|
).all()
|
||
|
|
items = [
|
||
|
|
AdminFileOut(
|
||
|
|
id=user_file.id,
|
||
|
|
user_id=user_file.user_id,
|
||
|
|
original_name=Path(user_file.original_name).name,
|
||
|
|
sha256_prefix=blob.sha256[:12],
|
||
|
|
file_size=blob.file_size,
|
||
|
|
mime_type=blob.mime_type,
|
||
|
|
uploaded_at=user_file.uploaded_at,
|
||
|
|
)
|
||
|
|
for user_file, blob in rows
|
||
|
|
]
|
||
|
|
return ApiResponse(data=_page(items, page, limit, total))
|
||
|
|
|
||
|
|
|
||
|
|
def _ocr_out(row: ArtworkOcrText) -> AdminOcrTaskOut:
|
||
|
|
return AdminOcrTaskOut(
|
||
|
|
id=row.id,
|
||
|
|
user_id=row.user_id,
|
||
|
|
artwork_id=row.artwork_id,
|
||
|
|
status=row.status,
|
||
|
|
language=row.language,
|
||
|
|
confidence=row.confidence,
|
||
|
|
engine=row.engine,
|
||
|
|
attempts=row.attempts,
|
||
|
|
error=row.error,
|
||
|
|
text_length=len(row.ocr_text or ""),
|
||
|
|
updated_at=row.updated_at,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def _push_device_out(row: PushDeviceToken) -> AdminPushDeviceOut:
|
||
|
|
return AdminPushDeviceOut(
|
||
|
|
id=row.id,
|
||
|
|
user_id=row.user_id,
|
||
|
|
device_id=row.device_id,
|
||
|
|
platform=row.platform,
|
||
|
|
token_tail=row.fcm_token[-8:] if row.fcm_token else "",
|
||
|
|
is_active=row.is_active,
|
||
|
|
last_seen_at=row.last_seen_at,
|
||
|
|
updated_at=row.updated_at,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def _check_login_rate_limit(request: Request) -> None:
|
||
|
|
key = request.client.host if request.client is not None else "unknown"
|
||
|
|
now = time.time()
|
||
|
|
attempts = _login_attempts[key]
|
||
|
|
while attempts and now - attempts[0] > 60:
|
||
|
|
attempts.popleft()
|
||
|
|
if len(attempts) >= settings.admin_login_rate_limit_per_minute:
|
||
|
|
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many admin login attempts")
|
||
|
|
attempts.append(now)
|
||
|
|
|
||
|
|
|
||
|
|
def _redact_url(value: str) -> str:
|
||
|
|
if "@" not in value:
|
||
|
|
return value
|
||
|
|
prefix, suffix = value.rsplit("@", 1)
|
||
|
|
scheme = prefix.split(":", 1)[0]
|
||
|
|
return f"{scheme}:***@{suffix}"
|
||
|
|
|
||
|
|
|
||
|
|
def _redact_log_line(line: str) -> str:
|
||
|
|
text_value = line
|
||
|
|
for marker in ("Bearer ", "token=", "password=", "cookie=", "secret="):
|
||
|
|
index = text_value.lower().find(marker.lower())
|
||
|
|
if index >= 0:
|
||
|
|
text_value = text_value[: index + len(marker)] + "***"
|
||
|
|
return text_value
|
||
|
|
|
||
|
|
|
||
|
|
def _read_filtered_log_lines(keywords: tuple[str, ...], *, limit: int) -> list[AdminLogLineOut]:
|
||
|
|
root = Path(settings.log_dir).resolve()
|
||
|
|
if not root.is_dir():
|
||
|
|
return []
|
||
|
|
candidates = sorted(root.glob("*.log"), key=lambda item: item.stat().st_mtime if item.exists() else 0, reverse=True)
|
||
|
|
matched: list[str] = []
|
||
|
|
lowered_keywords = tuple(item.lower() for item in keywords)
|
||
|
|
for path in candidates[:5]:
|
||
|
|
try:
|
||
|
|
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
||
|
|
except OSError:
|
||
|
|
continue
|
||
|
|
for line in reversed(lines):
|
||
|
|
lowered = line.lower()
|
||
|
|
if any(keyword in lowered for keyword in lowered_keywords):
|
||
|
|
matched.append(_redact_log_line(line))
|
||
|
|
if len(matched) >= limit:
|
||
|
|
break
|
||
|
|
if len(matched) >= limit:
|
||
|
|
break
|
||
|
|
matched.reverse()
|
||
|
|
return [AdminLogLineOut(line_no=index + 1, text=line) for index, line in enumerate(matched)]
|