From 0e7545bd9a0740628dfd3ed7b249e0ca6d267935 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 25 Oct 2026 13:43:26 +0800 Subject: [PATCH] =?UTF-8?q?feat(user):=20=E6=96=B0=E5=A2=9E=20user.getAcco?= =?UTF-8?q?untInfo=20=E8=B4=A6=E5=8F=B7=E7=BA=A7=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 user.getAccountInfo:仅查询当前登录账号的 wms_account 信息 - 白名单返回 id/username/real_name/phone/email/status/last_login_at/created_at/updated_at,排除 password_hash、salt、last_login_ip - 未登录返回 401,账号不存在返回 404;不接收账号ID,避免越权查询 - 同步 methods/system.json(0.3.304 → 0.3.305)、变更记录、AI_METHOD_ROUTING 与方法文档库表 - 新增单测 test/app/service/systemMethods/user.getAccountInfo.test.js(5 通过) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- AI_METHOD_ROUTING.md | 8 +- app/service/systemMethods/user.js | 11 +- app/service/systems/auth/user.js | 53 +++++++ methods/changes/system.json | 17 +++ methods/system.json | 85 ++++++++++- .../systemMethods/user.getAccountInfo.test.js | 138 ++++++++++++++++++ 6 files changed, 305 insertions(+), 7 deletions(-) create mode 100644 test/app/service/systemMethods/user.getAccountInfo.test.js diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index 43fac5d..f6ec0d0 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 (9) - - login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, changeRole, register +- app/service/systemMethods/user.js (10) + - login, loginByCode, getBindWechatCode, getLoginWechatCode, unbindWechat, logout, info, getAccountInfo, 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 (67) - - 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, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register +- 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/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/service/systemMethods/user.js b/app/service/systemMethods/user.js index 3808e91..54ac83e 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,getBindWechatCode,getLoginWechatCode'; + const _noNeedLog = 'info,getAccountInfo,getBindWechatCode,getLoginWechatCode'; const _noNeedAuth = '*'; // info:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问 const _noNeedBind = 'info'; @@ -72,6 +72,15 @@ class userService extends MainService { const result = await service.systems.auth.user.info(data); return this.success('获取成功' + JSON.stringify(data), result); } + // 获取当前登录账号的账号级信息(仅 wms_account,不含敏感字段) + async getAccountInfo(data) { + const { service } = this; + const result = await service.systems.auth.user.getAccountInfo(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 77c21f0..ffbc658 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -1736,6 +1736,59 @@ class UserService extends Service { } } + /** + * 获取当前登录账号的账号级信息(仅 wms_account,不含敏感字段) + * @return {Promise} 账号信息 + */ + async getAccountInfo() { + const { ctx } = this; + const userId = Number(ctx.userId || (ctx.user && ctx.user.id)); + if (!Number.isInteger(userId) || userId <= 0) { + return { + success: false, + data: null, + code: 401, + message: '未登录或登录已过期', + }; + } + + try { + const account = await ctx.model.Account.findOne({ + where: { id: userId }, + // 白名单字段,避免返回 password_hash / salt / last_login_ip 等敏感信息 + attributes: [ + 'id', 'username', 'real_name', 'phone', 'email', + 'status', 'last_login_at', 'created_at', 'updated_at', + ], + raw: true, + }); + + if (!account) { + return { + success: false, + data: null, + code: 404, + message: '账号不存在', + }; + } + + return { + success: true, + data: account, + 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/methods/changes/system.json b/methods/changes/system.json index 3504227..d626f7d 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,21 @@ [ + { + "version": "0.3.305", + "date": "2026-10-25", + "type": "added", + "summary": "新增 user.getAccountInfo:仅返回当前登录账号在 wms_account 的账号级信息,不返回 password_hash、salt、last_login_ip 等敏感字段。", + "methods": [ + "user.getAccountInfo" + ], + "notes": [ + "方法层:app/service/systemMethods/user.js 新增 getAccountInfo(data),未加入 _noNeedLogin(需登录),加入 _noNeedLog(只读接口不写操作日志),统一 this.success('获取账号信息成功', result) 包装;不接收账号ID,避免越权查询。", + "系统层:app/service/systems/auth/user.js 新增 getAccountInfo(),账号ID取自 ctx.userId / ctx.user.id;使用 attributes 白名单(id/username/real_name/phone/email/status/last_login_at/created_at/updated_at)查询 wms_account,raw=true,显式排除 password_hash、salt、last_login_ip。", + "错误码:未登录或登录已过期返回 401;账号不存在返回 404;查询异常返回 code=0。", + "测试:test/app/service/systemMethods/user.getAccountInfo.test.js(5 通过,覆盖方法层透传/失败码、登录账号过滤与敏感字段白名单、未登录 401、账号不存在 404)。", + "文档变更范围:methods/system.json 的 user.getAccountInfo 一条(新增)+根版本 0.3.304 → 0.3.305、updatedAt 2026-10-25;methods/changes/system.json 新增本条(插入数组首位)。", + "代码依据:app/service/systemMethods/user.js#getAccountInfo、app/service/systems/auth/user.js#getAccountInfo。" + ] + }, { "version": "0.3.304", "date": "2026-10-23", diff --git a/methods/system.json b/methods/system.json index 0f25709..17d10da 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.304", - "updatedAt": "2026-10-23", + "version": "0.3.305", + "updatedAt": "2026-10-25", "headers": [ { "name": "platform", @@ -31255,6 +31255,87 @@ "response": [], "errors": [] }, + { + "method": "user.getAccountInfo", + "description": "获取当前登录账号的账号级信息(仅查询 wms_account,不返回 password_hash、salt、last_login_ip 等敏感字段;不接受账号ID入参,始终取登录上下文)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "******" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "账号ID" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "用户名" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "真实姓名" + }, + { + "name": "phone", + "type": "string", + "required": true, + "description": "手机号" + }, + { + "name": "email", + "type": "string", + "required": false, + "description": "邮箱" + }, + { + "name": "status", + "type": "number", + "required": true, + "description": "状态:0-禁用,1-启用,2-离职" + }, + { + "name": "last_login_at", + "type": "string", + "required": false, + "description": "最后登录时间" + }, + { + "name": "created_at", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + } + ], + "errors": [ + { + "code": 401, + "message": "未登录或登录已过期" + }, + { + "code": 404, + "message": "账号不存在" + } + ] + }, { "method": "user.changeRole", "description": "user.changeRole 接口", diff --git a/test/app/service/systemMethods/user.getAccountInfo.test.js b/test/app/service/systemMethods/user.getAccountInfo.test.js new file mode 100644 index 0000000..3de986b --- /dev/null +++ b/test/app/service/systemMethods/user.getAccountInfo.test.js @@ -0,0 +1,138 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserMethodService = require('../../../../app/service/systemMethods/user'); +const UserSystemService = require('../../../../app/service/systems/auth/user'); + +function createMethodHarness(getAccountInfo) { + const calls = []; + const ctx = { + app: { config: {}, Sequelize: {} }, + logger: { error() {} }, + service: { + systems: { + auth: { + user: { + async getAccountInfo(data) { + calls.push(data); + return getAccountInfo(data); + }, + }, + }, + }, + }, + }; + + return { + service: new UserMethodService(ctx), + calls, + }; +} + +function createSystemHarness(options = {}) { + const calls = []; + const ctx = { + app: { config: {}, Sequelize: {} }, + userId: options.userId, + user: options.user, + logger: { error() {} }, + model: { + Account: { + async findOne(args) { + calls.push(args); + return options.account === undefined ? null : options.account; + }, + }, + }, + }; + + return { + service: new UserSystemService(ctx), + calls, + }; +} + +describe('test/app/service/systemMethods/user.getAccountInfo.test.js', () => { + it('方法层应透传系统层结果并返回成功结构', async () => { + const payload = { + success: true, + data: { id: 1, username: 'admin' }, + code: 200, + message: '获取账号信息成功', + }; + const { service, calls } = createMethodHarness(async () => payload); + + const result = await service.getAccountInfo({ id: 99 }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, payload.data); + assert.deepEqual(calls, [{ id: 99 }]); + }); + + it('方法层应保留系统层业务失败码', async () => { + const { service } = createMethodHarness(async () => ({ + success: false, + data: null, + code: 404, + message: '账号不存在', + })); + + const result = await service.getAccountInfo({}); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 404); + assert.equal(result.message, '账号不存在'); + }); + + it('系统层只按登录账号查询并排除敏感字段', async () => { + const account = { + id: 7, + username: 'demo', + real_name: '演示账号', + phone: '13800000000', + email: 'demo@example.com', + status: 1, + 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'), + }; + const { service, calls } = createSystemHarness({ userId: 7, account }); + + const result = await service.getAccountInfo({ id: 999 }); + + assert.equal(result.success, true); + assert.equal(result.code, 200); + assert.deepEqual(result.data, account); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0].where, { id: 7 }); + 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', + ]); + for (const field of [ 'password_hash', 'salt', 'last_login_ip' ]) { + assert.ok(!calls[0].attributes.includes(field)); + } + }); + + it('系统层未登录时返回 401 且不查库', async () => { + const { service, calls } = createSystemHarness({ account: { id: 1 } }); + + const result = await service.getAccountInfo(); + + assert.equal(result.success, false); + assert.equal(result.code, 401); + assert.equal(calls.length, 0); + }); + + it('系统层账号不存在时返回 404', async () => { + const { service } = createSystemHarness({ userId: 7, account: null }); + + const result = await service.getAccountInfo(); + + assert.equal(result.success, false); + assert.equal(result.code, 404); + assert.equal(result.message, '账号不存在'); + }); +});