Merge branch 'ming' of ssh://192.168.9.101:22/liufumingren/WMS_MAIN into ming

This commit is contained in:
liufumingren 2026-04-05 09:08:09 +08:00
commit de9c5c0ab6
11 changed files with 4888 additions and 5003 deletions

View File

@ -434,109 +434,7 @@ class MainService extends Service {
}
/**
* debug 模式下确保 API 权限存在,并绑定到 role_id=2
* @param {string} apiPath - API路径
* @param {Object} user - 当前用户
* @return {Promise<{ensured:boolean, permissionId:number|null}>} 同步结果
*/
async ensureApiPermissionInDebugMode(apiPath, user = null) {
const { ctx, app } = this;
if (app.config.debug !== true) {
return {
ensured: false,
permissionId: null,
};
}
const normalizedPath = String(apiPath || '').trim();
if (!normalizedPath) {
return {
ensured: false,
permissionId: null,
};
}
const template = await ctx.model.Permission.findOne({
where: {
type: 'api',
},
attributes: [
'component',
'name',
'redirect',
'meta_title',
'meta_icon',
'hidden',
'always_show',
'parent_id',
'sort',
'status',
],
order: [[ 'id', 'ASC' ]],
raw: true,
});
const [ permission, created ] = await ctx.model.Permission.findOrCreate({
where: {
path: normalizedPath,
type: 'api',
},
defaults: {
path: normalizedPath,
type: 'api',
component: template ? template.component : null,
name: template && template.name ? template.name : normalizedPath,
redirect: template ? template.redirect : null,
meta_title: template && template.meta_title ? template.meta_title : `API:${normalizedPath}`,
meta_icon: template ? template.meta_icon : null,
hidden: template ? template.hidden : 0,
always_show: template ? template.always_show : 0,
parent_id: template ? template.parent_id : null,
sort: template ? template.sort : 0,
status: 1,
},
});
if (!permission || !permission.id) {
return {
ensured: false,
permissionId: null,
};
}
await ctx.service.systems.auth.rolePermission.bulkAssign(2, [ Number(permission.id) ]);
// 仅在新建权限时清理当前用户缓存,避免继续使用旧权限快照。
if (created && user && user.id) {
await ctx.service.systems.auth.user.clearUserCache(user.id);
}
return {
ensured: true,
permissionId: permission.id,
};
}
async hasRole2(employeeId) {
const { ctx } = this;
if (!employeeId) {
return false;
}
const link = await ctx.model.EmployeeRole.findOne({
where: {
employee_id: employeeId,
role_id: 2,
},
attributes: [ 'id' ],
raw: true,
});
return !!link;
}
/**
* 检查用户是否有 API 访问权限(只检查 type=api)
* 检查用户是否有API访问权限(只检查类型为api的权限)
* @param {Object} user - 用户信息
* @param {string} apiPath - API路径
* @return {Promise<boolean>} 是否有权限
@ -548,16 +446,7 @@ class MainService extends Service {
if (user.permissions && Array.isArray(user.permissions)) {
// 用户权限列表中可能包含所有权限,需要过滤出api权限
console.log('user.permissions', user.permissions);
if (user.permissions.includes('*') || user.permissions.includes(apiPath)) {
return true;
}
const ensureResult = await this.ensureApiPermissionInDebugMode(apiPath, user);
if (!ensureResult.ensured) {
return false;
}
return await this.hasRole2(user.employees_id);
return user.permissions.includes(apiPath);
}
return false;
} catch (error) {

View File

@ -6,9 +6,15 @@ class permissionService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
<<<<<<< HEAD
const _noNeedRight = 'list,add,delete,update';
const _noNeedLog = '*';
const _noNeedAuth = 'list,add,delete,update';
=======
const _noNeedRight = 'list';
const _noNeedLog = '*';
const _noNeedAuth = 'list';
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}

View File

@ -6,9 +6,15 @@ class roleService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
<<<<<<< HEAD
const _noNeedRight = 'list,add,delete,update,permission';
const _noNeedLog = '*';
const _noNeedAuth = 'list,add,delete,update,permission';
=======
const _noNeedRight = 'list,add,delete,update';
const _noNeedLog = '*';
const _noNeedAuth = 'list,add,delete,update';
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -33,6 +39,7 @@ class roleService extends MainService {
}
/**
<<<<<<< HEAD
* 角色权限列表(兼容旧入口)。
* @param {*} data
*/
@ -41,6 +48,8 @@ class roleService extends MainService {
}
/**
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
* 新增角色。
* @param {*} data
*/

