Files
zyt/identity-admin/server/app/service/group/RoleAccessService.php
T
2026-11-11 13:53:14 +08:00

221 lines
12 KiB
PHP

<?php
declare(strict_types=1);
namespace app\service\group;
use app\exception\ApiError;
use app\service\Input;
/** 集团菜单权限只来自当前源角色的显式授权;公司与任职均不构成授权。 */
final class RoleAccessService
{
public const ID_OFFSET = 1000000000;
public const MENU_ID_BASE = self::ID_OFFSET;
private const MAX_PUBLIC_ID = 9007199254740991;
public function __construct(private readonly GroupStore $store) {}
public static function isNativeId(int $id): bool { return $id > self::ID_OFFSET; }
public static function isNativeMenuId(int $id): bool { return self::isNativeId($id); }
public function validateMenuIds(array $ids, array $retainedIds = []): array
{
$ids = Input::ids($ids, '集团菜单');
if (!$ids) { return []; }
$companies = []; $nodes = [];
foreach ($this->store->all('SELECT * FROM company') as $row) { $companies[(int) $row['id']] = $row; }
foreach ($this->store->all("SELECT * FROM company_structure_node WHERE kind='menu'") as $row) { $nodes[(int) $row['id']] = $row; }
foreach ($ids as $id) {
$node = $nodes[$id - self::ID_OFFSET] ?? null;
if ($id <= self::ID_OFFSET || $id > self::MAX_PUBLIC_ID || !$node) {
throw new ApiError(422, '集团菜单不存在或不可分配');
}
// 仅服务器从当前角色读取的既有授权可保留;停用资源始终不进入有效权限。
if (in_array($id, $retainedIds, true)) { continue; }
$companyId = (int) $node['company_id'];
if (!$this->companyActive($companyId, $companies) || $this->activeChain($id - self::ID_OFFSET, $nodes) === null
|| !$this->validPermission($node, $companies[$companyId])) {
throw new ApiError(422, '集团菜单或所属公司已停用,或菜单配置不可授权');
}
}
return $ids;
}
/** 一次查询完整页面的角色授权,避免角色列表逐行访问本地数据库。 */
public function menuIdsForRoles(array $roleIds): array
{
$roleIds = $this->roleIds($roleIds);
$result = array_fill_keys($roleIds, []);
if (!$roleIds) { return $result; }
$placeholders = implode(',', array_fill(0, count($roleIds), '?'));
foreach ($this->store->all("SELECT g.source_role_id,g.menu_id FROM role_native_menu g JOIN company_structure_node n ON n.id=g.menu_id AND n.kind='menu' WHERE g.source_role_id IN ($placeholders) ORDER BY g.menu_id", $roleIds) as $row) {
$result[(int) $row['source_role_id']][] = (int) $row['menu_id'] + self::ID_OFFSET;
}
return $result;
}
public function replace(int $roleId, array $ids, int $actorId, array $retainedIds = []): void
{
Input::integer($roleId, '角色');
$this->store->write(function () use ($roleId, $ids, $actorId, $retainedIds): void {
$existing = $this->menuIdsForRoles([$roleId])[$roleId];
$ids = $this->validateMenuIds($ids, array_values(array_unique([...$existing, ...$retainedIds])));
$this->store->execute('DELETE FROM role_native_menu WHERE source_role_id=?', [$roleId]);
foreach ($ids as $id) {
$this->store->execute('INSERT INTO role_native_menu(source_role_id,menu_id,update_time) VALUES(?,?,?)', [$roleId, $id - self::ID_OFFSET, time()]);
}
$this->store->audit($actorId, 'role.native-menu.replace', 0, $roleId);
});
}
public function grantTree(): array
{
$rows = $this->store->all("SELECT n.*,c.name AS company_name,c.code AS company_code FROM company_structure_node n JOIN company c ON c.id=n.company_id WHERE n.kind='menu' ORDER BY c.id,n.sort DESC,n.id");
return $this->tree($rows);
}
/** 调用时重新读取授权和资源状态,不信任曾经下发给浏览器的权限快照。 */
public function effective(array $profile): array
{
$roles = $this->roleIds($profile['role_id'] ?? []);
$grants = $this->menuIdsForRoles($roles);
$wanted = [];
foreach ($grants as $ids) { foreach ($ids as $id) { $wanted[$id - self::ID_OFFSET] = true; } }
if (!$wanted) { return ['permissions' => [], 'menus' => [], 'company_ids' => [], 'menu_ids' => []]; }
$companies = [];
foreach ($this->store->all('SELECT * FROM company') as $company) { $companies[(int) $company['id']] = $company; }
$rows = $this->store->all("SELECT * FROM company_structure_node WHERE kind='menu' ORDER BY company_id,sort DESC,id");
$byId = [];
foreach ($rows as $row) { $byId[(int) $row['id']] = $row; }
$effective = []; $include = []; $permissions = []; $companyIds = [];
foreach ($wanted as $id => $_) {
$node = $byId[$id] ?? null;
if (!$node || !$this->companyActive((int) $node['company_id'], $companies)) { continue; }
$chain = $this->activeChain($id, $byId);
if ($chain === null) { continue; }
$company = $companies[(int) $node['company_id']];
$permission = (string) $node['perms'];
// 旧数据或直接库写入的错误命名空间也不能形成有效授权。
if (!$this->validPermission($node, $company)) { continue; }
$effective[$id] = true;
$companyIds[(int) $node['company_id']] = true;
if ($permission !== '') { $permissions[$permission] = true; }
foreach ($chain as $ancestor) { $include[$ancestor] = true; }
}
$navigation = [];
foreach ($rows as $row) {
$id = (int) $row['id'];
// 下发完整有效树:按钮用于操作鉴权,隐藏页用于直达;仅前端导航过滤显示状态。
if (!isset($include[$id])) { continue; }
$company = $companies[(int) $row['company_id']];
$row['company_name'] = $company['name']; $row['company_code'] = $company['code'];
$row['explicit_grant'] = isset($effective[$id]);
$navigation[] = $row;
}
return ['permissions' => array_keys($permissions), 'menus' => $this->tree($navigation, true),
'company_ids' => array_map('intval', array_keys($companyIds)),
'menu_ids' => array_map(static fn (int $id): int => $id + self::ID_OFFSET, array_keys($effective))];
}
public function canStructure(array $profile, array $company, string $operation, ?array $access = null): bool
{
if (!preg_match('/^(dept|menu)\.(lists|add|edit|delete)$/D', $operation, $match)) { return false; }
$access ??= $this->effective($profile);
if (!in_array((int) $company['id'], $access['company_ids'], true)) { return false; }
$prefix = 'company.' . $company['code'] . '.';
$kind = $match[1] === 'dept' ? 'dept.dept' : 'auth.menu';
$permission = $prefix . $kind . '/' . $match[2];
return in_array($permission, $access['permissions'], true);
}
private function roleIds(array $ids): array
{
// profile 已经由源映射器验证;低层帮助器仍拒绝越界角色和非列表。
if (!array_is_list($ids) || count($ids) > 10000) { throw new ApiError(502, '共享角色响应异常'); }
return array_values(array_unique(array_map(static fn ($id): int => Input::integer($id, '角色'), $ids)));
}
private function companyActive(int $id, array $companies): bool
{
$seen = [];
while ($id !== 0) {
if (isset($seen[$id]) || !isset($companies[$id]) || (int) $companies[$id]['disable'] !== 0) { return false; }
$seen[$id] = true; $id = (int) $companies[$id]['parent_id'];
}
return true;
}
private function validPermission(array $node, array $company): bool
{
$permission = (string) $node['perms']; $prefix = 'company.' . $company['code'] . '.';
if (!in_array($node['type'], ['M', 'C', 'A'], true) || ($permission === '' && $node['type'] !== 'M')) { return false; }
return $permission === '' || (str_starts_with($permission, $prefix) && strlen($permission) > strlen($prefix)
&& (bool) preg_match('~^[A-Za-z0-9._:/-]+$~D', $permission));
}
private function activeChain(int $id, array $nodes): ?array
{
$chain = []; $companyId = (int) $nodes[$id]['company_id'];
while ($id !== 0) {
if (isset($chain[$id]) || count($chain) >= 64 || !isset($nodes[$id])
|| (int) $nodes[$id]['company_id'] !== $companyId || (int) $nodes[$id]['disable'] !== 0
|| !in_array($nodes[$id]['type'], ['M', 'C', 'A'], true)
|| ($nodes[$id]['type'] === 'A' && (int) $nodes[$id]['pid'] === 0)
|| ($chain !== [] && $nodes[$id]['type'] === 'A')) { return null; }
$chain[$id] = $id; $id = (int) $nodes[$id]['pid'];
}
return array_values($chain);
}
private function tree(array $rows, bool $navigation = false): array
{
$byId = []; $children = [];
foreach ($rows as $row) { $byId[(int) $row['id']] = $row; }
foreach ($rows as $row) {
$pid = (int) $row['pid'];
// 仅拼接同公司的父子节点;展示用祖先不会因此取得业务权限。
$parent = isset($byId[$pid]) && (int) $byId[$pid]['company_id'] === (int) $row['company_id'] ? $pid : 0;
$children[$parent][] = $row;
}
$build = function (int $pid, array $seen = []) use (&$build, $children, $navigation): array {
if (count($seen) >= 64) { return []; }
$result = [];
foreach ($children[$pid] ?? [] as $row) {
$id = (int) $row['id'];
if (isset($seen[$id])) { continue; }
$node = $this->publicMenu($row, $navigation);
$node['children'] = $build($id, $seen + [$id => true]);
$result[] = $node;
}
return $result;
};
return $build(0);
}
private function publicMenu(array $row, bool $navigation): array
{
$id = (int) $row['id'] + self::ID_OFFSET;
$result = ['id' => $id, 'pid' => (int) $row['pid'] ? (int) $row['pid'] + self::ID_OFFSET : 0,
'name' => $row['name'], 'type' => $row['type'], 'sort' => (int) $row['sort'], 'disable' => (int) $row['disable'],
'is_show' => (int) $row['is_show'], 'is_cache' => (int) $row['is_cache'],
'company_id' => (int) $row['company_id'], 'company_name' => $row['company_name'], 'native' => true];
foreach (['paths', 'component', 'perms', 'icon', 'selected', 'params'] as $field) { $result[$field] = $row[$field]; }
if (!$navigation) { return $result; }
$result['paths'] = '/company/' . $row['company_id'] . '/menu/' . $id;
$result['params'] = ''; $result['selected'] = ''; $result['is_cache'] = 0;
if (empty($row['explicit_grant'])) {
$result['component'] = ''; $result['perms'] = ''; $result['type'] = 'M';
} elseif ($row['type'] === 'C') {
$component = preg_replace('~\.vue$~', '', trim((string) $row['component'], '/'));
$prefix = 'company.' . $row['company_code'] . '.';
$result['component'] = match (true) {
in_array($component, ['system/depts', 'organization/department/index'], true)
&& $row['perms'] === $prefix . 'dept.dept/lists' => 'system/depts',
in_array($component, ['system/menus', 'permission/menu/index'], true)
&& $row['perms'] === $prefix . 'auth.menu/lists' => 'system/menus',
default => 'common/custom',
};
} else { $result['component'] = ''; }
return $result;
}
}