1471 lines
41 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_CACHE_TTL_SECONDS = 600;
const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000;
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}`;
}
createWechatBindCode() {
const payload = {
uuid: `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`,
};
return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
}
parseWechatBindCode(code) {
if (!code) {
return null;
}
try {
const decodedStr = Buffer.from(code, 'base64').toString('utf8');
const parsed = JSON.parse(decodedStr);
if (!parsed || typeof parsed !== 'object' || !parsed.uuid) {
return null;
}
return parsed;
} catch (error) {
return null;
}
}
formatBindWechatData(state, source = 'db') {
const nextCheckAt = Number(state.next_db_check_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(),
next_db_check_at: nextCheckAt,
next_poll_after_ms: Math.max(0, nextCheckAt - Date.now()),
source,
ye4s_user_id: state.ye4s_user_id || null,
};
}
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 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];
}
/**
* 用户登录(重构版)
* @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: '用户名或密码错误或账号状态异常',
};
}
}
/**
* 登录码登录:使用 ye4s_user.tmp_code 绑定的 wms_account_id 登录
* @param {string} code 登录码(ye4s_user.tmp_code)
* @return {Object} 登录结果
*/
async loginByCode(code) {
const { ctx, app } = this;
try {
const normalizedCode = typeof code === 'string' ? code.trim() : '';
if (!normalizedCode) {
return {
success: false,
data: null,
code: 0,
message: '缺少登录码 code',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const ye4sUser = await ye4sClient.get('ye4s_user', {
tmp_code: normalizedCode,
});
if (!ye4sUser) {
return {
success: false,
data: null,
code: 0,
message: '登录码不存在',
};
}
const wmsAccountId = Number(ye4sUser.wms_account_id);
if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) {
return {
success: false,
data: null,
code: 0,
message: '该登录码未绑定WMS账号',
};
}
const user = await ctx.model.Account.findOne({
where: { id: wmsAccountId },
});
if (!user) {
return {
success: false,
data: null,
code: 0,
message: '绑定的WMS账号不存在',
};
}
try {
this.checkUserStatus(user);
} catch (statusError) {
app.coreLogger.warn(`登录码登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`);
return {
success: false,
data: null,
code: 0,
message: '绑定账号状态异常',
};
}
await this.updateLastLoginTime(user.id);
return this.buildLoginResult(user);
} catch (error) {
app.coreLogger.error(`登录码登录异常: ${error.message}`);
return {
success: false,
data: null,
code: 0,
message: '登录失败,请稍后重试',
};
}
}
/**
* 获取微信绑定码(缓存优先,低频复查DB,适配轮询)
* @param {Object} data
* @return {Object}
*/
async getBindWechatCode(data = {}) {
const { app } = this;
try {
const accountId = this.getCurrentAccountId();
if (!accountId) {
return {
success: false,
code: 0,
data: null,
message: '未识别到登录账号,无法生成绑定码',
};
}
const cacheKey = this.getWechatBindCacheKey(accountId);
const forceRefresh = !!data.forceRefresh;
const now = Date.now();
let cachedState = null;
try {
cachedState = await this.app.getCacheAsync(cacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
if (cachedState && !forceRefresh) {
const nextCheckAt = Number(cachedState.next_db_check_at || 0);
if (nextCheckAt > now) {
return {
success: true,
code: 200,
data: this.formatBindWechatData(cachedState, 'cache'),
message: '获取绑定码成功(缓存)',
};
}
}
const ye4sBinding = await this.findYe4sBindingByAccountId(accountId);
if (ye4sBinding) {
const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : '';
const bindState = {
account_id: accountId,
status: 'bound',
code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(),
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sBinding.id || null,
};
await this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS);
return {
success: true,
code: 200,
data: this.formatBindWechatData(bindState, 'db'),
message: '账号已绑定微信',
};
}
const code = (cachedState && cachedState.code) || this.createWechatBindCode();
const pendingState = {
account_id: accountId,
status: 'pending',
code,
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: null,
};
await this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS);
return {
success: true,
code: 200,
data: this.formatBindWechatData(pendingState, code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated'),
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 code = typeof data.code === 'string' ? data.code.trim() : '';
if (!code) {
return {
success: false,
code: 0,
data: null,
message: '缺少绑定码 code',
};
}
if (!this.parseWechatBindCode(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: true,
code: 200,
data: {
account_id: cachedAccountId,
code,
status: codeState.status || 'pending',
source: 'cache',
updated_at: codeState.updated_at || new Date().toISOString(),
},
message: '获取账号成功',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const ye4sUser = await ye4sClient.get('ye4s_user', {
tmp_code: code,
});
const wmsAccountId = Number(ye4sUser && ye4sUser.wms_account_id);
if (Number.isFinite(wmsAccountId) && wmsAccountId > 0) {
const boundState = {
account_id: wmsAccountId,
status: 'bound',
code,
updated_at: new Date().toISOString(),
next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sUser.id || null,
};
await this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS);
return {
success: true,
code: 200,
data: {
account_id: wmsAccountId,
code,
status: 'bound',
source: 'db',
updated_at: boundState.updated_at,
},
message: '获取账号成功',
};
}
return {
success: false,
code: 0,
data: null,
message: '绑定码不存在或已过期',
};
} catch (error) {
app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '获取账号失败,请稍后重试',
};
}
}
/**
* 解绑微信:清理 ye4s_user 中与当前账号关联的数据
* @return {Object}
*/
async unbindWechat() {
const { ctx, app } = this;
try {
const accountId = this.getCurrentAccountId();
if (!accountId) {
return {
success: false,
code: 0,
data: null,
message: '未识别到登录账号,无法解绑',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const bindRows = await ye4sClient.select('ye4s_user', {
where: {
wms_account_id: accountId,
},
columns: [ 'id', 'tmp_code', 'wms_account_id' ],
orders: [[ 'id', 'desc' ]],
limit: 500,
});
let affectedRows = 0;
for (const row of bindRows) {
const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : '';
if (rowCode) {
await this.setWechatBindCodeCache(rowCode, null, 1);
}
try {
const ret = await ye4sClient.update('ye4s_user', {
id: row.id,
wms_account_id: null,
tmp_code: null,
});
affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0);
} catch (err) {
// 兼容不允许 NULL 的旧表结构
const ret = await ye4sClient.update('ye4s_user', {
id: row.id,
wms_account_id: 0,
tmp_code: '',
});
affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0);
}
}
const cacheKey = this.getWechatBindCacheKey(accountId);
const cachedState = await this.app.getCacheAsync(cacheKey);
if (cachedState && cachedState.code) {
await this.setWechatBindCodeCache(cachedState.code, null, 1);
}
await this.setWechatBindCache(cacheKey, null, 1);
return {
success: true,
code: 200,
data: {
account_id: accountId,
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. 获取角色的权限
const rolePermissions = await ctx.model.RolePermission.findAll({
where: {
role_id: {
[Op.in]: roleIds,
},
},
raw: true,
});
if (!rolePermissions || rolePermissions.length === 0) {
return [];
}
const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ];
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. 获取角色的权限
const rolePermissions = await ctx.model.RolePermission.findAll({
where: {
role_id: {
[Op.in]: roleIds,
},
},
raw: true,
});
if (!rolePermissions || rolePermissions.length === 0) {
return [];
}
const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ];
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;