refactor(后端): 清掉 Django 遗留的死列与手工级联,角色字符串收成一份

三条迁移,一次部署(0008/0009 含 DROP COLUMN,需要 OJ2_ALLOW_DESTRUCTIVE=1):

- 0008 删 IP 相关:比赛 IP 白名单(前端本来就没有输入框,detail.vue 无条件置空)、
  submission.ip(前端从未显示过)、以及一次都没被调用过的 IP 限流桶。
  judge_server.ip 是运维数据,保留。
- 0009 删九个只有 Django 时代写过、OJ2 一次都没读过的列:user 的 auth_token /
  open_api / open_api_appkey / session_keys,user_profile 的 blog / github /
  school / major / language。open_api 后台连开关都没有,那段「已经开着就不重置
  appkey」的逻辑从上线起没进过 if。判据是「全仓零读取」而不是「看着没用」——
  raw_password 同样刺眼却是在用的,别一起清掉。
- 0010 给 17 条外键补上删除动作,不再是 Django 留下的一律 NO ACTION。父行消失后
  必然无意义、且不构成学生留痕的走 CASCADE(中间表、题单/教程/成就的组成部分、
  user_profile 与 user_stat);需要人看见的继续拦着——submission.problem_id、
  以及 user 的绝大多数外键,删用户撞外键会被 handler 翻译成「请改为禁用账号」,
  这是有意的:全 CASCADE 会静默抹掉成就与进度,而 submission.user_id 压根没有
  外键,结果是一半删一半留。六处手工级联随之删掉。

角色字符串收进 packages/contract/src/roles.ts:原先 ADMIN_ROLES / TEACHER_ROLES
在两个文件各抄一份、学生口径在四个文件各写一遍、前端 USER_TYPE 是第三份副本。
AuthUser.adminType 与 drizzle 的列都收窄成联合类型,二十多处 `=== "Super Admin"`
从此受编译器管着($type 是纯 TS 层的,generate 确认不产生任何 SQL 变更)。

顺带删掉 db/relations.ts —— drizzle-kit pull 的产物,全仓零引用。

一处行为变化:后台用户列表传非法的 ?type= 回 400,不再静默返回空列表;界面上的
下拉只有合法值,打不到这条。

验证:tsc / vue-tsc / vite build / check:routes 全过;三条迁移在 dev 库执行,
并逐条建 fixture 走 HTTP 接口验过删除连坐与拦截(题单五张子表连坐、user_badge
二级连坐、删有提交的题目仍 409、删有表情的用户仍 409)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeJoYc2t2d7cThVqMBYrBF
This commit is contained in:
2026-09-02 22:57:45 -06:00
parent e624c62502
commit 2c4d56b29a
41 changed files with 12081 additions and 491 deletions

View File

