Files
zyt/server/app/mcp/service/Identity.php
T
2026-09-24 09:45:44 +08:00

114 lines
3.6 KiB
PHP

<?php
declare(strict_types=1);
namespace app\mcp\service;
use app\common\enum\AdminTerminalEnum;
use app\common\model\auth\Admin;
use app\common\model\auth\SystemRole;
use app\common\service\DataScope\DataScopeService;
/**
* 一次 MCP 调用的调用人:授权记录 + 后台账号 + 与登录中间件同结构的 adminInfo。
* 权限每次实时计算,不随令牌冻结:调整角色立即生效。
*/
class Identity
{
public array $grant;
public array $admin;
public int $adminId;
public bool $root;
public array $adminInfo;
public function __construct(array $grant, Admin $admin)
{
$this->grant = $grant;
$this->admin = $admin->toArray();
unset($this->admin['password']);
$this->adminId = (int) $admin['id'];
$this->root = (int) $admin['root'] === 1;
$this->adminInfo = self::buildAdminInfo($admin, (int) ($grant['expire_time'] ?? 0));
}
/** 与 AdminTokenCache::setAdminInfo 相同的结构,列表类和数据范围服务按它识别当前账号 */
public static function buildAdminInfo(Admin $admin, int $expireTime): array
{
$roleIds = $admin->role_id;
$roleName = '';
if ((int) $admin['root'] === 1) {
$roleName = '系统管理员';
} else {
$roleLists = SystemRole::column('name', 'id');
foreach ($roleIds as $roleId) {
$roleName .= ($roleLists[$roleId] ?? '') . '/';
}
$roleName = trim($roleName, '/');
}
return [
'admin_id' => $admin->id,
'root' => $admin->root,
'name' => $admin->name,
'account' => $admin->account,
'role_name' => $roleName,
'role_id' => $roleIds,
'token' => '',
'terminal' => AdminTerminalEnum::PC,
'expire_time' => $expireTime,
'login_ip' => request()->ip(),
'work_wechat_userid' => $admin->work_wechat_userid ?? '',
];
}
/** 该账号是否拥有某个(已登记、未停用的)权限点 */
public function can(string $perm): bool
{
if (!PermissionService::isRegistered($perm)) {
return false;
}
return $this->root || isset(PermissionService::adminPerms($this->adminId)[PermissionService::normalize($perm)]);
}
/** 可见完整手机号:AI 敏感信息权限,或后台已有的「诊单明文手机号」按钮权限 */
public function seesPhone(): bool
{
return $this->root || $this->can('ai.mcp/sensitive') || $this->can('tcm.diagnosis/phonePlain');
}
/** 可见完整身份证号、住址、附件地址 */
public function seesSensitive(): bool
{
return $this->root || $this->can('ai.mcp/sensitive');
}
public function roleNames(): array
{
return array_values(array_filter(explode('/', (string) $this->adminInfo['role_name'])));
}
public function dataScopeText(): string
{
$scope = DataScopeService::getEffectiveScope($this->adminInfo);
return [
DataScopeService::SCOPE_ALL => '全部数据',
DataScopeService::SCOPE_DEPT_AND_CHILD => '本部门及下级部门',
DataScopeService::SCOPE_DEPT => '本部门',
DataScopeService::SCOPE_SELF => '仅本人',
][$scope] ?? '仅本人';
}
public function publicProfile(): array
{
return [
'id' => $this->adminId,
'name' => (string) $this->admin['name'],
'account' => (string) $this->admin['account'],
'roles' => $this->roleNames(),
'root' => $this->root,
];
}
}