feat(workbench): 工作台绑定码登录,新增 login_code/token 字段与索引,扫码绑定生成 token,token 免登录获取工作台信息,敏感字段查询脱敏

This commit is contained in:
liufumingren 2026-09-03 17:03:30 +08:00
parent cb2a78f4f1
commit bc0d62d297
5 changed files with 865 additions and 7 deletions

View File

@ -47,6 +47,16 @@ module.exports = app => {
allowNull: true,
comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids',
},
login_code: {
type: STRING(64),
allowNull: true,
comment: '工作台登录码(前缀+随机,64位,全局唯一)',
},
token: {
type: STRING(64),
allowNull: true,
comment: '工作台令牌(随机64位,绑定后生成)',
},
created_at: {
type: DATE,
allowNull: false,
@ -74,6 +84,8 @@ module.exports = app => {
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
{ name: 'idx_barcode', fields: [ 'barcode' ] },
{ name: 'uk_warehouse_barcode', unique: true, fields: [ 'warehouse_id', 'barcode', 'deleted_at' ] },
{ name: 'uk_login_code', unique: true, fields: [ 'login_code' ] },
{ name: 'idx_token', fields: [ 'token' ] },
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
],
});

View File

@ -1052,10 +1052,10 @@ class indexService extends MainService {
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl';
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder';
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode';
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode';
const _noNeedLog = '*';
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder';
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async fastWhereTree(data) {
@ -3357,5 +3357,45 @@ class indexService extends MainService {
const result = await service.systems.waybill.toOrder({ waybill_code: waybillCode });
return this.success('查询成功', result);
}
/**
* 获取工作台绑定码(免登录、免鉴权)
* 不传 client_code:返回新会话的 client_code + 绑定码;
* 传 client_code:等待绑定完成返回 token,超时/缓存失效时重新生成绑定码后返回。
* @param {Object} data - { clientCode | client_code }
*/
async getWorkbenchBindCode(data) {
const { service } = this;
try {
const result = await service.systems.workbench.getWorkbenchBindCode(data || {});
if (result && result.success) {
return this.success('获取工作台绑定码成功', result);
}
return this.fail(result && result.message ? result.message : '获取工作台绑定码失败', undefined);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 通过工作台登录码登录,获取 token(免登录、免鉴权)
* @param {Object} data - { loginCode | login_code }
*/
async LoginWorkbenchByCode(data) {
const { service } = this;
try {
const result = await service.systems.workbench.loginWorkbenchByCode(data || {});
if (result && result.success) {
return this.success('工作台登录成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '工作台登录失败',
statusCode ? { code: statusCode } : undefined
);
} catch (error) {
return this.fail(error.message);
}
}
}
module.exports = indexService;

View File

@ -5,10 +5,10 @@ const MainService = require('../main');
class WorkbenchService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'business';
const _noNeedRight = 'list,detail,checkBarcode,business';
const _noNeedLog = 'list,detail,checkBarcode';
const _noNeedAuth = 'list,detail,checkBarcode,business';
const _noNeedLogin = 'business,getWorkbenchInfo';
const _noNeedRight = 'list,detail,checkBarcode,business,getWorkbenchInfo';
const _noNeedLog = 'list,detail,checkBarcode,getWorkbenchInfo';
const _noNeedAuth = 'list,detail,checkBarcode,business,getWorkbenchInfo';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -139,6 +139,64 @@ class WorkbenchService extends MainService {
return this.fail(error.message);
}
}
/**
* 工作台绑定:校验缓存绑定码与工作台ID,写入随机 token(需登录、需权限)
* @param data - { code, id }
*/
async bind(data) {
const { service } = this;
try {
const result = await service.systems.workbench.bindWorkbench(data || {});
if (result && result.success) {
return this.success('绑定成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '绑定失败',
statusCode ? { code: statusCode } : undefined
);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 使用 token 获取工作台信息(免登录、免鉴权)
* @param data - { token }
*/
async getWorkbenchInfo(data) {
const { service } = this;
try {
const result = await service.systems.workbench.getWorkbenchInfoByToken(data || {});
if (result && result.success) {
return this.success('获取成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '获取工作台信息失败',
statusCode ? { code: statusCode } : undefined
);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 重置工作台登录码(需登录、需权限)
* @param data - { id }
*/
async resetLoginCode(data) {
const { service } = this;
try {
const { id } = data || {};
if (!id) return this.fail('工作台ID不能为空');
const result = await service.systems.workbench.resetLoginCode(parseInt(id));
return this.success('重置成功', result);
} catch (error) {
return this.fail(error.message);
}
}
}
module.exports = WorkbenchService;

View File

@ -1,6 +1,7 @@
'use strict';
const Service = require('egg').Service;
const crypto = require('node:crypto');
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
@ -9,6 +10,29 @@ const WAVE_ORDER_COUNT_CACHE_KEY_PREFIX = 'cache:workbench:wave_order_count';
/** @type {number} 工作台波次订单实时计数缓存 TTL(秒),TTL 内分表 COUNT 只执行一次 */
const WAVE_ORDER_COUNT_CACHE_TTL_SECONDS = 15;
/** @type {string} 工作台绑定会话缓存 key 前缀(client_code 维度,最终 key:{前缀}{clientCode}) */
const WORKBENCH_BIND_CLIENT_CACHE_PREFIX = 'workbench:bind:client:';
/** @type {string} 工作台绑定码缓存 key 前缀(code 维度,供 bind 反查会话,最终 key:{前缀}{code}) */
const WORKBENCH_BIND_CODE_CACHE_PREFIX = 'workbench:bind:code:';
/** @type {string} 工作台 token → 信息缓存 key 前缀(最终 key:workbench:token:{token}) */
const WORKBENCH_TOKEN_CACHE_PREFIX = 'workbench:token:';
/** @type {number} 工作台绑定码缓存有效期(秒) */
const WORKBENCH_BIND_CACHE_TTL_SECONDS = 120;
/** @type {number} 工作台 token 信息缓存有效期(秒) */
const WORKBENCH_TOKEN_CACHE_TTL_SECONDS = 300;
/** @type {number} 工作台绑定长轮询超时(毫秒) */
const WORKBENCH_BIND_LONG_POLL_TIMEOUT_MS = 60000;
/** @type {number} 工作台绑定长轮询检查间隔(毫秒) */
const WORKBENCH_BIND_POLL_INTERVAL_MS = 1000;
/** @type {string} 工作台登录码前缀(登录码总长度 64 位) */
const WORKBENCH_LOGIN_CODE_PREFIX = 'wblc';
/** @type {number} 工作台登录码随机段长度(64 - 前缀长度 = 60 位十六进制) */
const WORKBENCH_LOGIN_CODE_RANDOM_HEX_LENGTH = 64 - WORKBENCH_LOGIN_CODE_PREFIX.length;
/** @type {string} 工作台绑定码 / client_code 字符集 */
const WORKBENCH_BIND_CODE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
/** @type {number} 工作台绑定码 / client_code 长度 */
const WORKBENCH_BIND_CODE_LENGTH = 6;
class WorkbenchService extends Service {
/**
* 查询工作台列表(仓库隔离 + 软删除过滤)
@ -41,6 +65,7 @@ class WorkbenchService extends Service {
const { count, rows } = await ctx.model.Workbench.findAndCountAll({
where: queryWhere,
attributes: { exclude: [ 'token' ] },
order: [['created_at', 'DESC']],
offset: (page - 1) * pageSize,
limit: pageSize,
@ -70,6 +95,7 @@ class WorkbenchService extends Service {
const record = await ctx.model.Workbench.findOne({
where: { id, warehouse_id: warehouseId },
attributes: { exclude: [ 'token' ] },
});
if (!record) {
@ -99,6 +125,7 @@ class WorkbenchService extends Service {
type: data.type || 'personal',
status: data.status !== undefined ? parseInt(data.status) : 1,
device_ids: data.device_ids || null,
login_code: await this.generateUniqueWorkbenchLoginCode(),
remark: data.remark ? String(data.remark).trim() : null,
});
@ -1607,6 +1634,638 @@ class WorkbenchService extends Service {
const count = await ctx.model.Workbench.count({ where });
return count > 0;
}
// ==================== 绑定码 / 登录码 / 令牌 ====================
/**
* 工作台绑定会话缓存 key(client_code 维度)
* @param {string} clientCode 客户端编码
* @return {string} 缓存 key
*/
getWorkbenchBindClientCacheKey(clientCode) {
return `${WORKBENCH_BIND_CLIENT_CACHE_PREFIX}${clientCode}`;
}
/**
* 工作台绑定码缓存 key(code 维度)
* @param {string} code 绑定码
* @return {string} 缓存 key
*/
getWorkbenchBindCodeCacheKey(code) {
return `${WORKBENCH_BIND_CODE_CACHE_PREFIX}${code}`;
}
/**
* 工作台 token 信息缓存 key
* @param {string} token 工作台令牌
* @return {string} 缓存 key
*/
getWorkbenchTokenCacheKey(token) {
return `${WORKBENCH_TOKEN_CACHE_PREFIX}${token}`;
}
/**
* 生成指定字符集与长度的随机串。
* @param {string} charset 字符集
* @param {number} length 长度
* @return {string} 随机串
*/
generateRandomChars(charset, length) {
let result = '';
for (let i = 0; i < length; i++) {
result += charset[crypto.randomInt(0, charset.length)];
}
return result;
}
/**
* 生成工作台令牌(64 位十六进制)。
* @return {string} token
*/
generateWorkbenchToken() {
return crypto.randomBytes(32).toString('hex');
}
/**
* 生成工作台登录码(前缀 wblc + 60 位十六进制随机段,总长度 64 位)。
* @return {string} login_code
*/
generateWorkbenchLoginCode() {
return WORKBENCH_LOGIN_CODE_PREFIX
+ crypto.randomBytes(WORKBENCH_LOGIN_CODE_RANDOM_HEX_LENGTH / 2).toString('hex');
}
/**
* 标准化绑定码 / client_code:去空格转大写,仅接受 6 位大写字母+数字。
* @param {string} code 原始编码
* @return {string|null} 标准化结果,非法返回 null
*/
normalizeWorkbenchBindCode(code) {
const normalized = typeof code === 'string' ? code.trim().toUpperCase() : '';
if (!/^[A-Z0-9]{6}$/.test(normalized)) {
return null;
}
return normalized;
}
/**
* 生成全局唯一的登录码(查库去重,最多 5 次尝试)。
* @return {Promise<string>} 唯一登录码
*/
async generateUniqueWorkbenchLoginCode() {
const { ctx } = this;
for (let attempt = 0; attempt < 5; attempt++) {
const code = this.generateWorkbenchLoginCode();
const exists = await ctx.model.Workbench.findOne({
where: { login_code: code },
attributes: [ 'id' ],
raw: true,
});
if (!exists) {
return code;
}
}
throw new Error('生成登录码失败,请稍后重试');
}
/**
* 生成唯一的 client_code(缓存去重)。
* @param {number} [maxAttempts=200] 最大尝试次数
* @return {Promise<string>} 唯一 client_code
*/
async createUniqueWorkbenchClientCode(maxAttempts = 200) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const code = this.generateRandomChars(WORKBENCH_BIND_CODE_CHARSET, WORKBENCH_BIND_CODE_LENGTH);
const cacheKey = this.getWorkbenchBindClientCacheKey(code);
const exists = await this.app.getCacheAsync(cacheKey);
if (!exists) {
return code;
}
}
throw new Error('生成客户端编码失败,请稍后重试');
}
/**
* 生成唯一的绑定码(缓存去重)。
* @param {number} [maxAttempts=200] 最大尝试次数
* @return {Promise<string>} 唯一绑定码
*/
async createUniqueWorkbenchBindCode(maxAttempts = 200) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const code = this.generateRandomChars(WORKBENCH_BIND_CODE_CHARSET, WORKBENCH_BIND_CODE_LENGTH);
const cacheKey = this.getWorkbenchBindCodeCacheKey(code);
const exists = await this.app.getCacheAsync(cacheKey);
if (!exists) {
return code;
}
}
throw new Error('生成绑定码失败,请稍后重试');
}
/**
* 构建绑定会话状态。
* @param {string} clientCode 客户端编码
* @param {string} code 绑定码
* @param {Object} [extra={}] 附加字段
* @return {Object} 会话状态
*/
buildWorkbenchBindState(clientCode, code, extra = {}) {
return {
client_code: clientCode,
code,
status: 'pending',
workbench_id: null,
token: null,
updated_at: new Date().toISOString(),
expires_at: Date.now() + WORKBENCH_BIND_CACHE_TTL_SECONDS * 1000,
...extra,
};
}
/**
* 按缓存剩余时间计算 TTL(秒)。
* @param {number} expiresAt 过期时间戳(毫秒)
* @param {number} [fallbackTtl] 兜底 TTL
* @return {number} 剩余秒数(至少 1 秒)
*/
getWorkbenchBindRemainingSeconds(expiresAt, fallbackTtl = WORKBENCH_BIND_CACHE_TTL_SECONDS) {
const ts = Number(expiresAt);
if (!Number.isFinite(ts) || ts <= 0) {
return fallbackTtl;
}
return Math.max(1, Math.ceil((ts - Date.now()) / 1000));
}
/**
* 写入绑定会话状态(client_code 与 code 两个维度)。
* @param {Object} state 会话状态
* @param {number} [ttl] 过期秒数
* @return {Promise<void>}
*/
async setWorkbenchBindState(state, ttl = WORKBENCH_BIND_CACHE_TTL_SECONDS) {
if (!state || !state.client_code || !state.code) {
return;
}
await Promise.all([
this.app.setCacheAsync(this.getWorkbenchBindClientCacheKey(state.client_code), state, ttl),
this.app.setCacheAsync(this.getWorkbenchBindCodeCacheKey(state.code), state, ttl),
]);
}
/**
* 创建新的绑定会话(新 client_code + 新绑定码)。
* @return {Promise<{client_code: string, code: string, state: Object}>} 会话信息
*/
async createWorkbenchBindSession() {
const clientCode = await this.createUniqueWorkbenchClientCode();
const code = await this.createUniqueWorkbenchBindCode();
const state = this.buildWorkbenchBindState(clientCode, code);
await this.setWorkbenchBindState(state, WORKBENCH_BIND_CACHE_TTL_SECONDS);
return { client_code: clientCode, code, state };
}
/**
* 为已有 client_code 重新生成绑定码并更新缓存。
* @param {string} clientCode 客户端编码
* @return {Promise<{code: string, state: Object}>} 新绑定码与会话状态
*/
async refreshWorkbenchBindCode(clientCode) {
const code = await this.createUniqueWorkbenchBindCode();
const state = this.buildWorkbenchBindState(clientCode, code);
await this.setWorkbenchBindState(state, WORKBENCH_BIND_CACHE_TTL_SECONDS);
return { code, state };
}
/**
* 格式化绑定码接口返回数据。
* @param {Object} state 会话状态
* @return {Object} 对外数据
*/
formatWorkbenchBindData(state) {
const expiresAt = Number(state.expires_at || 0);
return {
client_code: state.client_code || '',
code: state.code || '',
status: state.status || 'pending',
workbench_id: state.workbench_id || null,
token: state.token || null,
updated_at: state.updated_at || new Date().toISOString(),
expires_at: expiresAt > 0 ? expiresAt : null,
expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0,
};
}
/**
* 等待绑定完成(轮询 client_code 维度缓存状态)。
* @param {string} clientCode 客户端编码
* @param {number} [timeoutMs] 超时毫秒
* @return {Promise<{timed_out: boolean, state: Object|null}>} 等待结果
*/
async waitForWorkbenchBindComplete(clientCode, timeoutMs = WORKBENCH_BIND_LONG_POLL_TIMEOUT_MS) {
const startedAt = Date.now();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
while (Date.now() - startedAt < timeoutMs) {
await sleep(WORKBENCH_BIND_POLL_INTERVAL_MS);
let state = null;
try {
state = await this.app.getCacheAsync(this.getWorkbenchBindClientCacheKey(clientCode));
} catch (error) {
this.app.coreLogger.warn(`读取工作台绑定缓存失败: ${error.message}`);
}
if (state && state.status === 'bound' && state.token) {
return { timed_out: false, state };
}
}
return { timed_out: true, state: null };
}
/**
* 获取工作台绑定码(供 index.getWorkbenchBindCode)。
* - 不传 client_code:创建新会话并返回 client_code + 绑定码;
* - 传 client_code 且缓存存在:等待绑定完成返回 token,超时则重新生成绑定码后返回;
* - 传 client_code 但缓存不存在:重新生成绑定码后返回。
* @param {Object} [data={}] - { clientCode | client_code }
* @return {Promise<Object>} { success, code, data, message }
*/
async getWorkbenchBindCode(data = {}) {
const { app } = this;
try {
const rawClientCode = typeof data.clientCode === 'string'
? data.clientCode
: (typeof data.client_code === 'string' ? data.client_code : '');
const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0;
if (!hasInputClientCode) {
const session = await this.createWorkbenchBindSession();
return {
success: true,
code: 200,
data: this.formatWorkbenchBindData(session.state),
message: '工作台绑定码已生成',
};
}
const clientCode = this.normalizeWorkbenchBindCode(rawClientCode);
if (!clientCode) {
return {
success: false,
code: 0,
statusCode: 400,
data: null,
message: '无效的客户端编码格式',
};
}
const clientCacheKey = this.getWorkbenchBindClientCacheKey(clientCode);
let cachedState = null;
try {
cachedState = await app.getCacheAsync(clientCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取工作台绑定码缓存失败: ${cacheErr.message}`);
}
// 传入 client_code 但缓存不存在:按新会话处理,重新生成绑定码后返回。
if (!cachedState) {
const refreshed = await this.refreshWorkbenchBindCode(clientCode);
return {
success: true,
code: 200,
data: this.formatWorkbenchBindData(refreshed.state),
message: '绑定码缓存已过期,已重新生成',
};
}
// 绑定已完成:直接返回 token。
if (cachedState.status === 'bound' && cachedState.token) {
return {
success: true,
code: 200,
data: this.formatWorkbenchBindData(cachedState),
message: '绑定成功',
};
}
// 长轮询等待绑定完成。
const waitResult = await this.waitForWorkbenchBindComplete(clientCode, WORKBENCH_BIND_LONG_POLL_TIMEOUT_MS);
if (!waitResult.timed_out && waitResult.state && waitResult.state.status === 'bound' && waitResult.state.token) {
return {
success: true,
code: 200,
data: this.formatWorkbenchBindData(waitResult.state),
message: '绑定成功',
};
}
// 超时:重新生成绑定码后才返回数据。
const refreshed = await this.refreshWorkbenchBindCode(clientCode);
return {
success: true,
code: 200,
data: this.formatWorkbenchBindData(refreshed.state),
message: '等待绑定超时,已刷新绑定码',
};
} catch (error) {
app.coreLogger.error(`获取工作台绑定码失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '获取工作台绑定码失败,请稍后重试',
};
}
}
/**
* 格式化工作台 token 缓存/接口信息(不含 token、login_code 敏感字段)。
* @param {Object} record 工作台记录(模型实例或普通对象)
* @return {Object} 对外信息
*/
formatWorkbenchTokenInfo(record) {
const plain = record && typeof record.get === 'function'
? record.get({ plain: true })
: (record || {});
return {
id: plain.id,
warehouse_id: plain.warehouse_id,
name: plain.name,
barcode: plain.barcode,
status: plain.status,
type: plain.type,
remark: plain.remark,
device_ids: plain.device_ids,
created_at: plain.created_at,
updated_at: plain.updated_at,
};
}
/**
* 绑定工作台:校验缓存绑定码 + 工作台归属后写入随机 token(供 workbench.bind)。
* - 成功后在 wms_workbench.token 写入随机生成的 token;
* - 若工作台已有 token,删除旧 workbench:token:{token} 缓存;
* - 更新绑定会话状态为 bound,供 index.getWorkbenchBindCode 长轮询返回 token。
* @param {Object} data - { code, id }
* @return {Promise<Object>} { success, code, data, message }
*/
async bindWorkbench(data = {}) {
const { ctx, app } = this;
try {
const warehouseId = ctx.user && ctx.user.store_id;
const rawCode = typeof data.code === 'string' ? data.code : '';
const code = this.normalizeWorkbenchBindCode(rawCode);
const workbenchId = Number(data.id ?? data.workbench_id ?? data.workbenchId);
if (!code) {
return {
success: false,
code: 0,
statusCode: 400,
data: null,
message: '绑定码格式无效',
};
}
if (!Number.isInteger(workbenchId) || workbenchId <= 0) {
return {
success: false,
code: 0,
statusCode: 400,
data: null,
message: '工作台ID不能为空或无效',
};
}
const codeCacheKey = this.getWorkbenchBindCodeCacheKey(code);
let codeState = null;
try {
codeState = await app.getCacheAsync(codeCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取工作台绑定码缓存失败: ${cacheErr.message}`);
}
if (!codeState || codeState.status === 'bound') {
return {
success: false,
code: 0,
statusCode: 400,
data: null,
message: '绑定码不存在或已过期',
};
}
const record = await ctx.model.Workbench.findOne({
where: { id: workbenchId, warehouse_id: warehouseId },
});
if (!record) {
return {
success: false,
code: 0,
statusCode: 404,
data: null,
message: '工作台不存在或无权操作',
};
}
const newToken = this.generateWorkbenchToken();
const oldToken = typeof record.token === 'string' ? record.token : '';
// 若工作台已有 token,删除旧 token 缓存。
if (oldToken && oldToken !== newToken) {
await app.delCacheAsync(this.getWorkbenchTokenCacheKey(oldToken));
}
await record.update({ token: newToken });
// 写入 token → 工作台信息缓存。
await app.setCacheAsync(
this.getWorkbenchTokenCacheKey(newToken),
this.formatWorkbenchTokenInfo(record),
WORKBENCH_TOKEN_CACHE_TTL_SECONDS
);
// 更新绑定会话状态,供长轮询侧返回 token。
const remainingTtl = this.getWorkbenchBindRemainingSeconds(codeState.expires_at, WORKBENCH_BIND_CACHE_TTL_SECONDS);
const boundState = {
...codeState,
status: 'bound',
workbench_id: record.id,
token: newToken,
updated_at: new Date().toISOString(),
};
await this.setWorkbenchBindState(boundState, remainingTtl);
return {
success: true,
code: 200,
data: {
id: record.id,
workbench_id: record.id,
token: newToken,
},
message: '绑定成功',
};
} catch (error) {
app.coreLogger.error(`工作台绑定失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '工作台绑定失败,请稍后重试',
};
}
}
/**
* 通过 token 获取工作台信息(供 workbench.getWorkbenchInfo)。
* 先查缓存 workbench:token:{token},未命中则查库并回填缓存;查无信息返回失败(403)。
* @param {Object} [data={}] - { token }
* @return {Promise<Object>} { success, code, data, message }
*/
async getWorkbenchInfoByToken(data = {}) {
const { ctx, app } = this;
try {
const rawToken = typeof data.token === 'string' ? data.token.trim() : '';
if (!rawToken) {
return {
success: false,
code: 0,
statusCode: 400,
data: null,
message: 'token 不能为空',
};
}
const tokenCacheKey = this.getWorkbenchTokenCacheKey(rawToken);
let cached = null;
try {
cached = await app.getCacheAsync(tokenCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取工作台 token 缓存失败: ${cacheErr.message}`);
}
if (cached) {
return { success: true, code: 200, data: cached, message: 'ok' };
}
const record = await ctx.model.Workbench.findOne({
where: { token: rawToken },
});
if (!record) {
return {
success: false,
code: 0,
statusCode: 403,
data: null,
message: '工作台不存在或 token 无效',
};
}
const info = this.formatWorkbenchTokenInfo(record);
await app.setCacheAsync(tokenCacheKey, info, WORKBENCH_TOKEN_CACHE_TTL_SECONDS);
return { success: true, code: 200, data: info, message: 'ok' };
} catch (error) {
app.coreLogger.error(`通过 token 获取工作台信息失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '获取工作台信息失败,请稍后重试',
};
}
}
/**
* 通过 login_code 获取工作台 token(供 index.LoginWorkbenchByCode)。
* 按 wms_workbench.login_code 查询;查无工作台返回失败(403);
* 工作台尚无 token 时自动生成并持久化(等价于补绑定)。
* @param {Object} [data={}] - { loginCode | login_code }
* @return {Promise<Object>} { success, code, data, message }
*/
async loginWorkbenchByCode(data = {}) {
const { ctx, app } = this;
try {
const rawLoginCode = typeof data.loginCode === 'string'
? data.loginCode.trim()
: (typeof data.login_code === 'string' ? data.login_code.trim() : '');
if (!rawLoginCode) {
return {
success: false,
code: 0,
statusCode: 400,
data: null,
message: 'login_code 不能为空',
};
}
const record = await ctx.model.Workbench.findOne({
where: { login_code: rawLoginCode },
});
if (!record) {
return {
success: false,
code: 0,
statusCode: 403,
data: null,
message: '工作台不存在或登录码无效',
};
}
let token = typeof record.token === 'string' ? record.token : '';
if (!token) {
token = this.generateWorkbenchToken();
await record.update({ token });
}
await app.setCacheAsync(
this.getWorkbenchTokenCacheKey(token),
this.formatWorkbenchTokenInfo(record),
WORKBENCH_TOKEN_CACHE_TTL_SECONDS
);
return {
success: true,
code: 200,
data: {
id: record.id,
workbench_id: record.id,
name: record.name,
token,
},
message: '登录成功',
};
} catch (error) {
app.coreLogger.error(`通过登录码获取工作台 token 失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '工作台登录失败,请稍后重试',
};
}
}
/**
* 重置工作台登录码(供 workbench.resetLoginCode)。
* 重新生成随机 login_code 并写入数据库。
* @param {number} id - 工作台 ID
* @return {Promise<{id: number, login_code: string}>} 新登录码
*/
async resetLoginCode(id) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const workbenchId = Number(id);
if (!Number.isInteger(workbenchId) || workbenchId <= 0) {
throw new Error('工作台ID不能为空或无效');
}
const record = await ctx.model.Workbench.findOne({
where: { id: workbenchId, warehouse_id: warehouseId },
});
if (!record) {
throw new Error('工作台不存在或无权操作');
}
const loginCode = await this.generateUniqueWorkbenchLoginCode();
await record.update({ login_code: loginCode });
return { id: record.id, login_code: loginCode };
}
}
module.exports = WorkbenchService;

View File

@ -0,0 +1,89 @@
'use strict';
const TABLE_NAME = 'wms_workbench';
async function indexExists(queryInterface, tableName, indexName) {
const indexes = await queryInterface.showIndex(tableName);
return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName);
}
async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) {
if (await indexExists(queryInterface, tableName, indexName)) {
console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`);
return;
}
await queryInterface.addIndex(tableName, options.fields, {
name: indexName,
unique: !!options.unique,
});
console.log(`[idx] ${tableName}.${indexName} 已创建`);
}
async function dropIndexIfExists(queryInterface, tableName, indexName) {
if (await indexExists(queryInterface, tableName, indexName)) {
await queryInterface.removeIndex(tableName, indexName);
console.log(`[idx] ${tableName}.${indexName} 已删除`);
}
}
/**
* Migration: add login_code / token to wms_workbench
* - login_code: VARCHAR(64) NULL COMMENT '工作台登录码(前缀+随机,64位,全局唯一)'
* - token: VARCHAR(64) NULL COMMENT '工作台令牌(随机64位,绑定后生成)'
*
* Idempotent: 通过 describeTable / showIndex 判断后仅补齐缺失部分。
*/
module.exports = {
/**
* 执行正向迁移:新增 login_code、token 两列与 uk_login_code、idx_token 索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!columns.login_code) {
await queryInterface.addColumn(TABLE_NAME, 'login_code', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '工作台登录码(前缀+随机,64位,全局唯一)',
});
}
if (!columns.token) {
await queryInterface.addColumn(TABLE_NAME, 'token', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '工作台令牌(随机64位,绑定后生成)',
});
}
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_login_code', {
fields: [ 'login_code' ],
unique: true,
});
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_token', {
fields: [ 'token' ],
});
},
/**
* 执行回滚迁移:删除索引与新增列。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_login_code');
await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_token');
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns.login_code) {
await queryInterface.removeColumn(TABLE_NAME, 'login_code');
}
if (columns.token) {
await queryInterface.removeColumn(TABLE_NAME, 'token');
}
},
};