站长反馈仍然无法编辑其它用户。上一版只把**小程序端**的状态改成小写, 但如果小程序没重新编译(或用的还是旧版本),发上来的仍是 `ACTIVE`, 服务端 `['active','withdrawn','graduate'].includes(status)` 依旧不通过 → 400 「用户状态只能是 active, withdrawn 或 graduate」——编辑任何用户都会失败。 这版把容忍度放到**服务端**,与客户端版本解耦: - 新增 server/utils/user-status.ts: · USER_STATUSES = ['active','withdrawn','graduate'] · normalizeUserStatus() 大小写不敏感('ACTIVE' / ' Active ' → 'active'),认不出返回 null · USER_STATUS_RULE_MESSAGE 统一文案 - [id].put.ts:状态改用归一化值;另修正"自己只能改姓名"里的状态比较也忽略大小写 - [id]/status.put.ts、batch-status.put.ts:同样归一化; 并修掉一个我自己引入的隐患(把归一化结果赋回 const 变量 → TypeError), batch-status 之前被误写成不存在的 statusesRaw,一并改正 效果:无论小程序是否重新编译,管理员都能编辑其它用户(含历史拼音账号只改年级)。
137 lines
3.6 KiB
TypeScript
137 lines
3.6 KiB
TypeScript
import { createError, defineEventHandler, getRouterParam, readBody } from 'h3'
|
|
import { normalizeUserStatus, USER_STATUS_RULE_MESSAGE } from '~~/server/utils/user-status'
|
|
import { db } from '~/drizzle/db'
|
|
import { users, userStatusLogs } from '~/drizzle/schema'
|
|
import { eq } from 'drizzle-orm'
|
|
import { getBeijingTime } from '~/utils/timeUtils'
|
|
import { getStatusText } from '~~/server/utils/user'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
// 检查认证和权限
|
|
const user = event.context.user
|
|
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
|
throw createError({
|
|
statusCode: 403,
|
|
statusMessage: '没有权限访问'
|
|
})
|
|
}
|
|
|
|
const userId = getRouterParam(event, 'id')
|
|
const body = await readBody(event)
|
|
const { status: rawStatus, reason } = body
|
|
|
|
// 验证必填字段;状态大小写不敏感(客户端历史版本发大写 ACTIVE 也能用)
|
|
const status = normalizeUserStatus(rawStatus)
|
|
if (!status) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: USER_STATUS_RULE_MESSAGE
|
|
})
|
|
}
|
|
|
|
if (!reason || reason.trim().length === 0) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: '变更原因为必填项'
|
|
})
|
|
}
|
|
|
|
// 检查用户是否存在
|
|
const existingUser = await db
|
|
.select({
|
|
id: users.id,
|
|
name: users.name,
|
|
username: users.username,
|
|
status: users.status,
|
|
role: users.role
|
|
})
|
|
.from(users)
|
|
.where(eq(users.id, parseInt(userId)))
|
|
.limit(1)
|
|
|
|
if (existingUser.length === 0) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: '用户不存在'
|
|
})
|
|
}
|
|
|
|
const targetUser = existingUser[0]
|
|
|
|
// 检查是否为学生用户
|
|
if (targetUser.role !== 'USER') {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: '只能修改学生用户的状态'
|
|
})
|
|
}
|
|
|
|
// 检查状态是否有变化
|
|
if (targetUser.status === status) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: '用户状态未发生变化'
|
|
})
|
|
}
|
|
|
|
const currentTime = getBeijingTime()
|
|
const oldStatus = targetUser.status
|
|
|
|
// 开始事务
|
|
await db.transaction(async (tx) => {
|
|
// 更新用户状态
|
|
await tx
|
|
.update(users)
|
|
.set({
|
|
status: status,
|
|
statusChangedAt: currentTime,
|
|
statusChangedBy: user.id
|
|
})
|
|
.where(eq(users.id, parseInt(userId)))
|
|
|
|
// 记录状态变更日志
|
|
await tx.insert(userStatusLogs).values({
|
|
userId: parseInt(userId),
|
|
oldStatus: oldStatus,
|
|
newStatus: status,
|
|
reason: reason.trim(),
|
|
operatorId: user.id,
|
|
createdAt: currentTime
|
|
})
|
|
})
|
|
|
|
// 清除相关缓存
|
|
try {
|
|
const { cache } = await import('~~/server/utils/cache-helpers')
|
|
await cache.delete(`auth:user:${parseInt(userId)}`)
|
|
console.log('[Cache] 用户认证缓存已清除(状态更新)')
|
|
} catch (cacheError) {
|
|
console.warn('[Cache] 清除缓存失败:', cacheError)
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
message: `用户状态已更新为${getStatusText(status)}`,
|
|
data: {
|
|
userId: parseInt(userId),
|
|
oldStatus,
|
|
newStatus: status,
|
|
changedAt: currentTime,
|
|
changedBy: user.name
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error('更新用户状态失败:', error)
|
|
|
|
if (error.statusCode) {
|
|
throw error
|
|
}
|
|
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: '更新用户状态失败: ' + error.message
|
|
})
|
|
}
|
|
})
|