feat(user): 新增账号用户名/密码修改与自定义密码标记

- wms_account 新增 is_custom_password(TINYINT(1) NOT NULL DEFAULT 0),同步模型与迁移 20261025135000;开发库、生产库均已执行

- user.getAccountInfo 返回 is_custom_password,仍不返回 password_hash/salt/last_login_ip

- 新增 user.updateUsername:仅改当前账号,服务端重名校验并排除自己,重名返回 409,更新后清理用户缓存

- 新增 user.changePassword:is_custom_password=0 时旧密码可不传,修改后置 1;再次修改必须校验旧密码;已排除操作日志避免明文密码落库

- 单测覆盖 getAccountInfo/updateUsername/changePassword,20 通过;同步 AI_METHOD_ROUTING

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-10-27 03:08:51 +08:00
parent de2f66a2d1
commit 640ce501cb
8 changed files with 714 additions and 9 deletions

View File

@ -562,8 +562,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- list, sign, confirmSign, rename, unbind, adjustPrintQuantity, queryPrintQuantityLogs, getPolicyConfig, getPolicyConfigFields, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, openAccount, createUser, export, exportTaskProgress, exportPrintQuantityLogs, exportPrintQuantityLogsTaskProgress, queryStorePrintQuantityLogs, exportStorePrintQuantityLogs, exportStorePrintQuantityLogsTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/storeWarehouse/warehouse.js (3)
- list, sign, confirmSign
- app/service/systemMethods/user.js (10)
- login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, getAccountInfo, changeRole, register
- app/service/systemMethods/user.js (12)
- login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, getAccountInfo, updateUsername, changePassword, changeRole, register
- app/service/systemMethods/warehouse.js (25)
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo, getBatchFieldValue, hasBatchField, normalizeBatchString, getCurrentWarehouseCode, batchUpdateSpaceInfo, exportRackSpaces
- app/service/systemMethods/waybill/warehouse.js (9)
@ -582,8 +582,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- generateAppKey, generateAppSecret, getDefaultInterfaceTypeId, list, create, update, delete, regenerateSecret
- app/service/systems/auth/role_permission.js (7)
- normalizeTypeFilter, normalizePermissionSet, toApiPermissionIds, serializePermissionSet, getPermissionIdsForRoles, assignPermissions, removePermissionsFromAllRoles
- app/service/systems/auth/user.js (68)
- getMenuTypeWhereByPlatform, getCurrentAccountId, getWechatBindCacheKey, getWechatBindCodeCacheKey, getWechatBindScanCacheKey, getWechatLoginClientCacheKey, getWechatLoginCodeCacheKey, getWechatLoginEventChannel, createWechatBindCodeCandidate, createUniqueSixCode, createWechatBindCode, createWechatLoginCode, createWechatLoginClientCode, parseWechatBindCode, formatBindWechatData, formatLoginWechatData, getRemainingSecondsByExpiresAt, setWechatBindCache, setWechatBindCodeCache, setWechatBindScanCache, getWechatBindScanCache, setWechatLoginClientCache, setWechatLoginCodeCache, findYe4sBindingByAccountId, getWechatBindEventChannel, getWechatLongPollTimeoutMs, shouldUseWechatBindLongPoll, publishWechatBindEvent, publishWechatLoginEvent, waitForWechatBindEvent, refreshWechatBindState, login, loginByYe4sCode, waitForLoginCodeRefresh, isTransientWechatLoginError, extractYe4sUserIdFromLoginEvent, waitForWechatLoginEvent, loginByYe4sUserId, tryBuildWechatLoginTokenFromState, refreshWechatLoginState, getLoginWechatCode, getBindWechatCode, getBindWechatCodeByAccountId, getUserByTempCode, bindAccountByTempCode, unbindWechat, unbindWechatByAccountId, buildLoginResult, changeRole, info, getAccountInfo, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
- app/service/systems/auth/user.js (70)
- getMenuTypeWhereByPlatform, getCurrentAccountId, getWechatBindCacheKey, getWechatBindCodeCacheKey, getWechatBindScanCacheKey, getWechatLoginClientCacheKey, getWechatLoginCodeCacheKey, getWechatLoginEventChannel, createWechatBindCodeCandidate, createUniqueSixCode, createWechatBindCode, createWechatLoginCode, createWechatLoginClientCode, parseWechatBindCode, formatBindWechatData, formatLoginWechatData, getRemainingSecondsByExpiresAt, setWechatBindCache, setWechatBindCodeCache, setWechatBindScanCache, getWechatBindScanCache, setWechatLoginClientCache, setWechatLoginCodeCache, findYe4sBindingByAccountId, getWechatBindEventChannel, getWechatLongPollTimeoutMs, shouldUseWechatBindLongPoll, publishWechatBindEvent, publishWechatLoginEvent, waitForWechatBindEvent, refreshWechatBindState, login, loginByYe4sCode, waitForLoginCodeRefresh, isTransientWechatLoginError, extractYe4sUserIdFromLoginEvent, waitForWechatLoginEvent, loginByYe4sUserId, tryBuildWechatLoginTokenFromState, refreshWechatLoginState, getLoginWechatCode, getBindWechatCode, getBindWechatCodeByAccountId, getUserByTempCode, bindAccountByTempCode, unbindWechat, unbindWechatByAccountId, buildLoginResult, changeRole, info, getAccountInfo, updateUsername, changePassword, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
- app/service/systems/camera.js (12)
- list, detail, create, update, setOsd, _findCameraForControl, _assertPtzSuccess, ptzControl, ptzStop, ptzPresetGoto, ptzPresetSet, delete
- app/service/systems/cameraServer.js (5)

