fix(auth): 角色切换按平台维度清理缓存,修复小程序端切换身份不生效

changeRole 写库用的是请求头 platform 原值(如 miniProgram),但清缓存调用的却是
clearUserCache(userId)(不带平台),其内部只清 web/pda/mini/app/workerstation/workstation
这几个硬编码平台;miniProgram/wx 等取值不在清单内,且 Redis key 大小写敏感,
user:info:{accountId}:{platform} 会残留切换前的旧身份,紧随其后的 findById 命中 5 分钟旧缓存,
导致签发的 token current_role_id 与返回的 data.user 都是切换前的角色
(实测出现 current_role_id=34 + current_store_id=1000000 这种自相矛盾的 token)。

修复:clearUserCache(user.id, platformCode),并同步清理
platform_active:{accountId}:{platformCode}(30 分钟 TTL)。

验证(开发环境 temp/verify-change-role-fix.cjs):注入旧身份缓存后 user.info 返回注入值
→ changeRole 返回 employees_id=33,token 的 current_role_id/current_store_id 自洽
→ 回读缓存已刷新,DB 行保持 33 未被改动。
This commit is contained in:
liufumingren 2026-09-26 18:00:20 +08:00
parent 0a31b3aab1
commit 81127b61aa

View File

@ -1619,8 +1619,13 @@ class UserService extends Service {
platform_code: platformCode,
});
// 清理缓存
await this.clearUserCache(user.id);
// 清理缓存:必须带上 platformCode
// clearUserCache(userId) 不带平台时只清 web/pda/mini/app/workerstation/workstation 这几个硬编码平台,
// 小程序(miniProgram)、微信(wx)等取值不在清单内且 Redis key 大小写敏感,会残留旧身份,
// 导致紧随其后的 findById 命中 5 分钟旧缓存,签发 token / 返回 user 时仍是切换前的角色。
await this.clearUserCache(user.id, platformCode);
// 同步清理平台激活上下文缓存(platform_active:{accountId}:{platformCode},30 分钟 TTL)
await this.service.systems.accountPlatform.clearPlatformCache(user.id, platformCode);
// 获取更新后的用户信息
const userInfo = await this.findById(user.id);