From 640ce501cb96c0f03027c0f0fb190d10ac5ceef7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 27 Oct 2026 03:08:51 +0800 Subject: [PATCH] =?UTF-8?q?feat(user):=20=E6=96=B0=E5=A2=9E=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E7=94=A8=E6=88=B7=E5=90=8D/=E5=AF=86=E7=A0=81?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=8E=E8=87=AA=E5=AE=9A=E4=B9=89=E5=AF=86?= =?UTF-8?q?=E7=A0=81=E6=A0=87=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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> --- AI_METHOD_ROUTING.md | 8 +- app/model/account.js | 12 + app/service/systemMethods/user.js | 20 +- app/service/systems/auth/user.js | 240 +++++++++++++++++- ...0-add-is-custom-password-to-wms-account.js | 44 ++++ .../systemMethods/user.changePassword.test.js | 208 +++++++++++++++ .../systemMethods/user.getAccountInfo.test.js | 3 +- .../systemMethods/user.updateUsername.test.js | 188 ++++++++++++++ 8 files changed, 714 insertions(+), 9 deletions(-) create mode 100644 database/migrations/20261025135000-add-is-custom-password-to-wms-account.js create mode 100644 test/app/service/systemMethods/user.changePassword.test.js create mode 100644 test/app/service/systemMethods/user.updateUsername.test.js diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index f6ec0d0..161d8cd 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -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) diff --git a/app/model/account.js b/app/model/account.js index eec7981..b2199a2 100644 --- a/app/model/account.js +++ b/app/model/account.js @@ -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, diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 54ac83e..33a2deb 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -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); diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index ffbc658..3e1e448 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -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} 修改结果 + */ + 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} 修改结果 + */ + 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 diff --git a/database/migrations/20261025135000-add-is-custom-password-to-wms-account.js b/database/migrations/20261025135000-add-is-custom-password-to-wms-account.js new file mode 100644 index 0000000..b7faa39 --- /dev/null +++ b/database/migrations/20261025135000-add-is-custom-password-to-wms-account.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * 为账号表新增“是否自定义密码”标记。 + */ +module.exports = { + /** + * 执行迁移:新增 is_custom_password 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + 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} 无返回值 + */ + 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'); + }, +}; diff --git a/test/app/service/systemMethods/user.changePassword.test.js b/test/app/service/systemMethods/user.changePassword.test.js new file mode 100644 index 0000000..4427e0d --- /dev/null +++ b/test/app/service/systemMethods/user.changePassword.test.js @@ -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' }]); + }); +}); diff --git a/test/app/service/systemMethods/user.getAccountInfo.test.js b/test/app/service/systemMethods/user.getAccountInfo.test.js index 3de986b..6e854de 100644 --- a/test/app/service/systemMethods/user.getAccountInfo.test.js +++ b/test/app/service/systemMethods/user.getAccountInfo.test.js @@ -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)); diff --git a/test/app/service/systemMethods/user.updateUsername.test.js b/test/app/service/systemMethods/user.updateUsername.test.js new file mode 100644 index 0000000..b30dab0 --- /dev/null +++ b/test/app/service/systemMethods/user.updateUsername.test.js @@ -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' }]); + }); +});