View File

@ -74,6 +74,18 @@ module.exports = app => {
},
comment: '状态:0-封号,1-启用',
},
is_custom_password: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
validate: {
isIn: {
args: [[ 0, 1 ]],
msg: '自定义密码标记值不合法,0-否,1-是',
},
},
comment: '是否自定义密码:0-否,1-是',
},
last_login_at: {
type: DATE,
allowNull: true,

View File

@ -7,7 +7,7 @@ class userService extends MainService {
super(ctx);
const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode';
const _noNeedRight = '*';
const _noNeedLog = 'info,getAccountInfo,getBindWechatCode,getLoginWechatCode';
const _noNeedLog = 'info,getAccountInfo,changePassword,getBindWechatCode,getLoginWechatCode';
const _noNeedAuth = '*';
// info:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问
const _noNeedBind = 'info';
@ -81,6 +81,24 @@ class userService extends MainService {
}
return this.fail(result.message || '获取账号信息失败', result);
}
// 修改当前账号用户名(服务端校验重名,排除自己)
async updateUsername(data) {
const { service } = this;
const result = await service.systems.auth.user.updateUsername(data);
if (result.code === 200) {
return this.success(result.message || '用户名修改成功', result);
}
return this.fail(result.message || '用户名修改失败', result);
}
// 修改当前账号密码(首次自定义密码可不传旧密码)
async changePassword(data) {
const { service } = this;
const result = await service.systems.auth.user.changePassword(data);
if (result.code === 200) {
return this.success(result.message || '密码修改成功', result);
}
return this.fail(result.message || '密码修改失败', result);
}
async changeRole(data) {
const { service } = this;
const result = await service.systems.auth.user.changeRole(data);

View File

@ -1742,8 +1742,8 @@ class UserService extends Service {
*/
async getAccountInfo() {
const { ctx } = this;
const userId = Number(ctx.userId || (ctx.user && ctx.user.id));
if (!Number.isInteger(userId) || userId <= 0) {
const userId = this.getCurrentAccountId();
if (!userId) {
return {
success: false,
data: null,
@ -1758,7 +1758,7 @@ class UserService extends Service {
// 白名单字段,避免返回 password_hash / salt / last_login_ip 等敏感信息
attributes: [
'id', 'username', 'real_name', 'phone', 'email',
'status', 'last_login_at', 'created_at', 'updated_at',
'status', 'is_custom_password', 'last_login_at', 'created_at', 'updated_at',
],
raw: true,
});
@ -1789,6 +1789,240 @@ class UserService extends Service {
}
}
/**
* 修改当前登录账号的用户名(服务端做重名校验,排除自己)
* @param {Object} [data={}] 入参
* @param {string} [data.username] 新用户名
* @return {Promise<Object>} 修改结果
*/
async updateUsername(data = {}) {
const { ctx } = this;
const userId = this.getCurrentAccountId();
if (!userId) {
return {
success: false,
data: null,
code: 401,
message: '未登录或登录已过期',
};
}
const username = typeof data.username === 'string' ? data.username.trim() : '';
if (!username) {
return {
success: false,
data: null,
code: 400,
message: 'username 不能为空',
};
}
if (username.length < 3 || username.length > 50) {
return {
success: false,
data: null,
code: 400,
message: '用户名长度应在3-50个字符之间',
};
}
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
return {
success: false,
data: null,
code: 400,
message: '用户名只能包含字母、数字和下划线',
};
}
try {
const account = await ctx.model.Account.findOne({
where: { id: userId },
attributes: [ 'id', 'username' ],
raw: true,
});
if (!account) {
return {
success: false,
data: null,
code: 404,
message: '账号不存在',
};
}
if (account.username === username) {
return {
success: true,
data: { id: userId, username },
code: 200,
message: '用户名未变更',
};
}
const { Op } = this.app.Sequelize;
const duplicate = await ctx.model.Account.findOne({
where: {
username,
id: { [Op.ne]: userId },
},
attributes: [ 'id' ],
raw: true,
});
if (duplicate) {
return {
success: false,
data: null,
code: 409,
message: '用户名已存在',
};
}
await ctx.model.Account.update({ username }, {
where: { id: userId },
});
// clearUserCache 默认平台清单不含 miniprogram/wx 等取值,先按当前平台补清一次
const platformCode = ctx.header && ctx.header.platform;
if (platformCode) {
await this.clearUserCache(userId, platformCode);
}
await this.clearUserCache(userId);
ctx.username = username;
if (ctx.user) {
ctx.user.username = username;
}
return {
success: true,
data: { id: userId, username },
code: 200,
message: '用户名修改成功',
};
} catch (error) {
const isDuplicate = error && (
error.name === 'SequelizeUniqueConstraintError'
|| (error.parent && error.parent.code === 'ER_DUP_ENTRY')
);
if (isDuplicate) {
return {
success: false,
data: null,
code: 409,
message: '用户名已存在',
};
}
ctx.logger.error(`修改用户名失败: ${error.message}`);
return {
success: false,
data: null,
code: 0,
message: '修改用户名失败',
};
}
}
/**
* 修改当前登录账号的密码;首次自定义密码(is_custom_password=0)无需旧密码。
* @param {Object} [data={}] 入参
* @param {string} [data.old_password] 旧密码(is_custom_password=1 时必填)
* @param {string} [data.new_password] 新密码
* @return {Promise<Object>} 修改结果
*/
async changePassword(data = {}) {
const { ctx } = this;
const userId = this.getCurrentAccountId();
if (!userId) {
return {
success: false,
data: null,
code: 401,
message: '未登录或登录已过期',
};
}
const rawOldPassword = data.old_password !== undefined ? data.old_password : data.oldPassword;
const rawNewPassword = data.new_password !== undefined ? data.new_password : data.newPassword;
const oldPassword = typeof rawOldPassword === 'string' ? rawOldPassword : '';
const newPassword = typeof rawNewPassword === 'string' ? rawNewPassword.trim() : '';
if (!newPassword) {
return {
success: false,
data: null,
code: 400,
message: '新密码不能为空',
};
}
if (newPassword.length > 64) {
return {
success: false,
data: null,
code: 400,
message: '新密码长度不能超过64个字符',
};
}
try {
const account = await ctx.model.Account.findOne({
where: { id: userId },
attributes: [ 'id', 'password_hash', 'salt', 'is_custom_password' ],
raw: true,
});
if (!account) {
return {
success: false,
data: null,
code: 404,
message: '账号不存在',
};
}
if (Number(account.is_custom_password) === 1) {
if (!oldPassword) {
return {
success: false,
data: null,
code: 400,
message: '请输入旧密码',
};
}
try {
await this.verifyPassword(oldPassword, account.password_hash, account.salt);
} catch (error) {
return {
success: false,
data: null,
code: 400,
message: '旧密码错误',
};
}
}
const salt = this.generateSalt();
const passwordHash = await this.encryptPassword(newPassword, salt);
await ctx.model.Account.update({
password_hash: passwordHash,
salt,
is_custom_password: 1,
}, {
where: { id: userId },
});
await this.clearUserCache(userId);
return {
success: true,
data: { is_custom_password: 1 },
code: 200,
message: '密码修改成功',
};
} catch (error) {
ctx.logger.error(`修改密码失败: ${error.message}`);
return {
success: false,
data: null,
code: 0,
message: '修改密码失败',
};
}
}
/**
* 查找用户所有的角色以及对应的主体(重构版)
* @param {number} userId 用户ID

View File

@ -0,0 +1,44 @@
'use strict';
/**
* 为账号表新增“是否自定义密码”标记。
*/
module.exports = {
/**
* 执行迁移:新增 is_custom_password 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @param {import('sequelize')} Sequelize Sequelize 实例
* @return {Promise<void>} 无返回值
*/
async up(queryInterface, Sequelize) {
const tableName = 'wms_account';
const columns = await queryInterface.describeTable(tableName);
if (columns.is_custom_password) {
return;
}
await queryInterface.addColumn(tableName, 'is_custom_password', {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否自定义密码:0-否,1-是',
});
},
/**
* 回滚迁移:删除 is_custom_password 字段(幂等)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
* @return {Promise<void>} 无返回值
*/
async down(queryInterface) {
const tableName = 'wms_account';
const columns = await queryInterface.describeTable(tableName);
if (!columns.is_custom_password) {
return;
}
await queryInterface.removeColumn(tableName, 'is_custom_password');
},
};

View File

@ -0,0 +1,208 @@
'use strict';
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const UserMethodService = require('../../../../app/service/systemMethods/user');
const UserSystemService = require('../../../../app/service/systems/auth/user');
const SALT = '0123456789abcdef0123';
const OLD_PASSWORD = 'old-pass';
const OLD_HASH = crypto.createHash('sha256').update(OLD_PASSWORD + SALT).digest('hex');
function createSystemHarness(options = {}) {
const calls = {
findOne: [],
update: [],
cleared: [],
};
const findOneResults = [ ...(options.findOneResults || []) ];
const ctx = {
app: { config: {}, Sequelize: {} },
userId: options.userId,
user: options.user,
logger: { error() {} },
model: {
Account: {
async findOne(args) {
calls.findOne.push(args);
return findOneResults.shift();
},
async update(values, updateOptions) {
calls.update.push({ values, updateOptions });
return [ 1 ];
},
},
},
};
const service = new UserSystemService(ctx);
service.clearUserCache = async userId => {
calls.cleared.push(userId);
return true;
};
return { service, calls };
}
function createMethodHarness(changePassword) {
const calls = [];
const ctx = {
app: { config: {}, Sequelize: {} },
logger: { error() {} },
service: {
systems: {
auth: {
user: {
async changePassword(data) {
calls.push(data);
return changePassword(data);
},
},
},
},
},
};
return {
service: new UserMethodService(ctx),
calls,
};
}
function assertNewPasswordHash(values, newPassword) {
assert.equal(values.is_custom_password, 1);
assert.match(values.salt, /^[0-9a-f]{20}$/);
const expected = crypto.createHash('sha256').update(newPassword + values.salt).digest('hex');
assert.equal(values.password_hash, expected);
}
describe('test/app/service/systemMethods/user.changePassword.test.js', () => {
it('首次自定义密码无需旧密码,并更新 is_custom_password', async () => {
const { service, calls } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 0 },
],
});
const result = await service.changePassword({ new_password: 'new-pass' });
assert.equal(result.success, true);
assert.equal(result.code, 200);
assert.deepEqual(result.data, { is_custom_password: 1 });
assert.equal(calls.update.length, 1);
assert.deepEqual(calls.update[0].updateOptions, { where: { id: 7 } });
assertNewPasswordHash(calls.update[0].values, 'new-pass');
assert.deepEqual(calls.cleared, [ 7 ]);
});
it('已自定义密码后必须校验旧密码', async () => {
const { service, calls } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
],
});
const result = await service.changePassword({
old_password: OLD_PASSWORD,
new_password: 'new-pass',
});
assert.equal(result.success, true);
assert.equal(calls.update.length, 1);
assertNewPasswordHash(calls.update[0].values, 'new-pass');
});
it('已自定义密码但未传旧密码返回 400', async () => {
const { service, calls } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
],
});
const result = await service.changePassword({ new_password: 'new-pass' });
assert.equal(result.success, false);
assert.equal(result.code, 400);
assert.equal(result.message, '请输入旧密码');
assert.equal(calls.update.length, 0);
});
it('旧密码错误返回 400', async () => {
const { service, calls } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
],
});
const result = await service.changePassword({
old_password: 'wrong-pass',
new_password: 'new-pass',
});
assert.equal(result.success, false);
assert.equal(result.code, 400);
assert.equal(result.message, '旧密码错误');
assert.equal(calls.update.length, 0);
});
it('支持旧密码/新密码驼峰别名', async () => {
const { service, calls } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, password_hash: OLD_HASH, salt: SALT, is_custom_password: 1 },
],
});
const result = await service.changePassword({
oldPassword: OLD_PASSWORD,
newPassword: 'new-pass',
});
assert.equal(result.success, true);
assert.equal(calls.update.length, 1);
});
it('新密码为空返回 400', async () => {
const { service, calls } = createSystemHarness({ userId: 7 });
const result = await service.changePassword({ new_password: ' ' });
assert.equal(result.success, false);
assert.equal(result.code, 400);
assert.equal(result.message, '新密码不能为空');
assert.equal(calls.findOne.length, 0);
});
it('未登录返回 401,账号不存在返回 404', async () => {
const anonymous = createSystemHarness({});
const missing = createSystemHarness({
userId: 7,
findOneResults: [ null ],
});
const anonymousResult = await anonymous.service.changePassword({ new_password: 'new-pass' });
const missingResult = await missing.service.changePassword({ new_password: 'new-pass' });
assert.equal(anonymousResult.code, 401);
assert.equal(missingResult.code, 404);
});
it('方法层应保留业务失败码', async () => {
const { service, calls } = createMethodHarness(async () => ({
success: false,
data: null,
code: 400,
message: '旧密码错误',
}));
const result = await service.changePassword({ old_password: 'bad', new_password: 'new-pass' });
assert.equal(result.flag, 'failure');
assert.equal(result.code, 400);
assert.deepEqual(calls, [{ old_password: 'bad', new_password: 'new-pass' }]);
});
});