View File

@ -6,8 +6,10 @@ class userService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode';
const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode';
const _noNeedRight = '*';
const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode';
const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode';
const _noNeedAuth = '*';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -56,6 +58,14 @@ class userService extends MainService {
}
return this.fail('获取微信登录码失败:' + result.message, result);
}
async getLoginWechatCode(data) {
const { service } = this;
const result = await service.systems.auth.user.getLoginWechatCode(data);
if (result.code) {
return this.success('获取微信登录码成功', result);
}
return this.fail('获取微信登录码失败:' + result.message, result);
}
async unbindWechat(data) {
const { service } = this;
const result = await service.systems.auth.user.unbindWechat(data);

View File

@ -493,6 +493,7 @@ class UserService extends Service {
}
/**
<<<<<<< HEAD
* 登录码登录:使用Ye4s登录码进行登录
* @param {string} code 登录码(WECHAT_LOGIN_CODE)
* @return {Object} 登录结果
@ -503,6 +504,18 @@ class UserService extends Service {
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,
@ -511,6 +524,7 @@ class UserService extends Service {
};
}
<<<<<<< HEAD
const candidateSet = new Set([ rawCode ]);
try {
const decoded = Buffer.from(rawCode, 'base64').toString('utf8').trim();
@ -551,6 +565,17 @@ class UserService extends Service {
});
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,
@ -559,6 +584,7 @@ class UserService extends Service {
};
}
<<<<<<< HEAD
const ye4sUserId = Number(rows[0].id);
if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) {
return {
@ -570,6 +596,44 @@ class UserService extends Service {
}
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 {
@ -1047,7 +1111,11 @@ class UserService extends Service {
};
}
<<<<<<< HEAD
const cacheKey = this.getWechatBindCacheKey(normalizedAccountId);
=======
const cacheKey = this.getWechatBindCacheKey(accountId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const useLongPoll = this.shouldUseWechatBindLongPoll(data);
const waitTimeoutMs = this.getWechatLongPollTimeoutMs();
@ -1058,7 +1126,11 @@ class UserService extends Service {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
<<<<<<< HEAD
const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, {
=======
const refreshed = await this.refreshWechatBindState(accountId, cachedState, {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
forceNewCode: false,
});
@ -1071,14 +1143,22 @@ class UserService extends Service {
};
}
<<<<<<< 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,
});
@ -1392,7 +1472,11 @@ class UserService extends Service {
}
}
<<<<<<< HEAD
const cacheKey = this.getWechatBindCacheKey(normalizedAccountId);
=======
const cacheKey = this.getWechatBindCacheKey(accountId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await this.setWechatBindCache(cacheKey, null, 1);
await this.publishWechatBindEvent(normalizedAccountId, {
status: 'unbound',

View File

@ -360,6 +360,7 @@ class SettingAccountService extends Service {
return employeeRoleMap;
}
<<<<<<< HEAD
async buildWechatBindingMap(accountIds) {
if (!Array.isArray(accountIds) || accountIds.length === 0) {
return new Map();
@ -450,6 +451,8 @@ class SettingAccountService extends Service {
throw this.createError('目标账号超出当前操作范围', 403);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
async formatEmployeeRow(employee, options = {}) {
let account = options.account || null;
if (!account) {
@ -562,10 +565,13 @@ class SettingAccountService extends Service {
.map(employee => Number(employee.id))
.filter(employeeId => Number.isFinite(employeeId) && employeeId > 0);
const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds);
<<<<<<< HEAD
const accountIds = employees
.map(employee => Number(employee.account_id))
.filter(accountId => Number.isFinite(accountId) && accountId > 0);
const wechatBindingMap = await this.buildWechatBindingMap(accountIds);
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const list = [];
for (const employee of employees) {
@ -586,17 +592,23 @@ class SettingAccountService extends Service {
continue;
}
<<<<<<< HEAD
const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || {
is_wechat_bound: false,
ye4s_user_id: null,
};
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
list.push({
...await this.formatEmployeeRow(employee, {
account: employee.account,
}),
<<<<<<< HEAD
is_wechat_bound: wechatBinding.is_wechat_bound,
ye4s_user_id: wechatBinding.ye4s_user_id,
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
role_ids: roleGroup.role_ids,
roles: roleGroup.roles,
});

View File

@ -151,22 +151,49 @@ class SettingPermissionService extends Service {
return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0));
}
<<<<<<< HEAD
async ensureParentPermissionExists(parentId) {
=======
async ensureParentPermissionInScope(parentId) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
if (!parentId) {
return;
}
await this.getPermission(parentId, false);
<<<<<<< HEAD
}
async ensurePermissionsExist(permissionIds) {
const { ctx } = this;
=======
const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled: false });
if (!availableSet.has(Number(parentId))) {
throw this.createError(`parent_id 超出当前登录工号可用权限集:${parentId}`, 400);
}
}
async ensurePermissionsInAvailableScope(permissionIds, options = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const includeDisabled = options.includeDisabled === true;
const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled });
if (availableSet.size === 0) {
throw this.createError('当前登录工号可用权限集为空,无法操作权限', 400);
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const targetRows = await ctx.model.Permission.findAll({
where: {
id: permissionIds,
},
<<<<<<< HEAD
attributes: [ 'id' ],
=======
attributes: [ 'id', 'parent_id' ],
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
raw: true,
});
if (targetRows.length !== permissionIds.length) {
@ -175,7 +202,68 @@ class SettingPermissionService extends Service {
throw this.createError(`权限不存在:${missing.join(',')}`, 404);
}
<<<<<<< HEAD
return targetRows;
=======
const parentMap = new Map(targetRows.map(item => [ Number(item.id), item.parent_id === null ? null : Number(item.parent_id) ]));
let pendingParentIds = Array.from(new Set(targetRows
.map(item => item.parent_id === null ? null : Number(item.parent_id))
.filter(parentId => Number.isFinite(parentId) && parentId > 0)));
while (pendingParentIds.length > 0) {
const fetchIds = pendingParentIds.filter(parentId => !parentMap.has(parentId));
if (fetchIds.length === 0) {
break;
}
const parentRows = await ctx.model.Permission.findAll({
where: {
id: {
[Op.in]: fetchIds,
},
},
attributes: [ 'id', 'parent_id' ],
raw: true,
});
for (const row of parentRows) {
parentMap.set(Number(row.id), row.parent_id === null ? null : Number(row.parent_id));
}
pendingParentIds = Array.from(new Set(parentRows
.map(row => row.parent_id === null ? null : Number(row.parent_id))
.filter(parentId => Number.isFinite(parentId) && parentId > 0 && !parentMap.has(parentId))));
}
const outOfScopeIds = [];
for (const permissionId of permissionIds) {
let currentId = Number(permissionId);
let inScope = false;
const visited = new Set();
while (Number.isFinite(currentId) && currentId > 0 && !visited.has(currentId)) {
visited.add(currentId);
if (availableSet.has(currentId)) {
inScope = true;
break;
}
const parentId = parentMap.has(currentId) ? parentMap.get(currentId) : null;
if (!Number.isFinite(parentId) || parentId <= 0) {
break;
}
currentId = Number(parentId);
}
if (!inScope) {
outOfScopeIds.push(Number(permissionId));
}
}
if (outOfScopeIds.length > 0) {
throw this.createError(`包含超出当前登录工号可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400);
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
normalizePermissionIds(inputPermissionIds) {
@ -271,7 +359,12 @@ class SettingPermissionService extends Service {
}
async getCurrentEmployeePermissionIds() {
<<<<<<< HEAD
const { ctx } = this;
=======
const { ctx, app } = this;
const { Op } = app.Sequelize;
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const currentEmployeeId = this.getCurrentEmployeeId();
if (!currentEmployeeId) {
return [];
@ -303,9 +396,25 @@ class SettingPermissionService extends Service {
return [];
}
<<<<<<< HEAD
return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
includeDisabled: false,
});
=======
const rolePermissions = await ctx.model.RolePermission.findAll({
where: {
role_id: {
[Op.in]: roleIds,
},
},
attributes: [ 'permission_id' ],
raw: true,
});
return Array.from(new Set(rolePermissions
.map(item => Number(item.permission_id))
.filter(id => Number.isFinite(id) && id > 0)));
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
async getCurrentRoleId() {
@ -342,6 +451,7 @@ class SettingPermissionService extends Service {
return roleId;
}
<<<<<<< HEAD
async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
@ -359,6 +469,26 @@ class SettingPermissionService extends Service {
[Op.in]: currentPermissionIds,
};
}
=======
async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '' } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentPermissionIds = await this.getCurrentEmployeePermissionIds();
if (currentPermissionIds.length === 0) {
return [];
}
const where = {
id: {
[Op.in]: currentPermissionIds,
},
status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1,
type: {
[Op.notLike]: '%_pages',
},
};
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
if (type) {
where.type = type;
}
@ -380,12 +510,16 @@ class SettingPermissionService extends Service {
'status',
'parent_id',
'sort',
<<<<<<< HEAD
'component',
'redirect',
'meta_title',
'meta_icon',
'hidden',
'always_show',
=======
'meta_title',
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
],
order: [
[ 'sort', 'ASC' ],
@ -414,11 +548,15 @@ class SettingPermissionService extends Service {
role = await this.getRole(roleId);
}
<<<<<<< HEAD
// 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permissionRows = await this.resolveVisiblePermissionRows({
includeDisabled,
type,
keyword,
<<<<<<< HEAD
scopeMode: 'all',
});
@ -431,6 +569,20 @@ class SettingPermissionService extends Service {
} else if (directPermissionIds.length > 0) {
selectedPermissionSet = new Set(directPermissionIds.map(item => Number(item)));
}
=======
});
let selectedPermissionSet = new Set();
if (role) {
const rolePermissions = await ctx.model.RolePermission.findAll({
where: {
role_id: role.id,
},
attributes: [ 'permission_id' ],
});
selectedPermissionSet = new Set(rolePermissions.map(item => Number(item.permission_id)));
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
const permissions = permissionRows.map(item => ({
@ -441,6 +593,7 @@ class SettingPermissionService extends Service {
status: Number(item.status),
parent_id: item.parent_id === null ? null : Number(item.parent_id),
sort: Number(item.sort || 0),
<<<<<<< HEAD
component: item.component || '',
redirect: item.redirect || '',
meta_title: item.meta_title || '',
@ -448,6 +601,10 @@ class SettingPermissionService extends Service {
hidden: Number(item.hidden || 0),
always_show: Number(item.always_show || 0),
selected: role ? (selectAllPermissions || selectedPermissionSet.has(Number(item.id))) : false,
=======
meta_title: item.meta_title || '',
selected: role ? selectedPermissionSet.has(Number(item.id)) : false,
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}));
return {
@ -482,7 +639,11 @@ class SettingPermissionService extends Service {
status: this.normalizeStatus(data.status),
};
<<<<<<< HEAD
await this.ensureParentPermissionExists(permissionData.parent_id);
=======
await this.ensureParentPermissionInScope(permissionData.parent_id);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
let created = null;
try {
@ -507,7 +668,13 @@ class SettingPermissionService extends Service {
const { ctx } = this;
const permissionIds = this.normalizeIds(data.ids, 'ids');
<<<<<<< HEAD
await this.ensurePermissionsExist(permissionIds);
=======
await this.ensurePermissionsInAvailableScope(permissionIds, {
includeDisabled: true,
});
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permissions = await ctx.model.Permission.findAll({
where: {
@ -539,7 +706,14 @@ class SettingPermissionService extends Service {
transaction,
});
<<<<<<< HEAD
await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, {
=======
await ctx.model.RolePermission.destroy({
where: {
permission_id: deletedIds,
},
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
transaction,
});
}
@ -562,8 +736,17 @@ class SettingPermissionService extends Service {
}
async update(data = {}) {
<<<<<<< HEAD
const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id');
await this.ensurePermissionsExist([ permissionId ]);
=======
const { ctx } = this;
const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id');
await this.ensurePermissionsInAvailableScope([ permissionId ], {
includeDisabled: true,
});
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permission = await this.getPermission(permissionId, true);
@ -617,7 +800,11 @@ class SettingPermissionService extends Service {
if (parentId && parentId === permissionId) {
throw this.createError('parent_id 不能等于 permission_id', 400);
}
<<<<<<< HEAD
await this.ensureParentPermissionExists(parentId);
=======
await this.ensureParentPermissionInScope(parentId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
updates.parent_id = parentId;
}
if (hasSort) {

View File

@ -145,6 +145,7 @@ class SettingRoleService extends Service {
return visited;
}
<<<<<<< HEAD
async buildRolePermissionMap(roleRows) {
const { service } = this.ctx;
const rows = Array.isArray(roleRows) ? roleRows : [];
@ -164,6 +165,9 @@ class SettingRoleService extends Service {
}
buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap = new Map()) {
=======
buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const nodeMap = new Map();
for (const row of roleRows) {
const roleId = Number(row.id);
@ -179,7 +183,10 @@ class SettingRoleService extends Service {
store_id: row.store_id === null ? null : Number(row.store_id),
pid: Number(row.pid || 0),
selected: selectedRoleIdSet.has(roleId),
<<<<<<< HEAD
permission_ids: rolePermissionMap.get(roleId) || [],
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
children: [],
});
}
@ -242,6 +249,7 @@ class SettingRoleService extends Service {
}
normalizePermissionIds(inputPermissionIds) {
<<<<<<< HEAD
if (inputPermissionIds === '*') {
return [ '*' ];
}
@ -266,21 +274,32 @@ class SettingRoleService extends Service {
}
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
if (!Array.isArray(inputPermissionIds)) {
throw this.createError('permission_ids 参数不能为空', 400);
}
<<<<<<< HEAD
if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) {
return [ '*' ];
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permissionIds = [];
for (const permissionId of inputPermissionIds) {
const normalized = Number(permissionId);
if (!Number.isFinite(normalized) || normalized <= 0) {
<<<<<<< HEAD
throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400);
}
permissionIds.push(Math.floor(normalized));
=======
throw this.createError('permission_ids 必须是正整数数组', 400);
}
permissionIds.push(normalized);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
return Array.from(new Set(permissionIds));
@ -320,11 +339,15 @@ class SettingRoleService extends Service {
async validatePermissionSet(permissionIds) {
const { ctx } = this;
<<<<<<< HEAD
if (!Array.isArray(permissionIds) || permissionIds.length === 0) {
return;
}
if (permissionIds.includes('*')) {
=======
if (permissionIds.length === 0) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return;
}
@ -341,12 +364,46 @@ class SettingRoleService extends Service {
const missing = permissionIds.filter(id => !found.has(id));
throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400);
}
<<<<<<< HEAD
}
async replaceRolePermissions(roleId, permissionIds, transaction) {
return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, {
transaction,
});
=======
const visiblePermissions = await this.ctx.service.systems.setting.permission.resolveVisiblePermissionRows({
includeDisabled: false,
type: null,
keyword: '',
});
const availableSet = new Set(visiblePermissions.map(item => Number(item.id)));
const outOfScopeIds = permissionIds.filter(id => !availableSet.has(id));
if (outOfScopeIds.length > 0) {
throw this.createError(`包含超出可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400);
}
}
async replaceRolePermissions(roleId, permissionIds, transaction) {
const { ctx } = this;
await ctx.model.RolePermission.destroy({
where: {
role_id: roleId,
},
transaction,
});
if (permissionIds.length > 0) {
const rows = permissionIds.map(permissionId => ({
role_id: roleId,
permission_id: permissionId,
}));
await ctx.model.RolePermission.bulkCreate(rows, { transaction });
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
async clearRoleUsersCache(roleId) {
@ -398,7 +455,11 @@ class SettingRoleService extends Service {
// 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。
const roleWhere = {
<<<<<<< HEAD
status: includeDisabled ? { [Op.in]: [0, 1] } : 1,
=======
status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1,
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
[Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ],
};
@ -415,7 +476,10 @@ class SettingRoleService extends Service {
'status',
'store_id',
'pid',
<<<<<<< HEAD
'permissions',
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
],
order: [
[ 'is_system', 'DESC' ],
@ -449,6 +513,7 @@ class SettingRoleService extends Service {
};
}
<<<<<<< HEAD
const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id)));
// 仅返回当前角色的下级角色树,不返回自己及同级角色。
@ -468,12 +533,34 @@ class SettingRoleService extends Service {
}
const visibleRoleIds = this.collectDescendantRoleIds(roleRows, Array.from(subordinateRootRoleIds));
=======
const sameLevelParentIds = new Set(currentRoleRows.map(item => Number(item.pid || 0)));
const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id)));
const hasSystemCurrentRole = currentRoleRows
.some(item => this.normalizeStoreScope(item.store_id) === 0);
// 默认场景下,若当前角色在系统域(store_id=0/null),只保留当前角色本身作为根,
// 避免暴露其他系统同级角色。
const sameLevelRoleIds = hasSystemCurrentRole && !includeSystem
? new Set(currentRoleIdSet)
: new Set(roleRows
.filter(item => sameLevelParentIds.has(Number(item.pid || 0)))
.filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem))
.map(item => Number(item.id)));
const descendantRoleIds = this.collectDescendantRoleIds(roleRows, currentRoleRows.map(item => Number(item.id)));
const visibleRoleIds = new Set([ ...sameLevelRoleIds, ...descendantRoleIds ]);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const visibleRoleRows = roleRows
.filter(item => visibleRoleIds.has(Number(item.id)))
.filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem));
const rootRoleIds = new Set(visibleRoleRows
<<<<<<< HEAD
.filter(item => subordinateRootRoleIds.has(Number(item.id)))
=======
.filter(item => sameLevelRoleIds.has(Number(item.id)))
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
.map(item => Number(item.id)));
let selectedRoleIdSet = new Set();
@ -486,8 +573,12 @@ class SettingRoleService extends Service {
selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id)));
}
<<<<<<< HEAD
const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows);
const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap);
=======
const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return {
code: 200,
@ -498,10 +589,13 @@ class SettingRoleService extends Service {
};
}
<<<<<<< HEAD
async permission(data = {}) {
return this.ctx.service.systems.setting.permission.list(data);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
async add(data = {}) {
const { ctx } = this;
@ -597,6 +691,18 @@ class SettingRoleService extends Service {
deletedIds.push(roleId);
}
<<<<<<< HEAD
=======
if (deletedIds.length > 0) {
await ctx.model.RolePermission.destroy({
where: {
role_id: deletedIds,
},
transaction,
});
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await transaction.commit();
} catch (error) {
await transaction.rollback();

File diff suppressed because it is too large Load Diff

View File

@ -86,6 +86,7 @@ function loadAuthRequiredMethods(methodDocPath) {
return [ ...methodSet ].sort();
}
<<<<<<< HEAD
function normalizeRolePermissions(rawValue) {
if (rawValue === undefined || rawValue === null) {
return { allAccess: false, permissionIds: [] };
@ -145,6 +146,8 @@ function serializeRolePermissions(rawValue) {
return state.allAccess ? '*' : JSON.stringify(state.permissionIds);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
function buildPermissionDefaults(methodPath, templateRow) {
return {
path: methodPath,
@ -178,16 +181,24 @@ async function queryExistingPermissions(conn, methodPaths) {
const placeholders = methodPaths.map(() => '?').join(',');
const [ rows ] = await conn.query(
<<<<<<< HEAD
`SELECT id, path, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`,
=======
`SELECT id, path FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`,
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
methodPaths
);
const result = new Map();
for (const row of rows) {
<<<<<<< HEAD
result.set(row.path, {
id: Number(row.id),
status: Number(row.status),
});
=======
result.set(row.path, row.id);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
return result;
}
@ -216,6 +227,7 @@ async function insertPermission(conn, defaults) {
return result.insertId;
}
<<<<<<< HEAD
async function activatePermission(conn, permissionId) {
const [ result ] = await conn.query(
'UPDATE wms_permission SET status = 1, update_at = NOW() WHERE id = ? AND status <> 1',
@ -244,6 +256,12 @@ async function bindRolePermission(conn, roleId, permissionId) {
const [ result ] = await conn.query(
'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?',
[ serializeRolePermissions(nextPermissions), roleId ]
=======
async function bindRolePermission(conn, roleId, permissionId) {
const [ result ] = await conn.query(
'INSERT IGNORE INTO wms_role_permission (role_id, permission_id, created_at) VALUES (?, ?, NOW())',
[ roleId, permissionId ]
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
);
return result.affectedRows > 0;
}
@ -277,6 +295,7 @@ async function main() {
const existingMap = await queryExistingPermissions(conn, methodPaths);
const missingPaths = methodPaths.filter(item => !existingMap.has(item));
<<<<<<< HEAD
const disabledPaths = methodPaths.filter(item => {
const row = existingMap.get(item);
return row && Number(row.status) !== 1;
@ -286,6 +305,12 @@ async function main() {
const touchedPermissionIds = [];
if (!args.dryRun && (missingPaths.length > 0 || disabledPaths.length > 0)) {
=======
const created = [];
const touchedPermissionIds = [];
if (!args.dryRun && missingPaths.length > 0) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await conn.beginTransaction();
try {
for (const methodPath of missingPaths) {
@ -294,6 +319,7 @@ async function main() {
created.push({ methodPath, permissionId });
touchedPermissionIds.push(permissionId);
}
<<<<<<< HEAD
for (const methodPath of disabledPaths) {
const permissionRow = existingMap.get(methodPath);
@ -308,6 +334,8 @@ async function main() {
touchedPermissionIds.push(permissionRow.id);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await conn.commit();
} catch (error) {
await conn.rollback();
@ -320,8 +348,13 @@ async function main() {
: await queryExistingPermissions(conn, methodPaths);
for (const methodPath of methodPaths) {
<<<<<<< HEAD
const permissionRow = latestMap.get(methodPath);
if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id);
=======
const permissionId = latestMap.get(methodPath);
if (permissionId) touchedPermissionIds.push(permissionId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ];
@ -340,12 +373,18 @@ async function main() {
totalAuthMethods: methodPaths.length,
existingPermissionCount: existingMap.size,
missingPermissionCount: missingPaths.length,
<<<<<<< HEAD
disabledPermissionCount: disabledPaths.length,
createdPermissionCount: created.length,
reactivatedPermissionCount: reactivated.length,
roleBindingCreated,
sampleMissing: missingPaths.slice(0, 20),
sampleDisabled: disabledPaths.slice(0, 20),
=======
createdPermissionCount: created.length,
roleBindingCreated,
sampleMissing: missingPaths.slice(0, 20),
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
};
console.log('[sync-system-api-permission] summary');

View File

@ -39,6 +39,7 @@ describe('test/app/controller/system.setting.permission.test.js', () => {
}
});
<<<<<<< HEAD
it('should expose setting.role.permission as alias of setting.permission.list', async () => {
const requestData = {
type: 'api',
@ -152,12 +153,23 @@ describe('test/app/controller/system.setting.permission.test.js', () => {
const updateRes = await invokeSystemMethod('setting.permission.update', {
permission_id: 999999999,
name: 'not_found_update',
=======
it('should reject out-of-scope permission update', async () => {
const updateRes = await invokeSystemMethod('setting.permission.update', {
permission_id: 999999999,
name: 'out_of_scope_update',
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}, token, EXTRA_HEADERS);
assert.equal(updateRes.status, 200);
assert.equal(updateRes.body.flag, 'failure');
<<<<<<< HEAD
assert.equal(Number(updateRes.body.code), 404);
assert.match(String(updateRes.body.message || ''), /权限不存在/);
=======
assert.ok([ 400, 404 ].includes(Number(updateRes.body.code)), `unexpected code: ${updateRes.body.code}`);
assert.match(String(updateRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
});
it('should create then update then delete permission successfully', async () => {
@ -289,7 +301,11 @@ describe('test/app/controller/system.setting.permission.test.js', () => {
}
});
<<<<<<< HEAD
it('should reject mixed delete when ids contain non-existent permission', async () => {
=======
it('should reject mixed delete when ids contain out-of-scope permission', async () => {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const suffix = Date.now();
const path = `autotest.permission.mixed.outscope.${suffix}`;
let permissionId = 0;
@ -315,8 +331,13 @@ describe('test/app/controller/system.setting.permission.test.js', () => {
assert.equal(mixedRes.status, 200);
assert.equal(mixedRes.body.flag, 'failure');
<<<<<<< HEAD
assert.equal(Number(mixedRes.body.code), 404);
assert.match(String(mixedRes.body.message || ''), /权限不存在/);
=======
assert.ok([ 400, 404 ].includes(Number(mixedRes.body.code)), `unexpected code: ${mixedRes.body.code}`);
assert.match(String(mixedRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
// 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删)
const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', {