Files
BYW-VoiceHub/server/utils/user-status.ts
T
Henry_Du cd6e235848 fix(users): 状态大小写不敏感 + 彻底修掉「无法编辑其它用户」
站长反馈仍然无法编辑其它用户。上一版只把**小程序端**的状态改成小写,
但如果小程序没重新编译(或用的还是旧版本),发上来的仍是 `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,一并改正

效果:无论小程序是否重新编译,管理员都能编辑其它用户(含历史拼音账号只改年级)。
2026-09-30 23:49:40 +08:00

28 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { eq } from 'drizzle-orm'
/**
* 用户状态(`users.status`)的唯一口径。
*
* ⚠️ 这里踩过一次真实的坑:小程序端一直发**大写** `ACTIVE`,
* 而服务端与 DB 用的是**小写** `active` / `withdrawn` / `graduate`(登录、2FA、WebAuthn
* 等地方都按小写判断)。于是管理员在用户管理里**编辑任何用户**都会被
* 「用户状态只能是 active, withdrawn 或 graduate」拒绝 —— 看起来像"编辑功能坏了"。
*
* 所以状态统一走这里的 `normalizeUserStatus()`:**大小写不敏感**,
* 认不出来的值返回 null,由调用方决定是报错还是忽略(创建用户时忽略、编辑时可报错)。
*/
export const USER_STATUSES = ['active', 'withdrawn', 'graduate'] as const
export type UserStatus = (typeof USER_STATUSES)[number]
/** 归一化:`ACTIVE` / `active` / ` Active ` → `active`;其它 → null */
export function normalizeUserStatus(value: unknown): UserStatus | null {
const s = String(value ?? '')
.trim()
.toLowerCase()
return (USER_STATUSES as readonly string[]).includes(s) ? (s as UserStatus) : null
}
/** 统一的错误文案(列出允许值,别让调用方各写各的) */
export const USER_STATUS_RULE_MESSAGE = '用户状态只能是 active、withdrawn 或 graduate'