2447 lines
72 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const crypto = require('node:crypto');
const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:';
const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:';
const WECHAT_BIND_SCAN_CACHE_PREFIX = 'user:wechat:bind:scan:';
const WECHAT_BIND_CACHE_TTL_SECONDS = 60;
const WECHAT_BIND_SCAN_CACHE_TTL_SECONDS = 180;
const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:';
const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000;
const WECHAT_LOGIN_CLIENT_CACHE_PREFIX = 'user:wechat:login:client:';
const WECHAT_LOGIN_CODE_CACHE_PREFIX = 'user:wechat:login:code:';
const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:';
const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60;
class UserService extends Service {
constructor(ctx) {
super(ctx);
}
getCurrentAccountId() {
const { ctx } = this;
const rawUserId = ctx.userId || (ctx.user && ctx.user.id);
const accountId = Number(rawUserId);
if (!Number.isFinite(accountId) || accountId <= 0) {
return null;
}
return accountId;
}
getWechatBindCacheKey(accountId) {
return `${WECHAT_BIND_CACHE_PREFIX}${accountId}`;
}
getWechatBindCodeCacheKey(code) {
return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`;
}
getWechatBindScanCacheKey(code) {
return `${WECHAT_BIND_SCAN_CACHE_PREFIX}${code}`;
}
getWechatLoginClientCacheKey(clientCode) {
return `${WECHAT_LOGIN_CLIENT_CACHE_PREFIX}${clientCode}`;
}
getWechatLoginCodeCacheKey(code) {
return `${WECHAT_LOGIN_CODE_CACHE_PREFIX}${code}`;
}
getWechatLoginEventChannel(clientCode) {
return `${WECHAT_LOGIN_EVENT_CHANNEL_PREFIX}${clientCode}`;
}
createWechatBindCodeCandidate() {
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < 6; i++) {
const index = crypto.randomInt(0, charset.length);
code += charset[index];
}
return code;
}
async createUniqueSixCode(getCacheKey, maxAttempts = 200) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const code = this.createWechatBindCodeCandidate();
if (!this.parseWechatBindCode(code)) {
continue;
}
const cacheKey = getCacheKey(code);
const existsState = await this.app.getCacheAsync(cacheKey);
if (!existsState) {
return code;
}
}
throw new Error('生成登录码失败,请稍后重试');
}
async createWechatBindCode(maxAttempts = 200) {
return await this.createUniqueSixCode(this.getWechatBindCodeCacheKey.bind(this), maxAttempts);
}
async createWechatLoginCode(maxAttempts = 200) {
return await this.createUniqueSixCode(this.getWechatLoginCodeCacheKey.bind(this), maxAttempts);
}
async createWechatLoginClientCode(maxAttempts = 200) {
return await this.createUniqueSixCode(this.getWechatLoginClientCacheKey.bind(this), maxAttempts);
}
parseWechatBindCode(code) {
const normalized = typeof code === 'string' ? code.trim().toUpperCase() : '';
if (!normalized) {
return null;
}
if (!/^[A-Z0-9]{6}$/.test(normalized)) {
return null;
}
if (!/[A-Z]/.test(normalized) || !/[0-9]/.test(normalized)) {
return null;
}
return normalized;
}
formatBindWechatData(state, source = 'db') {
const expiresAt = Number(state.expires_at || 0);
return {
account_id: state.account_id,
code: state.code || '',
status: state.status || 'pending',
is_bound: state.status === 'bound',
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,
scanned_at: state.scanned_at || null,
source,
ye4s_user_id: state.ye4s_user_id || null,
};
}
formatLoginWechatData(state, source = 'cache') {
const expiresAt = Number(state.expires_at || 0);
return {
client_code: state.client_code || '',
code: state.code || '',
status: state.status || 'pending',
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,
source,
};
}
getRemainingSecondsByExpiresAt(expiresAt, fallbackTtl = WECHAT_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));
}
async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) {
await this.app.setCacheAsync(cacheKey, state, ttl);
}
async setWechatBindCodeCache(code, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) {
if (!code) {
return;
}
const codeCacheKey = this.getWechatBindCodeCacheKey(code);
await this.app.setCacheAsync(codeCacheKey, state, ttl);
}
async setWechatBindScanCache(code, state, ttl = WECHAT_BIND_SCAN_CACHE_TTL_SECONDS) {
if (!code) {
return;
}
const scanCacheKey = this.getWechatBindScanCacheKey(code);
await this.app.setCacheAsync(scanCacheKey, state, ttl);
}
async getWechatBindScanCache(code) {
if (!code) {
return null;
}
const scanCacheKey = this.getWechatBindScanCacheKey(code);
return await this.app.getCacheAsync(scanCacheKey);
}
async setWechatLoginClientCache(clientCode, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) {
if (!clientCode) {
return;
}
const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode);
await this.app.setCacheAsync(clientCacheKey, state, ttl);
}
async setWechatLoginCodeCache(code, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) {
if (!code) {
return;
}
const codeCacheKey = this.getWechatLoginCodeCacheKey(code);
await this.app.setCacheAsync(codeCacheKey, state, ttl);
}
async findYe4sBindingByAccountId(accountId) {
const { ctx } = this;
const ye4sClient = ctx.app.mysql.get('ye4s');
const rows = await ye4sClient.select('ye4s_user', {
where: {
wms_account_id: accountId,
},
columns: [ 'id', 'tmp_code', 'wms_account_id' ],
orders: [[ 'id', 'desc' ]],
limit: 1,
});
if (!rows || rows.length === 0) {
return null;
}
return rows[0];
}
getWechatBindEventChannel(accountId) {
return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`;
}
getWechatLongPollTimeoutMs(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
const waitMs = Number(timeoutMs);
if (Number.isFinite(waitMs) && waitMs > 0) {
return Math.floor(waitMs);
}
return WECHAT_BIND_LONG_POLL_TIMEOUT_MS;
}
shouldUseWechatBindLongPoll(data = {}) {
return data.longPoll === true;
}
async publishWechatBindEvent(accountId, payload = {}) {
const { app } = this;
if (!accountId) {
return;
}
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis) {
return;
}
const channel = this.getWechatBindEventChannel(accountId);
const eventData = {
account_id: accountId,
event_at: new Date().toISOString(),
...payload,
};
try {
await cacheRedis.publish(channel, JSON.stringify(eventData));
} catch (error) {
app.coreLogger.warn(`发布微信绑定事件失败: ${error.message}`);
}
}
async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
const { app } = this;
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis || !accountId || typeof cacheRedis.duplicate !== 'function') {
return {
timed_out: true,
reason: 'redis_not_available',
};
}
const channel = this.getWechatBindEventChannel(accountId);
const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs);
const subscriber = cacheRedis.duplicate();
return await new Promise(resolve => {
let settled = false;
let timer = null;
const cleanup = () => {
subscriber.removeListener('message', onMessage);
subscriber.removeListener('error', onError);
Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => {
if (typeof subscriber.quit === 'function') {
Promise.resolve(subscriber.quit()).catch(() => {
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
return;
}
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
};
const finalize = result => {
if (settled) {
return;
}
settled = true;
if (timer) {
clearTimeout(timer);
}
cleanup();
resolve(result);
};
const onMessage = (messageChannel, message) => {
if (messageChannel !== channel) {
return;
}
let eventData = null;
try {
eventData = message ? JSON.parse(message) : null;
} catch (error) {
eventData = { raw: message };
}
finalize({
timed_out: false,
reason: 'event',
event: eventData,
});
};
const onError = error => {
app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_error',
});
};
timer = setTimeout(() => {
finalize({
timed_out: true,
reason: 'timeout',
});
}, waitMs);
subscriber.on('message', onMessage);
subscriber.on('error', onError);
Promise.resolve(subscriber.subscribe(channel)).catch(error => {
app.coreLogger.warn(`订阅微信绑定频道失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_failed',
});
});
});
}
async refreshWechatBindState(accountId, cachedState = null, options = {}) {
const now = Date.now();
const cacheKey = this.getWechatBindCacheKey(accountId);
const forceNewCode = options.forceNewCode === true;
const ye4sBinding = await this.findYe4sBindingByAccountId(accountId);
if (ye4sBinding) {
const boundState = {
account_id: accountId,
status: 'bound',
code: '',
updated_at: new Date().toISOString(),
ye4s_user_id: ye4sBinding.id || null,
expires_at: null,
scanned_at: null,
};
await this.setWechatBindCache(cacheKey, boundState, WECHAT_BIND_CACHE_TTL_SECONDS);
const hasChanged = !cachedState || cachedState.status !== 'bound' || Number(cachedState.ye4s_user_id || 0) !== Number(boundState.ye4s_user_id || 0);
if (hasChanged) {
await this.publishWechatBindEvent(accountId, {
status: 'bound',
code: '',
source: 'db',
});
}
return {
state: boundState,
source: 'db',
message: '账号已绑定微信',
};
}
const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : '';
let codeState = null;
if (!forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode)) {
const codeCacheKey = this.getWechatBindCodeCacheKey(cachedCode);
codeState = await this.app.getCacheAsync(codeCacheKey);
}
const codeAccountId = Number(codeState && codeState.account_id);
const cachedExpiresAt = Number((codeState && codeState.expires_at) || (cachedState && cachedState.expires_at));
const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(codeAccountId) && codeAccountId === accountId && (Number.isFinite(cachedExpiresAt) ? cachedExpiresAt > now : !!codeState);
if (cachedCodeValid) {
const scanState = await this.getWechatBindScanCache(cachedCode);
const normalizedStatus = scanState ? 'scanned' : 'pending';
const state = {
account_id: accountId,
status: normalizedStatus,
code: cachedCode,
updated_at: cachedState.updated_at || new Date().toISOString(),
ye4s_user_id: null,
expires_at: Number.isFinite(cachedExpiresAt) ? cachedExpiresAt : null,
scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null,
};
return {
state,
source: 'cache',
message: normalizedStatus === 'scanned' ? '二维码已被扫码,请继续绑定' : '获取绑定码成功(缓存)',
};
}
const nextCode = await this.createWechatBindCode();
const expiresAt = now + WECHAT_BIND_CACHE_TTL_SECONDS * 1000;
const pendingState = {
account_id: accountId,
status: 'pending',
code: nextCode,
updated_at: new Date().toISOString(),
ye4s_user_id: null,
expires_at: expiresAt,
scanned_at: null,
};
const tasks = [
this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCodeCache(nextCode, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS),
];
if (cachedCode && cachedCode !== nextCode) {
tasks.push(this.setWechatBindCodeCache(cachedCode, null, 1));
tasks.push(this.setWechatBindScanCache(cachedCode, null, 1));
}
await Promise.all(tasks);
return {
state: pendingState,
source: forceNewCode ? 'refreshed' : 'generated',
message: forceNewCode ? '长轮询超时,已刷新绑定码' : '账号未绑定,已生成绑定码',
};
}
/**
* 用户登录(重构版)
* @param {string} username - 用户名/手机号/邮箱
* @param {string} password - 密码
* @param {string} loginType - 登录类型: username, phone, email, auto
* @param {string} platformCode - 平台编码(web、pda、mini等)
* @return {Object} 登录结果
*/
async login(username, password, loginType = 'auto') {
const { ctx, app } = this;
try {
// 统一的认证错误信息
const authError = new Error('用户名或密码错误或账号状态异常');
authError.code = 'AUTH_FAILED';
// 1. 查找用户
const user = await this.findUserByIdentifier(username, loginType);
if (!user) {
app.coreLogger.warn(`登录失败: 用户不存在 [${username}]`);
throw authError;
}
console.log('登录获取用户信息', user);
// 2. 检查用户状态
try {
this.checkUserStatus(user);
} catch (statusError) {
app.coreLogger.warn(`登录失败: 用户状态异常 [${user.id}] - ${statusError.message}`);
throw authError;
}
// 3. 验证密码
const isPasswordValid = await user.verifyPassword(password);
if (!isPasswordValid) {
app.coreLogger.warn(`登录失败: 密码错误 [${user.id}]`);
throw authError;
}
// 4. 更新最后登录时间
await this.updateLastLoginTime(user.id);
return this.buildLoginResult(user, { includeUser: false });
} catch (error) {
app.coreLogger.error(`登录异常: ${error.message}`);
return {
success: false,
data: null,
code: 0,
message: '用户名或密码错误或账号状态异常',
};
}
}
/**
<<<<<<< HEAD
* 登录码登录:使用Ye4s登录码进行登录
* @param {string} code 登录码(WECHAT_LOGIN_CODE)
* @return {Object} 登录结果
*/
async loginByYe4sCode(code) {
const { ctx, app } = this;
try {
const rawCode = typeof code === 'string' ? code.trim() : '';
if (!rawCode) {
=======
* 登录码登录:使用本系统缓存登录码完成登录
* @param {string} code 登录码(WECHAT_LOGIN_CODE)
* @return {Object} 登录结果
*/
async loginByCode(code) {
const { app } = this;
try {
const normalizedCode = this.parseWechatBindCode(code);
if (!normalizedCode) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return {
success: false,
data: null,
code: 0,
message: '缺少或无效的登录码 code',
};
}
<<<<<<< HEAD
const candidateSet = new Set([ rawCode ]);
try {
const decoded = Buffer.from(rawCode, 'base64').toString('utf8').trim();
if (decoded) {
candidateSet.add(decoded);
if (decoded.startsWith('{') && decoded.endsWith('}')) {
const parsed = JSON.parse(decoded);
const possibleCode = [ parsed && parsed.uuid, parsed && parsed.tmp_code, parsed && parsed.code ]
.map(item => (typeof item === 'string' ? item.trim() : ''))
.filter(Boolean);
for (const item of possibleCode) {
candidateSet.add(item);
}
}
}
} catch (decodeErr) {
// 非 base64/JSON 登录码时忽略解码失败,继续使用原始 code。
}
const codeCandidates = Array.from(candidateSet).filter(item => typeof item === 'string' && item.length > 0);
if (codeCandidates.length === 0) {
return {
success: false,
data: null,
code: 0,
message: '缺少或无效的登录码 code',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const rows = await ye4sClient.select('ye4s_user', {
where: {
tmp_code: codeCandidates,
},
columns: [ 'id', 'tmp_code', 'wms_account_id' ],
orders: [[ 'id', 'DESC' ]],
limit: 1,
});
if (!rows || rows.length === 0) {
=======
const codeCacheKey = this.getWechatLoginCodeCacheKey(normalizedCode);
let codeState = null;
try {
codeState = await this.app.getCacheAsync(codeCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取登录码缓存失败: ${cacheErr.message}`);
}
if (!codeState) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return {
success: false,
data: null,
code: 0,
message: '登录码不存在或已过期',
};
}
<<<<<<< HEAD
const ye4sUserId = Number(rows[0].id);
if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) {
return {
success: false,
data: null,
code: 0,
message: '登录码对应用户无效',
};
}
return await this.loginByYe4sUserId(ye4sUserId);
=======
const codeStateWithCode = {
...(codeState || {}),
code: normalizedCode,
};
let loginResponse = await this.tryBuildWechatLoginTokenFromState(codeState.client_code || '', codeStateWithCode);
if (loginResponse && loginResponse.success) {
return loginResponse;
}
const clientCode = this.parseWechatBindCode(codeState && codeState.client_code);
if (clientCode) {
let clientState = null;
try {
clientState = await this.app.getCacheAsync(this.getWechatLoginClientCacheKey(clientCode));
} catch (cacheErr) {
app.coreLogger.warn(`读取客户端登录状态缓存失败: ${cacheErr.message}`);
}
if (clientState) {
loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, {
...clientState,
code: normalizedCode,
});
if (loginResponse && loginResponse.success) {
return loginResponse;
}
}
}
return {
success: false,
data: null,
code: 0,
message: '登录码尚未授权,请扫码确认后重试',
};
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
} catch (error) {
app.coreLogger.error(`登录码登录异常: ${error.message}`);
return {
success: false,
data: null,
code: 0,
message: '登录失败,请稍后重试',
};
}
}
async waitForLoginCodeRefresh(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs);
await new Promise(resolve => {
setTimeout(resolve, waitMs);
});
}
isTransientWechatLoginError(error) {
if (!error) {
return false;
}
const code = typeof error.code === 'string' ? error.code : '';
const message = typeof error.message === 'string' ? error.message.toLowerCase() : '';
const transientCodes = new Set([ 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'PROTOCOL_CONNECTION_LOST', 'ECONNREFUSED' ]);
if (transientCodes.has(code)) {
return true;
}
return message.includes('econnreset') || message.includes('read econnreset') || message.includes('connection lost') || message.includes('timeout');
}
extractYe4sUserIdFromLoginEvent(eventData) {
if (!eventData) {
return null;
}
if (typeof eventData === 'number' || typeof eventData === 'string') {
const id = Number(eventData);
return Number.isFinite(id) && id > 0 ? id : null;
}
if (typeof eventData !== 'object') {
return null;
}
const rawId = eventData.ye4s_user_id ?? eventData.ye4sUserId ?? eventData.user_id ?? eventData.userId ?? eventData.value;
const ye4sUserId = Number(rawId);
return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null;
}
async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
const { app } = this;
const normalizedClientCode = this.parseWechatBindCode(clientCode);
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis || !normalizedClientCode || typeof cacheRedis.duplicate !== 'function') {
return {
timed_out: true,
reason: 'redis_not_available',
event: null,
};
}
const channel = this.getWechatLoginEventChannel(normalizedClientCode);
const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs);
const subscriber = cacheRedis.duplicate();
return await new Promise(resolve => {
let settled = false;
let timer = null;
const cleanup = () => {
subscriber.removeListener('message', onMessage);
subscriber.removeListener('error', onError);
Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => {
if (typeof subscriber.quit === 'function') {
Promise.resolve(subscriber.quit()).catch(() => {
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
return;
}
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
};
const finalize = result => {
if (settled) {
return;
}
settled = true;
if (timer) {
clearTimeout(timer);
}
cleanup();
resolve(result);
};
const onMessage = (messageChannel, message) => {
if (messageChannel !== channel) {
return;
}
let eventData = null;
try {
eventData = message ? JSON.parse(message) : null;
} catch (error) {
eventData = message;
}
const ye4sUserId = this.extractYe4sUserIdFromLoginEvent(eventData);
finalize({
timed_out: false,
reason: 'event',
event: eventData,
ye4s_user_id: ye4sUserId,
});
};
const onError = error => {
app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_error',
event: null,
});
};
timer = setTimeout(() => {
finalize({
timed_out: true,
reason: 'timeout',
event: null,
});
}, waitMs);
subscriber.on('message', onMessage);
subscriber.on('error', onError);
Promise.resolve(subscriber.subscribe(channel)).catch(error => {
app.coreLogger.warn(`订阅微信登录频道失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_failed',
event: null,
});
});
});
}
async loginByYe4sUserId(ye4sUserId) {
const { ctx, app } = this;
const normalizedYe4sUserId = Number(ye4sUserId);
if (!Number.isFinite(normalizedYe4sUserId) || normalizedYe4sUserId <= 0) {
return {
success: false,
code: 0,
data: null,
message: '登录事件缺少有效的 ye4s_user_id',
};
}
const maxAttempts = 2;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const ye4sClient = ctx.app.mysql.get('ye4s');
const ye4sUser = await ye4sClient.get('ye4s_user', { id: normalizedYe4sUserId });
if (!ye4sUser) {
return {
success: false,
code: 0,
data: null,
message: 'ye4s 用户不存在',
};
}
const wmsAccountId = Number(ye4sUser.wms_account_id);
if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) {
return {
success: false,
code: 0,
data: null,
message: '该 ye4s 用户未绑定WMS账号',
};
}
const user = await ctx.model.Account.findOne({
where: { id: wmsAccountId },
});
if (!user) {
return {
success: false,
code: 0,
data: null,
message: '绑定的WMS账号不存在',
};
}
try {
this.checkUserStatus(user);
} catch (statusError) {
app.coreLogger.warn(`微信事件登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`);
return {
success: false,
code: 0,
data: null,
message: '绑定账号状态异常',
};
}
await this.updateLastLoginTime(user.id);
const loginResult = await this.buildLoginResult(user, { includeUser: false });
return loginResult;
} catch (error) {
const isTransient = this.isTransientWechatLoginError(error);
if (isTransient && attempt < maxAttempts) {
app.coreLogger.warn(`微信事件登录异常,准备重试(${attempt}/${maxAttempts}): ${error.message}`);
await this.waitForLoginCodeRefresh(200);
continue;
}
app.coreLogger.error(`微信事件登录异常: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '登录失败,请稍后重试',
};
}
}
return {
success: false,
code: 0,
data: null,
message: '登录失败,请稍后重试',
};
}
async tryBuildWechatLoginTokenFromState(clientCode, state) {
const eventYe4sUserId = this.extractYe4sUserIdFromLoginEvent(state);
if (!Number.isFinite(Number(eventYe4sUserId)) || Number(eventYe4sUserId) <= 0) {
return null;
}
const loginResult = await this.loginByYe4sUserId(eventYe4sUserId);
if (!loginResult || !loginResult.success || !loginResult.data || !loginResult.data.token) {
return {
success: false,
code: 0,
data: null,
message: loginResult && loginResult.message ? loginResult.message : '登录事件处理失败',
};
}
const cleanupCode = state && typeof state.code === 'string' ? state.code.trim().toUpperCase() : '';
await Promise.all([
this.setWechatLoginClientCache(clientCode, null, 1),
cleanupCode ? this.setWechatLoginCodeCache(cleanupCode, null, 1) : Promise.resolve(),
]);
return {
success: true,
code: 200,
data: {
client_code: clientCode,
status: 'authorized',
source: 'event',
ye4s_user_id: Number(eventYe4sUserId),
loginToken: loginResult.data.token,
},
message: '已收到登录事件并签发登录令牌',
};
}
async refreshWechatLoginState(clientCode, cachedState = null, options = {}) {
const now = Date.now();
const forceNewCode = options.forceNewCode === true;
const normalizedClientCode = this.parseWechatBindCode(clientCode);
if (!normalizedClientCode) {
throw new Error('无效的客户端编码格式');
}
const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : '';
const cachedExpiresAt = Number(cachedState && cachedState.expires_at);
const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(cachedExpiresAt) && cachedExpiresAt > now;
if (cachedCodeValid) {
return {
state: {
client_code: normalizedClientCode,
code: cachedCode,
status: 'pending',
updated_at: cachedState.updated_at || new Date().toISOString(),
expires_at: cachedExpiresAt,
},
source: 'cache',
message: `客户端编码 ${normalizedClientCode} 已命中缓存登录码`,
};
}
const nextCode = await this.createWechatLoginCode();
const expiresAt = now + WECHAT_LOGIN_CACHE_TTL_SECONDS * 1000;
const loginState = {
client_code: normalizedClientCode,
code: nextCode,
status: 'pending',
updated_at: new Date().toISOString(),
expires_at: expiresAt,
};
const tasks = [
this.setWechatLoginClientCache(normalizedClientCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS),
this.setWechatLoginCodeCache(nextCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS),
];
if (cachedCode && cachedCode !== nextCode) {
tasks.push(this.setWechatLoginCodeCache(cachedCode, null, 1));
}
await Promise.all(tasks);
return {
state: loginState,
source: forceNewCode ? 'refreshed' : 'generated',
message: forceNewCode ?
`客户端编码 ${normalizedClientCode} 长轮询结束,已刷新登录码` :
`客户端编码 ${normalizedClientCode} 已生成登录码`,
};
}
/**
* 获取微信扫码登录码
* @param {Object} data
* @return {Object}
*/
async getLoginWechatCode(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;
let clientCode = '';
let shouldWaitRefresh = false;
let cachedState = null;
if (hasInputClientCode) {
const normalizedClientCode = this.parseWechatBindCode(rawClientCode);
if (!normalizedClientCode) {
return {
success: false,
code: 0,
data: null,
message: '无效的客户端编码格式',
};
}
const inputClientCacheKey = this.getWechatLoginClientCacheKey(normalizedClientCode);
try {
cachedState = await this.app.getCacheAsync(inputClientCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`);
}
// 传入 clientCode 但缓存不存在时,按空值处理,重新分配新的客户端编码。
if (cachedState) {
clientCode = normalizedClientCode;
shouldWaitRefresh = true;
} else {
clientCode = await this.createWechatLoginClientCode();
}
} else {
clientCode = await this.createWechatLoginClientCode();
}
const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode);
if (!cachedState) {
try {
cachedState = await this.app.getCacheAsync(clientCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`);
}
}
// 若外部已将 ye4s_user_id 写入 clientCode 对应缓存,直接登录并返回,不再等待长轮询。
if (hasInputClientCode && cachedState) {
const immediateLoginResult = await this.tryBuildWechatLoginTokenFromState(clientCode, cachedState);
if (immediateLoginResult && immediateLoginResult.success) {
return immediateLoginResult;
}
if (immediateLoginResult && immediateLoginResult.success === false) {
app.coreLogger.warn(`微信登录缓存态直登失败,继续轮询: ${immediateLoginResult.message}`);
}
}
if (shouldWaitRefresh) {
const waitResult = await this.waitForWechatLoginEvent(clientCode, this.getWechatLongPollTimeoutMs());
const eventYe4sUserId = Number(waitResult && waitResult.ye4s_user_id);
if (!waitResult.timed_out && Number.isFinite(eventYe4sUserId) && eventYe4sUserId > 0) {
const eventState = {
...(cachedState || {}),
ye4s_user_id: eventYe4sUserId,
};
const loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, eventState);
if (loginResponse && loginResponse.success) {
return loginResponse;
}
app.coreLogger.warn(`微信事件登录未成功,降级为刷新登录码: ${loginResponse && loginResponse.message ? loginResponse.message : 'unknown_error'}`);
}
try {
cachedState = await this.app.getCacheAsync(clientCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`);
}
const refreshed = await this.refreshWechatLoginState(clientCode, cachedState, {
forceNewCode: true,
});
return {
success: true,
code: 200,
data: this.formatLoginWechatData(refreshed.state, refreshed.source),
message: refreshed.message,
};
}
const generated = await this.refreshWechatLoginState(clientCode, cachedState, {
forceNewCode: false,
});
return {
success: true,
code: 200,
data: this.formatLoginWechatData(generated.state, generated.source),
message: generated.message,
};
} catch (error) {
app.coreLogger.error(`获取微信登录码失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '获取微信登录码失败,请稍后重试',
};
}
}
/**
* 获取微信绑定码(缓存优先,低频复查DB,适配轮询)
* @param {Object} data
* @return {Object}
*/
async getBindWechatCode(data = {}) {
const accountId = this.getCurrentAccountId();
return await this.getBindWechatCodeByAccountId(accountId, data, {
missingAccountMessage: '未识别到登录账号,无法生成绑定码',
});
}
async getBindWechatCodeByAccountId(accountId, data = {}, options = {}) {
const { app } = this;
try {
const normalizedAccountId = Number(accountId);
if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) {
return {
success: false,
code: 0,
data: null,
message: options.missingAccountMessage || '未识别到目标账号,无法生成绑定码',
};
}
<<<<<<< HEAD
const cacheKey = this.getWechatBindCacheKey(normalizedAccountId);
=======
const cacheKey = this.getWechatBindCacheKey(accountId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const useLongPoll = this.shouldUseWechatBindLongPoll(data);
const waitTimeoutMs = this.getWechatLongPollTimeoutMs();
let cachedState = null;
try {
cachedState = await this.app.getCacheAsync(cacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
<<<<<<< HEAD
const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, {
=======
const refreshed = await this.refreshWechatBindState(accountId, cachedState, {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
forceNewCode: false,
});
if (refreshed.state.status === 'bound' || !useLongPoll) {
return {
success: true,
code: 200,
data: this.formatBindWechatData(refreshed.state, refreshed.source),
message: refreshed.message,
};
}
<<<<<<< HEAD
const waitResult = await this.waitForWechatBindEvent(normalizedAccountId, waitTimeoutMs);
=======
const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
try {
cachedState = await this.app.getCacheAsync(cacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
<<<<<<< HEAD
const nextState = await this.refreshWechatBindState(normalizedAccountId, cachedState, {
=======
const nextState = await this.refreshWechatBindState(accountId, cachedState, {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
forceNewCode: waitResult.timed_out,
});
if (waitResult.timed_out) {
return {
success: true,
code: 200,
data: this.formatBindWechatData(nextState.state, nextState.source),
message: '长轮询结束未检测到状态变化,已刷新绑定码',
};
}
return {
success: true,
code: 200,
data: this.formatBindWechatData(nextState.state, nextState.source),
message: nextState.message,
};
} catch (error) {
app.coreLogger.error(`获取微信绑定码失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '获取绑定码失败,请稍后重试',
};
}
}
/**
* 根据绑定临时码获取账号ID(供 ye4s 扫码绑定调用)
* @param {Object} data
* @return {Object}
*/
async getUserByTempCode(data = {}) {
const { ctx, app } = this;
try {
const loadAccountRealName = async accountId => {
const account = await ctx.model.Account.findOne({
where: {
id: accountId,
},
attributes: [ 'id', 'real_name' ],
raw: true,
});
return account && account.real_name ? account.real_name : '';
};
const rawCode = typeof data.code === 'string' ? data.code.trim() : '';
if (!rawCode) {
return {
success: false,
code: 0,
data: null,
message: '缺少绑定码 code',
};
}
const code = this.parseWechatBindCode(rawCode);
if (!code) {
return {
success: false,
code: 0,
data: null,
message: '无效的绑定码格式',
};
}
const codeCacheKey = this.getWechatBindCodeCacheKey(code);
let codeState = null;
try {
codeState = await this.app.getCacheAsync(codeCacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取绑定码映射缓存失败: ${cacheErr.message}`);
}
const cachedAccountId = Number(codeState && codeState.account_id);
if (!Number.isFinite(cachedAccountId) || cachedAccountId <= 0) {
return {
success: false,
code: 0,
data: null,
message: '绑定码不存在或已过期',
};
}
const realName = await loadAccountRealName(cachedAccountId);
const scanState = {
account_id: cachedAccountId,
code,
status: 'scanned',
scanned_at: new Date().toISOString(),
source: 'gateway-scan',
};
const codeExpiresAt = Number(codeState && codeState.expires_at);
const scannedBindState = {
account_id: cachedAccountId,
code,
status: 'scanned',
scanned_at: scanState.scanned_at,
updated_at: scanState.scanned_at,
ye4s_user_id: null,
expires_at: Number.isFinite(codeExpiresAt) ? codeExpiresAt : null,
};
const bindCacheTtl = this.getRemainingSecondsByExpiresAt(codeExpiresAt, WECHAT_BIND_CACHE_TTL_SECONDS);
await Promise.all([
this.setWechatBindScanCache(code, scanState, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS),
this.setWechatBindCache(this.getWechatBindCacheKey(cachedAccountId), scannedBindState, bindCacheTtl),
]);
await this.publishWechatBindEvent(cachedAccountId, {
status: 'scanned',
code,
scanned_at: scanState.scanned_at,
source: 'gateway-scan',
});
return {
success: true,
code: 200,
data: {
account_id: cachedAccountId,
real_name: realName,
code,
status: 'scanned',
source: 'scan-cache',
scanned_at: scanState.scanned_at,
updated_at: codeState && codeState.updated_at ? codeState.updated_at : scanState.scanned_at,
},
message: '扫码状态已记录',
};
} catch (error) {
app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '获取账号失败,请稍后重试',
};
}
}
/**
* 账号绑定:供 ye4s 扫码后回调,按临时码绑定到指定 ye4s_user.id
* @param {Object} data
* @return {Object}
*/
async bindAccountByTempCode(data = {}) {
const { ctx, app } = this;
try {
const rawCode = typeof data.code === 'string' ? data.code.trim() : '';
const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId;
const ye4sUserId = Number(rawYe4sUserId);
if (!rawCode) {
return {
success: false,
code: 0,
data: null,
message: '缺少绑定码 code',
};
}
const code = this.parseWechatBindCode(rawCode);
if (!code) {
return {
success: false,
code: 0,
data: null,
message: '无效的绑定码格式',
};
}
if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) {
return {
success: false,
code: 0,
data: null,
message: '缺少有效的 ye4s_user_id',
};
}
const scanState = await this.getWechatBindScanCache(code);
const accountId = Number(scanState && scanState.account_id);
if (!Number.isFinite(accountId) || accountId <= 0) {
return {
success: false,
code: 0,
data: null,
message: '未检测到扫码记录或扫码状态已过期,请重新扫码',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const ye4sUser = await ye4sClient.get('ye4s_user', { id: ye4sUserId });
if (!ye4sUser) {
return {
success: false,
code: 0,
data: null,
message: 'ye4s 用户不存在',
};
}
const updateRet = await ye4sClient.update('ye4s_user', {
id: ye4sUserId,
wms_account_id: accountId,
});
const boundState = {
account_id: accountId,
status: 'bound',
code: '',
updated_at: new Date().toISOString(),
ye4s_user_id: ye4sUserId,
expires_at: null,
scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null,
};
await Promise.all([
this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCodeCache(code, null, 1),
this.setWechatBindScanCache(code, {
...scanState,
status: 'bound',
ye4s_user_id: ye4sUserId,
bound_at: boundState.updated_at,
}, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS),
]);
await this.publishWechatBindEvent(accountId, {
status: 'bound',
code: '',
source: 'gateway-bind',
});
return {
success: true,
code: 200,
data: {
account_id: accountId,
ye4s_user_id: ye4sUserId,
code,
status: 'bound',
source: 'gateway-bind',
affected_rows: Number(updateRet && updateRet.affectedRows ? updateRet.affectedRows : 0),
updated_at: boundState.updated_at,
},
message: '绑定成功',
};
} catch (error) {
app.coreLogger.error(`账号绑定失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '绑定失败,请稍后重试',
};
}
}
/**
* 解绑微信:清理 ye4s_user 中与当前账号关联的数据
* @return {Object}
*/
async unbindWechat() {
const accountId = this.getCurrentAccountId();
return await this.unbindWechatByAccountId(accountId, {
missingAccountMessage: '未识别到登录账号,无法解绑',
});
}
async unbindWechatByAccountId(accountId, options = {}) {
const { ctx, app } = this;
try {
const normalizedAccountId = Number(accountId);
if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) {
return {
success: false,
code: 0,
data: null,
message: options.missingAccountMessage || '未识别到目标账号,无法解绑',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const bindRows = await ye4sClient.select('ye4s_user', {
where: {
wms_account_id: normalizedAccountId,
},
columns: [ 'id', 'tmp_code', 'wms_account_id' ],
orders: [[ 'id', 'desc' ]],
limit: 500,
});
let affectedRows = 0;
for (const row of bindRows) {
try {
const ret = await ye4sClient.update('ye4s_user', {
id: row.id,
wms_account_id: null,
});
affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0);
} catch (err) {
const ret = await ye4sClient.update('ye4s_user', {
id: row.id,
wms_account_id: 0,
});
affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0);
}
}
<<<<<<< HEAD
const cacheKey = this.getWechatBindCacheKey(normalizedAccountId);
=======
const cacheKey = this.getWechatBindCacheKey(accountId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await this.setWechatBindCache(cacheKey, null, 1);
await this.publishWechatBindEvent(normalizedAccountId, {
status: 'unbound',
source: 'unbind',
});
return {
success: true,
code: 200,
data: {
account_id: normalizedAccountId,
status: 'unbound',
matched_rows: bindRows.length,
affected_rows: affectedRows,
updated_at: new Date().toISOString(),
},
message: bindRows.length > 0 ? '解绑成功' : '当前账号未绑定微信',
};
} catch (error) {
app.coreLogger.error(`解绑微信失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '解绑失败,请稍后重试',
};
}
}
/**
* 生成统一登录成功结构
* @param {Object} user
* @return {Object}
*/
async buildLoginResult(user, options = {}) {
const { ctx, app } = this;
const includeUser = options.includeUser !== false;
// 设置设备类型(用于菜单查询)
const platformCode = ctx.header.platform || 'web';
// 获取用户完整信息
const userInfo = await this.findById(user.id);
console.log('用户信息', userInfo);
if (!userInfo) {
throw new Error('用户信息加载失败');
}
// 如果用户有角色但当前平台没有激活角色,则自动设置一个
if (userInfo && userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) {
await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode);
}
// 生成 JWT Token
const tokenPayload = {
id: user.id,
username: user.username,
real_name: user.real_name,
platform_code: platformCode,
current_role_id: userInfo.employees_id,
current_store_id: userInfo.store_id || null,
};
const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, {
expiresIn: app.config.jwt.expiresIn,
});
const payloadData = {
token,
};
if (includeUser) {
payloadData.user = {
id: user.id,
username: user.username,
real_name: user.real_name,
phone: user.phone,
email: user.email,
status: user.status,
last_login_at: user.last_login_at,
roles: userInfo.roles,
role_id: userInfo.role_id,
menus: userInfo.menus,
permissions: userInfo.permissions,
userRole: userInfo.userRole,
realName: userInfo.realName,
};
}
return {
success: true,
data: payloadData,
code: 200,
message: '登录成功',
};
}
/**
* 切换角色(重构版)
* @param {Object} data - 切换角色数据
* @param {number} data.roleId - 角色关联ID (account_store_role.id)
* @param {string} data.platformCode - 平台编码(web、pda、mini等)
* @return {Object} 切换结果
*/
async changeRole(data) {
const { ctx, app } = this;
const user = ctx.state.user || ctx.user;
try {
// 验证角色关联是否存在且有效
const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({
where: {
id: data.roleId,
account_id: user.id,
status: 1,
},
include: [
{
model: ctx.model.EmployeeRole,
as: 'employeeRoles',
},
],
});
if (!accountStoreEmployee) {
throw new Error('角色不存在或未授权');
}
const platformCode = ctx.header.platform || 'web';
// 更新平台激活角色
await ctx.model.AccountPlatformActive.upsert({
account_id: user.id,
employee_id: data.roleId,
platform_code: platformCode,
});
// 清理缓存
await this.clearUserCache(user.id);
// 获取更新后的用户信息
const userInfo = await this.findById(user.id);
const tokenPayload = {
id: user.id,
username: user.username,
real_name: user.real_name,
platform_code: platformCode,
current_role_id: userInfo.employees_id,
current_store_id: accountStoreEmployee.store_id || null,
};
const newToken = app.jwt.sign(tokenPayload, app.config.jwt.secret, {
expiresIn: app.config.jwt.expiresIn,
});
return {
success: true,
data: {
user: userInfo,
token: newToken,
},
code: 200,
message: '角色切换成功',
};
} catch (error) {
app.coreLogger.error(`切换角色失败: ${error.message}`);
return {
success: false,
data: null,
code: 0,
message: error.message || '角色切换失败',
};
}
}
/**
* 获取用户信息(重构版)
* @param {Object} data - 请求数据
* @return {Object} 用户信息
*/
async info(data) {
const { ctx } = this;
try {
const userId = ctx.userId || (ctx.user && ctx.user.id);
const user = await this.findById(userId);
return {
success: true,
data: user,
code: 200,
};
} catch (error) {
console.log(error);
return {
success: false,
data: null,
code: 0,
};
}
}
/**
* 查找用户所有的角色以及对应的主体(重构版)
* @param {number} userId - 用户ID
* @param {string} platformCode - 平台编码
* @return {Promise<Array>}
*/
async getRoles(userId) {
const { ctx } = this;
const platformCode = ctx.header.platform || 'web';
const project = ctx.header.project;
try {
const loadAccountStoreEmployees = async projectFilter => {
const store_where = {
status: 1,
};
if (projectFilter && projectFilter !== 'all') {
store_where.project = projectFilter;
}
console.log('store_where', store_where, projectFilter, platformCode, ctx.header);
return ctx.model.AccountStoreEmployee.findAll({
where: {
account_id: userId,
status: 1,
},
include: [
{
model: ctx.model.EmployeeRole,
as: 'employeeRoles',
attributes: [ 'id', 'role_id' ],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name', 'project', 'auth_end' ],
where: store_where,
},
],
order: [[ 'created_at', 'DESC' ]],
});
};
// 先按请求 project 过滤;查不到时降级到 all,便于补齐平台激活记录。
let accountStoreEmployees = await loadAccountStoreEmployees(project);
if ((!accountStoreEmployees || accountStoreEmployees.length === 0) && project && project !== 'all') {
accountStoreEmployees = await loadAccountStoreEmployees('all');
}
if (!accountStoreEmployees || accountStoreEmployees.length === 0) {
return {
Employees: [],
activeEmployeeId: null,
menus: [],
permissions: [],
userRole: '',
realName: null,
};
}
console.log('accountStoreEmployees>>>>>', accountStoreEmployees);
// 获取当前平台的激活角色
let activeEmployeeId = null;
let realName = null;
let userRole = '';
let currentPlatformEmployeeId = null;
const platformActive = await ctx.model.AccountPlatformActive.findOne({
where: {
account_id: userId,
platform_code: platformCode,
},
attributes: [ 'account_id', 'employee_id', 'platform_code' ],
});
if (platformActive) {
currentPlatformEmployeeId = platformActive.employee_id;
}
// 转换数据格式
const Employees = accountStoreEmployees.map(item => ({
id: item.id,
store_id: item.store_id,
store_name: item.store.company_name,
is_primary: currentPlatformEmployeeId === item.id ? 1 : 0,
real_name: item.real_name,
auth_end: item.store.auth_end,
role_type: item.store.project,
}));
// 确定当前激活角色
for (const Employee of Employees) {
if (Employee.is_primary == 1) {
activeEmployeeId = Employee.id;
realName = Employee.real_name;
userRole = Employee.role_type == 1 ? 'warehouse' : 'customer';
break;
}
}
// 如果没有激活角色,选择第一个
if (!activeEmployeeId && Employees.length > 0) {
activeEmployeeId = Employees[0].id;
realName = Employees[0].real_name;
userRole = Employees[0].role_type == 1 ? 'warehouse' : 'customer';
// 设置为激活角色
if (Employees[0].id) {
await this.ensurePlatformActiveRole(userId, Employees[0].id, platformCode);
}
}
// 获取菜单和权限
const menus = await this.getMenus(activeEmployeeId);
console.log('获取菜单', activeEmployeeId, menus);
const permissions = await this.getPermissions(activeEmployeeId);
return { Employees, activeEmployeeId, menus, permissions, userRole, realName };
} catch (error) {
console.error('获取用户角色失败:', error);
return {
Employees: [],
activeEmployeeId: null,
menus: [],
permissions: [],
userRole: '',
realName: null,
};
}
}
/**
* 根据ID查找用户(重构版)
* @param {number} userId - 用户ID
* @param {string} platformCode - 平台编码
* @param useCache
* @return {Promise<Object>}
*/
async findById(userId, useCache = true) {
const { ctx } = this;
const platformCode = ctx.header.platform || 'web';
const project = ctx.header.project;
console.log(`调用${ctx.query_count}次,平台为${platformCode}`);
ctx.query_count++;
try {
// 生成缓存key
const cacheKey = `user:info:${userId}:${platformCode}`;
// 1. 尝试从缓存获取
if (useCache) {
try {
const cachedUser = await this.app.getCacheAsync(cacheKey);
if (cachedUser) {
console.log('用户信息缓存命中:', userId);
return cachedUser;
}
} catch (cacheError) {
console.warn('获取用户缓存失败:', cacheError.message);
// 缓存失败不影响主流程,继续查询数据库
}
}
// 2. 从数据库获取用户基本信息
const user = await this.ctx.model.Account.findOne({
where: { id: userId },
attributes: [ 'id', 'real_name', 'email', 'status', 'username', 'phone', 'last_login_at', 'last_login_ip' ],
});
if (!user) {
// 如果用户不存在,也缓存null值避免频繁查询
if (useCache) {
await this.setUserCache(cacheKey, null, 300); // 缓存5分钟
}
return null;
}
// 3. 获取角色信息(这个方法内部也有缓存逻辑)
let { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId);
console.log('activeEmployeeId>>>>>>>>', activeEmployeeId);
// pda 场景若缺少激活角色,优先补一条当前平台激活记录,避免直接报错。
if (platformCode == 'pda' && !activeEmployeeId && Employees.length > 0) {
const fallbackEmployee = Employees[0];
await this.ensurePlatformActiveRole(userId, fallbackEmployee.id, platformCode);
activeEmployeeId = fallbackEmployee.id;
userRole = fallbackEmployee.role_type == 1 ? 'warehouse' : 'customer';
realName = fallbackEmployee.real_name || realName;
menus = await this.getMenus(activeEmployeeId);
permissions = await this.getPermissions(activeEmployeeId);
}
// 4. 获取当前角色对应的仓库ID
let storeId = null;
let storeName = null;
let storeCode = null;
let roleName = null;
let auth_end = null;
let employees_name = null;
if (activeEmployeeId && Employees.length > 0) {
const currentRole = Employees.find(Employee => Employee.id === activeEmployeeId);
if (currentRole) {
storeId = currentRole.store_id;
storeName = currentRole.store_name;
storeCode = currentRole.store_code;
roleName = currentRole.role_name;
employees_name = currentRole.real_name;
auth_end = currentRole.auth_end;
}
}
const avatar = await this.getAvatarByEmployeeId(activeEmployeeId);
if (platformCode == 'pda' && !activeEmployeeId) {
ctx.logger.warn(`pda 平台未找到可激活角色,accountId=${userId},将以空角色上下文返回`);
}
// 5. 组合用户信息
const userInfo = {
id: user.id,
status: user.status,
employees: Employees,
auth_end,
employees_id: activeEmployeeId,
employees_name: employees_name || '未命名',
loginIp: user.last_login_ip,
role_name: roleName,
store_id: storeId,
store_name: storeName,
store_code: storeCode,
menus,
permissions,
userRole,
platform_code: platformCode,
avatar,
cached_at: new Date().toISOString(),
};
// 6. 设置缓存
if (useCache) {
console.log('设置用户缓存', userInfo);
await this.setUserCache(cacheKey, userInfo, 300); // 缓存5分钟
}
console.log('用户信息数据库查询:', userId);
return userInfo;
} catch (error) {
console.error('根据ID查找用户失败:', error);
return null;
}
}
/**
* 设置用户缓存
* @param cacheKey
* @param userInfo
* @param ttl
* @private
*/
async setUserCache(cacheKey, userInfo, ttl = 300) {
try {
// 移除缓存标识字段
if (userInfo) {
const { cached_at, ...cacheData } = userInfo;
await this.app.setCacheAsync(cacheKey, cacheData, ttl);
} else {
await this.app.setCacheAsync(cacheKey, null, ttl);
}
} catch (error) {
console.warn('设置用户缓存失败:', error.message);
}
}
async getAvatarByEmployeeId(employeeId) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
let url = '';
const image = await ctx.model.FileReference.findOne({
where: {
business_type: 'avater',
business_id: employeeId,
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
});
if (image) {
url = image.file.file_url;
}
return url;
}
/**
* 清除用户缓存
* @param userId
* @param platformCode
*/
async clearUserCache(userId, platformCode = null) {
try {
if (platformCode) {
// 清除指定平台的缓存
const cacheKey = `user:info:${userId}:${platformCode}`;
await this.app.setCacheAsync(cacheKey, null, 1);
} else {
// 清除用户所有平台的缓存
const platforms = [ 'web', 'pda', 'mini', 'app' ];
for (const platform of platforms) {
const cacheKey = `user:info:${userId}:${platform}`;
await this.app.setCacheAsync(cacheKey, null, 1);
}
}
// 同时清除相关的缓存
await this.clearRelatedCache(userId);
console.log('用户缓存已清除:', userId);
return true;
} catch (error) {
console.warn('清除用户缓存失败:', error.message);
return false;
}
}
/**
* 清除用户相关缓存
* @param userId
* @private
*/
async clearRelatedCache(userId) {
try {
// 清除用户基本信息缓存
const basicCacheKeys = [
`user:basic:${userId}`,
`account:username:${userId}`,
`account:phone:${userId}`,
`account:email:${userId}`,
];
for (const key of basicCacheKeys) {
await this.app.setCacheAsync(key, null, 1);
}
// 清除用户角色缓存
const roleCacheKey = `user:roles:${userId}`;
await this.app.setCacheAsync(roleCacheKey, null, 1);
// 清除用户权限缓存
const permCacheKeys = [
`user:permissions:${userId}`,
`user:menus:${userId}`,
];
for (const key of permCacheKeys) {
await this.app.setCacheAsync(key, null, 1);
}
} catch (error) {
console.warn('清除相关缓存失败:', error.message);
}
}
/**
* 获取权限列表(重构版)
* @param {number} roleId - 角色ID
* @param activeEmployeeId
* @return {Promise<Array>}
*/
async getPermissions(activeEmployeeId) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
if (!activeEmployeeId) {
return [];
}
try {
// 1. 获取员工绑定且启用的角色
const roles = await ctx.model.EmployeeRole.findAll({
attributes: [ 'role_id' ],
where: {
employee_id: activeEmployeeId,
},
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [],
where: {
status: 1,
},
required: true,
},
],
raw: true, // 获取纯数据对象
});
console.log('员工绑定的角色', roles);
if (!roles || roles.length === 0) {
return [];
}
const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ];
if (roleIds.length === 0) {
return [];
}
// 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表)
const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
includeDisabled: false,
});
if (permissionIds.length === 0) {
return [];
}
const permissions = await ctx.model.Permission.findAll({
where: {
id: {
[Op.in]: permissionIds,
},
status: 1,
// 修正 like 查询
type: {
[ctx.app.Sequelize.Op.notLike]: '%_pages',
},
},
attributes: [ 'id', 'path', 'type' ],
order: [
[ 'sort', 'ASC' ],
],
});
console.log('permissions列表', permissions);
if (!permissions) {
return [];
}
return permissions.map(item => item.path);
} catch (error) {
console.error('获取权限列表失败:', error);
return [];
}
}
async getMenus(activeEmployeeId) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
console.log('获取员工菜单员工id:', activeEmployeeId);
if (!ctx.header.platform || !activeEmployeeId) {
return [];
}
try {
// 1. 获取员工绑定且启用的角色
const roles = await ctx.model.EmployeeRole.findAll({
attributes: [ 'role_id' ],
where: {
employee_id: activeEmployeeId,
},
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [],
where: {
status: 1,
},
required: true,
},
],
raw: true, // 获取纯数据对象
});
console.log('员工绑定的角色', roles);
if (!roles || roles.length === 0) {
return [];
}
const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ];
if (roleIds.length === 0) {
return [];
}
// 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表)
const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
includeDisabled: false,
});
if (permissionIds.length === 0) {
return [];
}
// 3. 获取权限对应的菜单(根据设备筛选)
const permissions = await ctx.model.Permission.findAll({
where: {
id: {
[Op.in]: permissionIds,
},
status: 1,
// 修正 like 查询
type: {
[Op.like]: `${ctx.header.platform}_%`,
},
},
order: [
[ 'sort', 'ASC' ],
],
});
if (!permissions || permissions.length === 0) {
return [];
}
return this.convertToRoutes(permissions);
} catch (error) {
ctx.logger.error('获取菜单列表失败:', error);
return [];
}
}
/**
* 转换权限为路由格式(保持不变)
* @param data
*/
async convertToRoutes(data) {
const map = new Map();
const roots = [];
// 创建所有节点的映射
data.forEach(item => {
map.set(item.id, {
id: item.id,
path: item.path,
component: item.component,
name: item.name,
redirect: item.redirect,
meta: {
title: item.meta_title,
icon: item.meta_icon,
},
hidden: item.hidden === 1,
alwaysShow: item.always_show === 1,
sort: item.sort,
children: [],
});
});
// 构建树形结构
data.forEach(item => {
const node = map.get(item.id);
if (!item.parent_id) {
roots.push(node);
} else {
const parent = map.get(item.parent_id);
if (parent) {
parent.children.push(node);
}
}
});
// 递归排序函数
const sortTree = nodes => {
if (!nodes || nodes.length === 0) return;
nodes.sort((a, b) => {
return a.sort - b.sort || a.id - b.id;
});
nodes.forEach(node => {
if (node.children && node.children.length > 0) {
sortTree(node.children);
}
});
};
// 从根节点开始排序
sortTree(roots);
// 移除辅助字段
const cleanNode = node => {
const { id, sort, ...rest } = node;
if (rest.children && rest.children.length > 0) {
rest.children = rest.children.map(child => cleanNode(child));
}
return rest;
};
return roots.map(root => cleanNode(root));
}
/**
* 根据标识符查找用户(已重构)
* @param identifier
* @param type
* @param useCache
*/
async findUserByIdentifier(identifier, type = 'auto', useCache = true) {
const { ctx, app } = this;
let user;
if (type === 'auto') {
// 自动判断类型
const Op = app.Sequelize.Op;
if (/^1[3-9]\d{9}$/.test(identifier)) {
// 手机号格式
user = await ctx.model.Account.findOne({
where: { phone: identifier },
});
} else if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(identifier)) {
// 邮箱格式
user = await ctx.model.Account.findOne({
where: { email: identifier },
});
} else {
// 默认按用户名
user = await ctx.model.Account.findOne({
where: { username: identifier },
});
}
} else {
// 指定类型
let whereCondition = {};
switch (type) {
case 'phone':
whereCondition = { phone: identifier };
break;
case 'email':
whereCondition = { email: identifier };
break;
case 'username':
default:
whereCondition = { username: identifier };
break;
}
user = await ctx.model.Account.findOne({
where: whereCondition,
});
}
if (user) {
// 设置标志,表示不隐藏敏感字段
user._hideSensitive = false;
}
return user;
}
/**
* 检查用户状态(保持不变)
* @param user
*/
checkUserStatus(user) {
if (user.status === 0) {
throw new Error('账号已被禁用,请联系管理员');
}
if (user.status === 2) {
throw new Error('账号已离职,无法登录');
}
if (user.status !== 1) {
throw new Error('账号状态异常');
}
}
/**
* 验证密码(重构版)
* @param inputPassword
* @param storedHash
* @param salt
*/
async verifyPassword(inputPassword, storedHash, salt) {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update(inputPassword + salt);
const encryptedPassword = hash.digest('hex');
if (encryptedPassword !== storedHash) {
throw new Error('密码错误');
}
return true;
}
/**
* 加密密码(保持不变)
* @param password
* @param salt
*/
async encryptPassword(password, salt) {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update(password + salt);
return hash.digest('hex');
}
/**
* 生成密码盐(保持不变)
*/
generateSalt() {
const crypto = require('crypto');
return crypto.randomBytes(10).toString('hex');
}
/**
* 更新最后登录时间(重构版)
* @param userId
*/
async updateLastLoginTime(userId) {
const { ctx } = this;
console.log('登录上下文', ctx.request.header['x-real-ip']);
await ctx.model.Account.update({
last_login_at: new Date(),
last_login_ip: ctx.request.header['x-real-ip'],
}, {
where: { id: userId },
});
await this.clearUserCache(userId);
}
/**
* 确保平台激活角色存在
* @param accountId
* @param accountStoreRoleId
* @param platformCode
* @private
*/
async ensurePlatformActiveRole(accountId, accountStoreRoleId, platformCode) {
const { ctx } = this;
try {
await ctx.model.AccountPlatformActive.upsert({
account_id: accountId,
employee_id: accountStoreRoleId,
platform_code: platformCode,
});
} catch (error) {
console.warn('设置平台激活角色失败:', error.message);
}
}
/**
* 用户注册(重构版)
* @param userInfo
*/
async register(userInfo) {
const { ctx, app } = this;
// 检查用户名是否已存在
const existingUser = await this.findUserByIdentifier(userInfo.username, 'username');
if (existingUser) {
throw new Error('用户名已存在');
}
// 生成密码盐
const salt = this.generateSalt();
// 加密密码
const passwordHash = await this.encryptPassword(userInfo.password, salt);
// 创建用户
const user = await ctx.model.Account.create({
username: userInfo.username,
email: userInfo.email || '',
password_hash: passwordHash,
real_name: userInfo.real_name || '',
status: 1,
salt,
});
return {
userId: user.id,
username: user.username,
code: 200,
message: '注册成功',
};
}
}
module.exports = UserService;