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:
@@ -2,6 +2,7 @@ import { randomBytes } from "node:crypto"
|
||||
import { extname, resolve } from "node:path"
|
||||
|
||||
import {
|
||||
STUDENT_ROLES,
|
||||
activityRankItemSchema,
|
||||
metricsSchema,
|
||||
problemRankSchema,
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
lt,
|
||||
lte,
|
||||
min,
|
||||
ne,
|
||||
or,
|
||||
sql,
|
||||
} from "drizzle-orm"
|
||||
@@ -74,12 +76,8 @@ accountRoutes.post("/users", async (c) => {
|
||||
lastLogin: null,
|
||||
createTime: now,
|
||||
adminType: "Regular User",
|
||||
authToken: null,
|
||||
openApi: false,
|
||||
openApiAppkey: null,
|
||||
isDisabled: false,
|
||||
problemPermission: "None",
|
||||
sessionKeys: [],
|
||||
className: null,
|
||||
}).returning({ id: schema.user.id })
|
||||
if (!created) throw new Error("User insert did not return an id")
|
||||
@@ -161,7 +159,7 @@ const LEADERBOARD_SIZE = 100
|
||||
|
||||
/** 入榜人群:正常状态的学生与学生管理员。教师和超管不参与排名。 */
|
||||
const leaderboardWhere = and(
|
||||
inArray(schema.user.adminType, ["Regular User", "Student Admin"]),
|
||||
inArray(schema.user.adminType, [...STUDENT_ROLES]),
|
||||
eq(schema.user.isDisabled, false),
|
||||
)
|
||||
|
||||
@@ -266,7 +264,7 @@ accountRoutes.get("/rankings/activity", async (c) => {
|
||||
gte(schema.submission.createTime, start),
|
||||
inArray(schema.submission.result, [JudgeStatus.ACCEPTED, JudgeStatus.AST_CHECK_FAILED]),
|
||||
eq(schema.user.isDisabled, false),
|
||||
sql`${schema.user.adminType} <> 'Super Admin'`,
|
||||
ne(schema.user.adminType, "Super Admin"),
|
||||
))
|
||||
.groupBy(schema.submission.username).orderBy(desc(countDistinct(schema.submission.problemId))).limit(10)
|
||||
return success(c, rows.map((row) => activityRankItemSchema.parse({ username: row.username, count: row.value })))
|
||||
|
||||
@@ -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 ——
|
||||
// 一个是一对一附属、一个是可重算的统计缓存,都不构成「这人做过什么」的证据。
|
||||
// 别顺手把这里也改成全 CASCADE:submission.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("")
|
||||
}
|
||||
|
||||
@@ -103,12 +103,9 @@ adminAchievementRoutes.put("/achievements/:id", requireSuperAdmin, async (c) =>
|
||||
|
||||
adminAchievementRoutes.delete("/achievements/:id", requireSuperAdmin, async (c) => {
|
||||
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
|
||||
// user_achievement 的外键同样是 NO ACTION(Django 的级联在应用层),先清子表
|
||||
const deleted = await db.transaction(async (tx) => {
|
||||
await tx.delete(schema.userAchievement).where(eq(schema.userAchievement.achievementId, id))
|
||||
return tx.delete(schema.achievement).where(eq(schema.achievement.id, id))
|
||||
.returning({ id: schema.achievement.id })
|
||||
})
|
||||
// 解锁记录随成就一起没:user_achievement.achievement_id 是 CASCADE(0010)
|
||||
const deleted = await db.delete(schema.achievement).where(eq(schema.achievement.id, id))
|
||||
.returning({ id: schema.achievement.id })
|
||||
if (deleted.length === 0) return failure(c, 404, "achievement-not-found", "成就不存在")
|
||||
return success(c, null)
|
||||
})
|
||||
|
||||
@@ -26,16 +26,6 @@ function ownedBy(user: AuthUser, contest: { createdById: number }) {
|
||||
return user.adminType === "Super Admin" || contest.createdById === user.id
|
||||
}
|
||||
|
||||
/** CIDR 校验。`ip_network(strict=False)` 的等价物:允许主机位非零,如 192.168.1.5/24 */
|
||||
function validCidr(value: string) {
|
||||
const [address, prefixText] = value.split("/")
|
||||
const octets = (address ?? "").split(".")
|
||||
if (octets.length !== 4) return false
|
||||
if (!octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)) return false
|
||||
if (prefixText === undefined) return true
|
||||
return /^\d{1,2}$/.test(prefixText) && Number(prefixText) <= 32
|
||||
}
|
||||
|
||||
async function serialize(row: {
|
||||
contest: typeof schema.contest.$inferSelect
|
||||
user: typeof schema.user.$inferSelect
|
||||
@@ -52,9 +42,6 @@ async function serialize(row: {
|
||||
lastUpdateTime: row.contest.lastUpdateTime,
|
||||
password: row.contest.password,
|
||||
visible: row.contest.visible,
|
||||
allowedIpRanges: Array.isArray(row.contest.allowedIpRanges)
|
||||
? row.contest.allowedIpRanges.filter((item): item is string => typeof item === "string")
|
||||
: [],
|
||||
createdBy: sampleUser(row.user, row.realName),
|
||||
status: contestStatus(row.contest),
|
||||
contestType: row.contest.password ? "Password Protected" : "Public",
|
||||
@@ -69,15 +56,12 @@ function selectContest(id: number) {
|
||||
.where(eq(schema.contest.id, id)).limit(1)
|
||||
}
|
||||
|
||||
/** 请求体里的时间与 CIDR 校验,创建和编辑共用 */
|
||||
function validatePayload(data: { startTime: string; endTime: string; allowedIpRanges: string[] }) {
|
||||
/** 请求体里的时间校验,创建和编辑共用 */
|
||||
function validatePayload(data: { startTime: string; endTime: string }) {
|
||||
const start = Date.parse(data.startTime)
|
||||
const end = Date.parse(data.endTime)
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end)) return "开始或结束时间不是合法的时间格式"
|
||||
if (end <= start) return "Start time must occur earlier than end time"
|
||||
for (const range of data.allowedIpRanges) {
|
||||
if (!validCidr(range)) return `${range} is not a valid cidr network`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -132,7 +116,6 @@ adminContestRoutes.post("/contests", requireTeacher, async (c) => {
|
||||
// 空串归一成 null,否则 contestType 会把「密码是空字符串」当成密码保护赛
|
||||
password: parsed.data.password || null,
|
||||
visible: parsed.data.visible,
|
||||
allowedIpRanges: parsed.data.allowedIpRanges,
|
||||
createdById: c.get("user")!.id,
|
||||
createTime: now,
|
||||
lastUpdateTime: now,
|
||||
@@ -162,7 +145,6 @@ adminContestRoutes.put("/contests/:id", requireTeacher, async (c) => {
|
||||
endTime: new Date(parsed.data.endTime).toISOString(),
|
||||
password: parsed.data.password || null,
|
||||
visible: parsed.data.visible,
|
||||
allowedIpRanges: parsed.data.allowedIpRanges,
|
||||
lastUpdateTime: new Date().toISOString(),
|
||||
}).where(eq(schema.contest.id, id))
|
||||
const [row] = await selectContest(id)
|
||||
@@ -196,7 +178,6 @@ adminContestRoutes.post("/contests/:id/clone", requireTeacher, async (c) => {
|
||||
password: null,
|
||||
// 克隆出来的一律不可见:时间是拍脑袋定的 10 分钟后,直接开放会让学生看到一场没准备好的赛
|
||||
visible: false,
|
||||
allowedIpRanges: original.contest.allowedIpRanges,
|
||||
startTime: start.toISOString(),
|
||||
endTime: end.toISOString(),
|
||||
createdById: me,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
STUDENT_ROLES,
|
||||
TUTORIAL_READ_SECONDS,
|
||||
learnExerciseAttemptSchema,
|
||||
learnExerciseProgressListSchema,
|
||||
@@ -24,9 +25,6 @@ import { queryInteger, rounded } from "../helpers"
|
||||
*/
|
||||
export const adminLearnRoutes = new Hono<AppEnv>()
|
||||
|
||||
/** 统计只算学生,不算老师和管理员自己 —— 和班级榜(classroom.ts)的口径一致 */
|
||||
const STUDENT_ROLES = ["Regular User", "Student Admin"]
|
||||
|
||||
function tutorialTypeOf(value: string | undefined) {
|
||||
return value === "c" ? "c" : "python"
|
||||
}
|
||||
@@ -61,7 +59,7 @@ function classCondition(value: string | null) {
|
||||
function studentCondition(value: string | null) {
|
||||
return and(
|
||||
eq(schema.user.isDisabled, false),
|
||||
inArray(schema.user.adminType, STUDENT_ROLES),
|
||||
inArray(schema.user.adminType, [...STUDENT_ROLES]),
|
||||
classCondition(value),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -423,7 +423,15 @@ adminProblemRoutes.delete("/problems/:id", requireProblemPermission, async (c) =
|
||||
})
|
||||
|
||||
/**
|
||||
* 删题的共用实现。子表全是 NO ACTION 外键,Django 的级联在应用层,得手工清。
|
||||
* 删题的共用实现。
|
||||
*
|
||||
* 「有提交就不让删」这道守卫**不能去掉**:submission.problem_id 是本次唯一**没有**
|
||||
* 改成 CASCADE 的题目外键(0010),就是为了让 12 万条历史提交不会被一次误删带走。
|
||||
* 守卫先拦,报的是人话;库级外键是最后一道保险。
|
||||
* 其余子表(problem_tags / problemset_problem / problemset_submission / reaction /
|
||||
* flowchart_submission)全部交给 CASCADE,原先这里手抄了四条 delete、且漏了
|
||||
* problemset_submission —— 那条漏清被上面的守卫挡着,一直没能真的发作。
|
||||
*
|
||||
* 测试用例目录**不删** —— 与旧后端一致(它把 rmtree 注释掉了)。
|
||||
* 删错了还能从磁盘捞回来,而误删的测试数据没有别处备份;孤儿目录另有清理入口。
|
||||
*/
|
||||
@@ -433,13 +441,7 @@ async function deleteProblem(c: Parameters<typeof success>[0], id: number) {
|
||||
if ((submissions?.value ?? 0) > 0) {
|
||||
return failure(c, 409, "problem-has-submissions", "该题目已有提交记录,不能删除")
|
||||
}
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.delete(schema.problemTags).where(eq(schema.problemTags.problemId, id))
|
||||
await tx.delete(schema.problemsetProblem).where(eq(schema.problemsetProblem.problemId, id))
|
||||
await tx.delete(schema.flowchartSubmission).where(eq(schema.flowchartSubmission.problemId, id))
|
||||
await tx.delete(schema.reaction).where(eq(schema.reaction.problemId, id))
|
||||
await tx.delete(schema.problem).where(eq(schema.problem.id, id))
|
||||
})
|
||||
await db.delete(schema.problem).where(eq(schema.problem.id, id))
|
||||
return success(c, null)
|
||||
}
|
||||
|
||||
|
||||
@@ -178,20 +178,9 @@ adminProblemSetRoutes.put("/problem-sets/:id/status", requireTeacher, async (c)
|
||||
adminProblemSetRoutes.delete("/problem-sets/:id", requireTeacher, async (c) => {
|
||||
const row = await loadOwned(c, c.get("user")!)
|
||||
if (!row) return failure(c, 404, "problem-set-not-found", "题单不存在")
|
||||
// 五张子表全是 NO ACTION 外键,Django 的级联在应用层。顺序不能反:
|
||||
// user_badge 挂在 problemset_badge 上,得先于 badge 删
|
||||
await db.transaction(async (tx) => {
|
||||
const badges = await tx.select({ id: schema.problemsetBadge.id }).from(schema.problemsetBadge)
|
||||
.where(eq(schema.problemsetBadge.problemsetId, row.id))
|
||||
if (badges.length) {
|
||||
await tx.delete(schema.userBadge).where(inArray(schema.userBadge.badgeId, badges.map((b) => b.id)))
|
||||
}
|
||||
await tx.delete(schema.problemsetBadge).where(eq(schema.problemsetBadge.problemsetId, row.id))
|
||||
await tx.delete(schema.problemsetSubmission).where(eq(schema.problemsetSubmission.problemsetId, row.id))
|
||||
await tx.delete(schema.problemsetProgress).where(eq(schema.problemsetProgress.problemsetId, row.id))
|
||||
await tx.delete(schema.problemsetProblem).where(eq(schema.problemsetProblem.problemsetId, row.id))
|
||||
await tx.delete(schema.problemset).where(eq(schema.problemset.id, row.id))
|
||||
})
|
||||
// 子表交给库级 CASCADE(0010):problemset_{badge,problem,progress,submission} 直接连坐,
|
||||
// user_badge 经 problemset_badge 二级连坐。原先这里手抄五条 delete 并要求「顺序不能反」。
|
||||
await db.delete(schema.problemset).where(eq(schema.problemset.id, row.id))
|
||||
return success(c, null)
|
||||
})
|
||||
|
||||
@@ -366,10 +355,8 @@ adminProblemSetRoutes.delete("/problem-sets/:id/badges/:badgeId", requireTeacher
|
||||
eq(schema.problemsetBadge.problemsetId, row.id),
|
||||
)).limit(1)
|
||||
if (!badge) return failure(c, 404, "badge-not-found", "奖章不存在")
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.delete(schema.userBadge).where(eq(schema.userBadge.badgeId, badge.id))
|
||||
await tx.delete(schema.problemsetBadge).where(eq(schema.problemsetBadge.id, badge.id))
|
||||
})
|
||||
// 获奖记录随奖章一起没:user_badge.badge_id 是 CASCADE(0010)
|
||||
await db.delete(schema.problemsetBadge).where(eq(schema.problemsetBadge.id, badge.id))
|
||||
return success(c, null)
|
||||
})
|
||||
|
||||
|
||||
@@ -81,7 +81,8 @@ adminTagRoutes.put("/problem-tags/:id", requireProblemPermission, async (c) => {
|
||||
problemtagId: target.id,
|
||||
})))
|
||||
}
|
||||
await tx.delete(schema.problemTags).where(eq(schema.problemTags.problemtagId, id))
|
||||
// 旧标签上剩下的关系行随标签一起没:problem_tags.problemtag_id 是 CASCADE(0010)。
|
||||
// 上面那批 insert 已经把题目挂到 target 上了,这里删掉的只是旧的那一份关系。
|
||||
await tx.delete(schema.problemTag).where(eq(schema.problemTag.id, id))
|
||||
return links.length
|
||||
})
|
||||
@@ -92,12 +93,9 @@ adminTagRoutes.put("/problem-tags/:id", requireProblemPermission, async (c) => {
|
||||
|
||||
adminTagRoutes.delete("/problem-tags/:id", requireProblemPermission, async (c) => {
|
||||
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
|
||||
// 中间表是 NO ACTION 外键,得先清关系再删标签
|
||||
const deleted = await db.transaction(async (tx) => {
|
||||
await tx.delete(schema.problemTags).where(eq(schema.problemTags.problemtagId, id))
|
||||
return tx.delete(schema.problemTag).where(eq(schema.problemTag.id, id))
|
||||
.returning({ id: schema.problemTag.id })
|
||||
})
|
||||
// 中间表 problem_tags 随标签一起清:problemtag_id 是 CASCADE(0010)
|
||||
const deleted = await db.delete(schema.problemTag).where(eq(schema.problemTag.id, id))
|
||||
.returning({ id: schema.problemTag.id })
|
||||
if (deleted.length === 0) return failure(c, 404, "tag-not-found", "标签不存在,请刷新后重试")
|
||||
return success(c, null)
|
||||
})
|
||||
|
||||
@@ -113,14 +113,11 @@ adminTutorialRoutes.put("/tutorials/:id/visibility", requireSuperAdmin, async (c
|
||||
|
||||
adminTutorialRoutes.delete("/tutorials/:id", requireSuperAdmin, async (c) => {
|
||||
const id = queryInteger(c.req.param("id"), 0, { min: 1 })
|
||||
// 必须先删练习。Django 的 on_delete=CASCADE 是**应用层**实现的,
|
||||
// 库里的外键实际是 NO ACTION(已核对 pg_constraint.confdeltype='a'),
|
||||
// 直接删教程会撞外键约束、变成 500。后台每个 DELETE 都要照此核一遍子表。
|
||||
const deleted = await db.transaction(async (tx) => {
|
||||
await tx.delete(schema.exercise).where(eq(schema.exercise.tutorialId, id))
|
||||
return tx.delete(schema.tutorial).where(eq(schema.tutorial.id, id))
|
||||
.returning({ id: schema.tutorial.id })
|
||||
})
|
||||
// 练习与学习留痕都随教程一起没:exercise.tutorial_id 与 tutorial_progress.tutorial_id
|
||||
// 都是库级 CASCADE。**加子表时要回来想一遍该 CASCADE 还是该拦住**,
|
||||
// 别默认新表会自己连坐 —— 0010 只改了当时存在的那批外键。
|
||||
const deleted = await db.delete(schema.tutorial).where(eq(schema.tutorial.id, id))
|
||||
.returning({ id: schema.tutorial.id })
|
||||
if (deleted.length === 0) return failure(c, 404, "tutorial-not-found", "Tutorial does not exist")
|
||||
return success(c, null)
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
STUDENT_ROLES,
|
||||
classComparisonRequestSchema,
|
||||
classComparisonResponseSchema,
|
||||
classComparisonSchema,
|
||||
@@ -32,7 +33,7 @@ interface ClassUser {
|
||||
async function loadClassUsers(classNames?: string[], gradePrefix?: string) {
|
||||
const filters = [
|
||||
eq(schema.user.isDisabled, false),
|
||||
inArray(schema.user.adminType, ["Regular User", "Student Admin"]),
|
||||
inArray(schema.user.adminType, [...STUDENT_ROLES]),
|
||||
sql`${schema.user.className} is not null`,
|
||||
]
|
||||
if (classNames) filters.push(inArray(schema.user.className, classNames))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
STUDENT_ROLES,
|
||||
contestAccessSchema,
|
||||
contestListSchema,
|
||||
contestPasswordRequestSchema,
|
||||
@@ -207,7 +208,7 @@ contestRoutes.get("/contests/:id/rank", optionalAuth, requireContestAccess("rank
|
||||
const contest = c.get("contest")!
|
||||
const limit = queryInteger(c.req.query("limit"), 10, { min: 1, max: 250 })
|
||||
const offset = queryInteger(c.req.query("offset"), 0, { min: 0 })
|
||||
const where = and(eq(schema.acmContestRank.contestId, contest.id), inArray(schema.user.adminType, ["Regular User", "Student Admin"]), eq(schema.user.isDisabled, false))
|
||||
const where = and(eq(schema.acmContestRank.contestId, contest.id), inArray(schema.user.adminType, [...STUDENT_ROLES]), eq(schema.user.isDisabled, false))
|
||||
const [totalRows, rows] = await Promise.all([
|
||||
db.select({ value: count() }).from(schema.acmContestRank).innerJoin(schema.user, eq(schema.acmContestRank.userId, schema.user.id)).where(where),
|
||||
db.select({ rank: schema.acmContestRank, user: schema.user, realName: schema.userProfile.realName })
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { sampleUserSchema, type SampleUser } from "@oj2/contract"
|
||||
import {
|
||||
ADMIN_ROLES,
|
||||
TEACHER_ROLES,
|
||||
sampleUserSchema,
|
||||
type SampleUser,
|
||||
} from "@oj2/contract"
|
||||
|
||||
import type { AuthUser } from "../auth/session"
|
||||
|
||||
@@ -64,14 +69,9 @@ export function queryInteger(
|
||||
return parsed
|
||||
}
|
||||
|
||||
// 角色判断一律用白名单,对齐旧后端 `account/models.py:65-73` 的 is_admin_role /
|
||||
// is_teacher_or_above 显式列举写法。
|
||||
//
|
||||
// 不要写成黑名单(`adminType !== "Regular User"`):当前四种角色下两者等价,但将来新增
|
||||
// 任何角色(助教、家长……)都会**默认拿到管理员权限**,包括 canViewSubmission 里的
|
||||
//「看所有人代码」。加角色的人多半想不到要回来改这里,白名单则会默认拒绝。
|
||||
const ADMIN_ROLES = ["Student Admin", "Teacher Admin", "Super Admin"]
|
||||
export const TEACHER_ROLES = ["Teacher Admin", "Super Admin"]
|
||||
// 角色白名单本身在 `@oj2/contract` 的 roles.ts,那是全仓唯一的定义处;
|
||||
// 这里只是把它们包成吃 AuthUser 的谓词。为什么必须是白名单,见那边的注释。
|
||||
export { TEACHER_ROLES }
|
||||
|
||||
// 注意:不要再加 isRegularUser(user) 这类「是普通用户才受限」的判断 ——
|
||||
// 匿名用户 user 为 null 时它返回 false,守卫会整体短路,匿名的权限反而大于登录学生。
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
canAccessContest,
|
||||
contestStatus,
|
||||
findVisibleContest,
|
||||
ipAllowed,
|
||||
isContestAdmin,
|
||||
requireContestAccess,
|
||||
type ContestEnv,
|
||||
@@ -59,11 +58,6 @@ function objectValue(value: unknown): Record<string, unknown> {
|
||||
: {}
|
||||
}
|
||||
|
||||
function requestIp(c: { req: { header(name: string): string | undefined } }) {
|
||||
const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim()
|
||||
return forwarded || c.req.header("x-real-ip") || null
|
||||
}
|
||||
|
||||
submissionRoutes.post("/submissions", requireAuth, async (c) => {
|
||||
const parsed = createSubmissionRequestSchema.safeParse(
|
||||
await c.req.json().catch(() => null),
|
||||
@@ -80,9 +74,6 @@ submissionRoutes.post("/submissions", requireAuth, async (c) => {
|
||||
const access = await canAccessContest(c, contest, "problems")
|
||||
if (!access.ok) return failure(c, access.code === "login-required" ? 401 : 403, access.code, access.message)
|
||||
if (contestStatus(contest) === "-1") return failure(c, 403, "contest-ended", "The contest has ended")
|
||||
if (!isContestAdmin(c.get("user"), contest) && !ipAllowed(requestIp(c), contest.allowedIpRanges)) {
|
||||
return failure(c, 403, "ip-not-allowed", "Your IP is not allowed in this contest")
|
||||
}
|
||||
contestId = contest.id
|
||||
}
|
||||
|
||||
@@ -138,7 +129,6 @@ submissionRoutes.post("/submissions", requireAuth, async (c) => {
|
||||
const user = c.get("user")!
|
||||
const submissionId = randomBytes(16).toString("hex")
|
||||
const createTime = new Date().toISOString()
|
||||
const ip = requestIp(c)
|
||||
|
||||
await db.insert(schema.submission).values({
|
||||
id: submissionId,
|
||||
@@ -153,7 +143,6 @@ submissionRoutes.post("/submissions", requireAuth, async (c) => {
|
||||
language: parsed.data.language,
|
||||
shared: false,
|
||||
statisticInfo: {},
|
||||
ip,
|
||||
contestId,
|
||||
})
|
||||
|
||||
@@ -508,10 +497,9 @@ async function submissionDetail(id: string, user: AuthUser) {
|
||||
? undefined
|
||||
: await problemSetJoinTimes(user.id, [row.submission.problemId])
|
||||
if (!canViewSubmission(user, row.submission, row.problem, row.contest, true, joinTimes)) return null
|
||||
// info(含每个测试点的 test_case 编号与 output_md5)与 ip 只给管理员,对齐旧后端:
|
||||
// info(含每个测试点的 test_case 编号与 output_md5)只给管理员,对齐旧后端:
|
||||
// submission/views/oj.py 用 is_admin_role() 在 SubmissionModelSerializer 与
|
||||
// SubmissionSafeModelSerializer(exclude=("info", "contest", "ip")) 之间二选一,
|
||||
// 把关的是角色,不是「是不是自己的提交」。
|
||||
// SubmissionSafeModelSerializer 之间二选一,把关的是角色,不是「是不是自己的提交」。
|
||||
const full = isAdminRole(user)
|
||||
return submissionDetailSchema.parse({
|
||||
id: row.submission.id,
|
||||
@@ -524,9 +512,7 @@ async function submissionDetail(id: string, user: AuthUser) {
|
||||
language: row.submission.language,
|
||||
shared: row.submission.shared,
|
||||
statisticInfo: objectValue(row.submission.statisticInfo),
|
||||
ip: full ? row.submission.ip : null,
|
||||
// contest 也在旧后端的排除名单里(exclude 的三个字段是 info / contest / ip),
|
||||
// 首轮修复只处理了 info 与 ip,这里补齐。
|
||||
// contest 也在旧后端的排除名单里,同样只给管理员
|
||||
contestId: full ? row.submission.contestId : null,
|
||||
problemId: row.submission.problemId,
|
||||
// problem 表本来就 join 了,不额外查库
|
||||
|
||||
Reference in New Issue
Block a user