View File

@ -93,6 +93,7 @@ describe('test/app/service/systemMethods/user.getAccountInfo.test.js', () => {
phone: '13800000000',
email: 'demo@example.com',
status: 1,
is_custom_password: 0,
last_login_at: new Date('2026-10-25T05:00:00.000Z'),
created_at: new Date('2026-01-01T00:00:00.000Z'),
updated_at: new Date('2026-10-25T05:00:00.000Z'),
@ -109,7 +110,7 @@ describe('test/app/service/systemMethods/user.getAccountInfo.test.js', () => {
assert.equal(calls[0].raw, true);
assert.deepEqual(calls[0].attributes, [
'id', 'username', 'real_name', 'phone', 'email',
'status', 'last_login_at', 'created_at', 'updated_at',
'status', 'is_custom_password', 'last_login_at', 'created_at', 'updated_at',
]);
for (const field of [ 'password_hash', 'salt', 'last_login_ip' ]) {
assert.ok(!calls[0].attributes.includes(field));

View File

@ -0,0 +1,188 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const UserMethodService = require('../../../../app/service/systemMethods/user');
const UserSystemService = require('../../../../app/service/systems/auth/user');
function createSystemHarness(options = {}) {
const calls = {
findOne: [],
update: [],
cleared: [],
};
const findOneResults = [ ...(options.findOneResults || []) ];
const ctx = {
app: { config: {}, Sequelize: { Op } },
userId: options.userId,
user: options.user,
logger: { error() {} },
model: {
Account: {
async findOne(args) {
calls.findOne.push(args);
return findOneResults.shift();
},
async update(values, updateOptions) {
calls.update.push({ values, updateOptions });
if (options.updateError) {
throw options.updateError;
}
return [ 1 ];
},
},
},
};
const service = new UserSystemService(ctx);
service.clearUserCache = async userId => {
calls.cleared.push(userId);
return true;
};
return { service, calls, ctx };
}
function createMethodHarness(updateUsername) {
const calls = [];
const ctx = {
app: { config: {}, Sequelize: {} },
logger: { error() {} },
service: {
systems: {
auth: {
user: {
async updateUsername(data) {
calls.push(data);
return updateUsername(data);
},
},
},
},
},
};
return {
service: new UserMethodService(ctx),
calls,
};
}
describe('test/app/service/systemMethods/user.updateUsername.test.js', () => {
it('应修改用户名并清理用户缓存', async () => {
const { service, calls, ctx } = createSystemHarness({
userId: 7,
user: { username: 'old_name' },
findOneResults: [
{ id: 7, username: 'old_name' },
null,
],
});
const result = await service.updateUsername({ username: ' new_name ' });
assert.equal(result.success, true);
assert.equal(result.code, 200);
assert.deepEqual(result.data, { id: 7, username: 'new_name' });
assert.deepEqual(calls.update, [{
values: { username: 'new_name' },
updateOptions: { where: { id: 7 } },
}]);
assert.deepEqual(calls.cleared, [ 7 ]);
assert.equal(calls.findOne[1].where.username, 'new_name');
assert.equal(calls.findOne[1].where.id[Op.ne], 7);
assert.equal(ctx.user.username, 'new_name');
});
it('用户名未变化时直接返回成功且不更新', async () => {
const { service, calls } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, username: 'same_name' },
],
});
const result = await service.updateUsername({ username: 'same_name' });
assert.equal(result.success, true);
assert.equal(result.code, 200);
assert.equal(result.message, '用户名未变更');
assert.equal(calls.update.length, 0);
});
it('重名(排除自己)应返回 409', async () => {
const { service, calls } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, username: 'old_name' },
{ id: 9, username: 'taken_name' },
],
});
const result = await service.updateUsername({ username: 'taken_name' });
assert.equal(result.success, false);
assert.equal(result.code, 409);
assert.equal(result.message, '用户名已存在');
assert.equal(calls.update.length, 0);
});
it('唯一索引冲突应兜底返回 409', async () => {
const duplicateError = new Error('Duplicate entry');
duplicateError.parent = { code: 'ER_DUP_ENTRY' };
const { service } = createSystemHarness({
userId: 7,
findOneResults: [
{ id: 7, username: 'old_name' },
null,
],
updateError: duplicateError,
});
const result = await service.updateUsername({ username: 'new_name' });
assert.equal(result.success, false);
assert.equal(result.code, 409);
assert.equal(result.message, '用户名已存在');
});
it('用户名格式非法应返回 400', async () => {
const { service, calls } = createSystemHarness({ userId: 7 });
const shortResult = await service.updateUsername({ username: 'ab' });
const invalidResult = await service.updateUsername({ username: 'bad-name' });
assert.equal(shortResult.code, 400);
assert.equal(invalidResult.code, 400);
assert.equal(calls.findOne.length, 0);
});
it('未登录返回 401,账号不存在返回 404', async () => {
const anonymous = createSystemHarness({});
const missing = createSystemHarness({
userId: 7,
findOneResults: [ null ],
});
const anonymousResult = await anonymous.service.updateUsername({ username: 'new_name' });
const missingResult = await missing.service.updateUsername({ username: 'new_name' });
assert.equal(anonymousResult.code, 401);
assert.equal(missingResult.code, 404);
});
it('方法层应保留业务失败码', async () => {
const { service, calls } = createMethodHarness(async () => ({
success: false,
data: null,
code: 409,
message: '用户名已存在',
}));
const result = await service.updateUsername({ username: 'taken_name' });
assert.equal(result.flag, 'failure');
assert.equal(result.code, 409);
assert.deepEqual(calls, [{ username: 'taken_name' }]);
});
});