oms/backend/app/service/access.js
liufumingren b4b7c56729 feat: 权限范围收束与员工档案规则
- 新增 access 服务与 /api/access/context:按角色组权限判定集团 / 所在公司范围
- 菜单树按范围裁剪:所在公司范围仅保留「员工档案」,其余系统管理菜单隐藏
- 员工档案:角色组与所属公司必填;所在公司范围仅可见、仅可关联自己所属公司
- 创建者(所有者)行禁止编辑与解绑,且不可被移出主体;禁止新建所有者
- 所在公司范围禁止修改自己或他人的角色组、所属公司
- 新增员工时邮箱已注册则复用既有账号(reused),不再报「该邮箱已注册」
- 迁移:将所有者 role_id 统一指向系统管理员角色组

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-05 00:50:42 +08:00

77 lines
2.5 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');
/** 菜单权限范围:1集团全部 2所在公司 */
const SCOPE_GROUP = 1;
/**
* 权限范围判定服务
*
* 依据当前账号在指定主体下的角色组(roles → permissions.scope)判断权限范围:
* - 所有者(principal_users.role = owner)视为集团权限
* - 角色组内含任一「集团全部」权限 → group(可操作该主体全部公司)
* - 其余(仅「所在公司」权限或未分配角色组)→ company(只能操作自己关联的公司)
*/
class AccessService extends Service {
/**
* 解析账号在主体下的权限范围
* @param {number} userId 用户ID
* @param {number|string} principalId 主体ID
* @return {Promise<{isGroup: boolean, scope: string, relationId: number|null, role: string|null, roleId: number|null, ownCompanyIds: Array<number>}>} 权限上下文
*/
async resolve(userId, principalId) {
const empty = {
isGroup: false,
scope: 'company',
relationId: null,
role: null,
roleId: null,
ownCompanyIds: [],
};
if (!userId || principalId == null || principalId === '') return empty;
const relation = await this.ctx.model.PrincipalUser.findOne({
where: { user_id: userId, principal_id: Number(principalId) },
attributes: [ 'id', 'role', 'role_id' ],
});
if (!relation) return empty;
const companyRows = await this.ctx.model.PrincipalUserCompany.findAll({
where: { principal_user_id: relation.id },
attributes: [ 'subsidiary_id' ],
raw: true,
});
const ownCompanyIds = companyRows.map(row => Number(row.subsidiary_id));
let isGroup = relation.role === 'owner';
if (!isGroup && relation.role_id) {
const groupPermission = await this.ctx.model.Permission.findOne({
where: { scope: SCOPE_GROUP, status: 1 },
attributes: [ 'id' ],
include: [{
model: this.ctx.model.Role,
as: 'roles',
attributes: [ 'id' ],
where: { id: Number(relation.role_id) },
required: true,
through: { attributes: [] },
}],
});
isGroup = !!groupPermission;
}
return {
isGroup,
scope: isGroup ? 'group' : 'company',
relationId: Number(relation.id),
role: relation.role,
roleId: relation.role_id == null ? null : Number(relation.role_id),
ownCompanyIds,
};
}
}
module.exports = AccessService;
module.exports.SCOPE_GROUP = SCOPE_GROUP;