@@ -1,4 +1,6 @@
import {
STUDENT_ROLES,
adminTypeSchema,
adminUserListSchema,
adminUserRankSchema,
adminUserSchema,
@@ -7,6 +9,8 @@ import {
rankProfileSchema,
resetPasswordResponseSchema,
updateUserRequestSchema,
type AdminType,
type ProblemPermission,
} from "@oj2/contract"
import { randomInt } from "node:crypto"
import { and, asc, count, desc, eq, ilike, inArray, ne, or, sql } from "drizzle-orm"
@@ -50,7 +54,7 @@ function classNameOf(username: string): { ok: true; value: string | null } | { o
* 超管恒为 All、普通用户恒为 None、两种管理员取传入值或兜底 Own。
* 不这么做的话,把一个超管降级成普通用户后,他还留着 All 的题目权限。
*/
function normalizePermission(adminType: string, requested: string) {
function normalizePermission(adminType: AdminType, requested: ProblemPermission): ProblemPermission {
if (adminType === "Super Admin") return "All"
if (adminType === "Regular User") return "None"
return requested || "Own"
@@ -69,7 +73,6 @@ function serialize(row: {
realName: row.realName,
createTime: row.user.createTime,
lastLogin: row.user.lastLogin,
openApi: row.user.openApi,
isDisabled: row.user.isDisabled,
rawPassword: row.user.rawPassword,
className: row.user.className,
@@ -98,7 +101,7 @@ adminAccountRoutes.get("/rankings/users", requireSuperAdmin, async (c) => {
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
const keyword = c.req.query("keyword")?.trim()
const where = and(
inArray(schema.user.adminType, ["Regular User", "Student Admin"]),
inArray(schema.user.adminType, [...STUDENT_ROLES]),
eq(schema.user.isDisabled, false),
keyword ? ilike(schema.user.username, `%${keyword}%`) : undefined,
)
@@ -134,7 +137,13 @@ adminAccountRoutes.get("/users", requireSuperAdmin, async (c) => {
const filters = []
const type = c.req.query("type")?.trim()
const keyword = c.req.query("keyword")?.trim()
if (type) filters.push(eq(schema.user.adminType, type))
if (type) {
// 以前这里直接把 query 塞进 eq(),传个不存在的角色名只会静默返回空列表。
// 列加了 $type 之后编译器会拦下来,顺势改成校验:前端的下拉只有这四个值。
const parsedType = adminTypeSchema.safeParse(type)
if (!parsedType.success) return failure(c, 400, "invalid-request", "角色筛选值不合法")
filters.push(eq(schema.user.adminType, parsedType.data))
}
if (keyword) {
filters.push(or(
ilike(schema.user.username, `%${keyword}%`),
@@ -203,13 +212,6 @@ adminAccountRoutes.put("/users/:id", requireSuperAdmin, async (c) => {
patch.password = await hashPassword(data.password)
patch.rawPassword = data.password
}
if (data.openApi) {
// 已经开着就不重置 appkey否则每次保存用户都会把对方的 key 换掉
if (!existing.user.openApi) patch.openApiAppkey = randomBytes32()
} else {
patch.openApiAppkey = null
}
patch.openApi = data.openApi
await db.transaction(async (tx) => {
await tx.update(schema.user).set(patch).where(eq(schema.user.id, id))
@@ -276,12 +278,10 @@ adminAccountRoutes.post("/users", requireSuperAdmin, async (c) => {
rawPassword: item.raw,
email: item.email,
className: item.className,
adminType: "Regular User",
problemPermission: "None",
adminType: "Regular User" as const,
problemPermission: "None" as const,
createTime: new Date().toISOString(),
openApi: false,
isDisabled: false,
sessionKeys: [],
}))).returning({ id: schema.user.id, username: schema.user.username })
const byName = new Map(users.map((row) => [row.username, row.id]))
await tx.insert(schema.userProfile).values(prepared.map((item) => ({
@@ -308,12 +308,15 @@ adminAccountRoutes.delete("/users", requireSuperAdmin, async (c) => {
// 用户是被引用最广的一张表(提交、题目、比赛、公告……),级联删除牵连太大,
// 旧后端靠 Django 的应用层级联硬删。这里不复刻那个行为,改为让数据库拦下来:
// 撞外键说明该用户还有历史数据,应当禁用而不是删除。
//
// 所以 0010 那一批 CASCADE **有意跳过了 user 的绝大多数外键**:成就、表情、题单进度、
// AI 分析、站内信全都继续拦着。只有 user_profile 和 user_stat 走 CASCADE ——
// 一个是一对一附属、一个是可重算的统计缓存,都不构成「这人做过什么」的证据。
// 别顺手把这里也改成全 CASCADEsubmission.user_id 压根没有外键Django 那边就是个
// 裸 IntegerField全连坐的结果是成就没了、提交却留成孤儿行一半删一半留。
try {
const deleted = await db.transaction(async (tx) => {
await tx.delete(schema.userProfile).where(inArray(schema.userProfile.userId, parsed.data.ids))
return tx.delete(schema.user).where(inArray(schema.user.id, parsed.data.ids))
.returning({ id: schema.user.id })
})
const deleted = await db.delete(schema.user).where(inArray(schema.user.id, parsed.data.ids))
.returning({ id: schema.user.id })
return success(c, { deleted: deleted.length })
} catch {
return failure(c, 409, "user-in-use", "该用户还有提交、题目等历史数据,无法删除;请改为禁用账号")
@@ -333,8 +336,3 @@ adminAccountRoutes.post("/users/:id/reset-password", requireSuperAdmin, async (c
}).where(eq(schema.user.id, id))
return success(c, resetPasswordResponseSchema.parse({ password }))
})
function randomBytes32() {
return Array.from({ length: 32 }, () =>
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[randomInt(62)]).join("")
}