480 lines
28 KiB
PHP
480 lines
28 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace app\service\group;
|
|
|
|
use app\exception\ApiError;
|
|
use app\service\Input;
|
|
use app\service\Settings;
|
|
use app\service\shared\SessionStore;
|
|
use app\service\shared\SharedRecordsService;
|
|
use app\service\shared\SourceApiClient;
|
|
use app\service\shared\SourceMapper;
|
|
|
|
/** 集团范围只管理已登记的公司与应用;医院权限始终由原服务判断。 */
|
|
final class GroupService
|
|
{
|
|
private GroupStore $store;
|
|
private \Closure $clock;
|
|
/** 仅当前服务请求内的可信旧授权快照,不接受浏览器传入保留集合。 */
|
|
private array $nativeGrantPlans = [];
|
|
|
|
public function __construct(private readonly SourceApiClient $source, private readonly SessionStore $sessions,
|
|
?GroupStore $store = null, ?callable $clock = null, private readonly ?KefuMetadataClient $metadata = null,
|
|
private readonly ?KefuAuthorizationClient $authorization = null)
|
|
{
|
|
if (!self::enabled()) { throw new ApiError(503, '集团身份中心尚未启用'); }
|
|
$this->store = $store ?? new GroupStore($source->sourceKey());
|
|
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
|
|
}
|
|
|
|
public static function enabled(): bool
|
|
{
|
|
return in_array(strtolower(Settings::get('IAM_GROUP_ENABLED', '0')), ['1', 'true', 'yes'], true);
|
|
}
|
|
|
|
public static function hospitalEntry(): string
|
|
{
|
|
$base = rtrim(Settings::get('IAM_HOSPITAL_BASE_URL'), '/');
|
|
$parts = parse_url($base);
|
|
if (!$parts || !in_array($parts['scheme'] ?? '', ['http', 'https'], true) || empty($parts['host'])
|
|
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])
|
|
|| preg_match('/[\x00-\x20\x7f\\\\]/', $base)
|
|
|| !preg_match('~^/[A-Za-z0-9/_-]+$~D', $parts['path'] ?? '')) { return ''; }
|
|
if ($parts['scheme'] === 'http' && !in_array(strtolower($parts['host']), ['localhost', '127.0.0.1', '[::1]', '::1'], true)) { return ''; }
|
|
return $base . '/group-login';
|
|
}
|
|
|
|
public static function hospitalOrigin(): string
|
|
{
|
|
$entry = self::hospitalEntry();
|
|
if ($entry === '') { return ''; }
|
|
$p = parse_url($entry);
|
|
return $p['scheme'] . '://' . $p['host'] . (isset($p['port']) ? ':' . $p['port'] : '');
|
|
}
|
|
|
|
public function isOwner(array $profile): bool
|
|
{
|
|
$ids = array_filter(array_map('trim', explode(',', Settings::get('IAM_GROUP_OWNER_IDS', ''))),
|
|
static fn (string $id): bool => (bool) preg_match('/^[1-9][0-9]*$/D', $id));
|
|
return !empty($profile['is_root']) && in_array((string) $profile['id'], $ids, true);
|
|
}
|
|
|
|
public function enrich(array $profile): array
|
|
{
|
|
$identity = $this->store->identity((int) $profile['id']);
|
|
$sourcePermissions = $profile['source_permissions'] ?? $profile['permissions'];
|
|
$sourceMenus = $profile['source_menus'] ?? $profile['menus'];
|
|
$access = $this->roleAccess($profile)->effective($profile);
|
|
$hospitalPermissions = $this->companyActive(1)
|
|
? array_map(static fn (string $permission): string => 'company.zyt-hospital.application.internet-hospital.' . $permission, $sourcePermissions) : [];
|
|
return array_replace($profile, ['gid' => $identity['gid'], 'is_group_admin' => $this->isOwner($profile),
|
|
'source_permissions' => $sourcePermissions, 'source_menus' => $sourceMenus,
|
|
'permissions' => array_values(array_unique([...$sourcePermissions, ...$access['permissions']])),
|
|
'menus' => [...$sourceMenus, ...$access['menus']], 'native_permissions' => $access['permissions'],
|
|
'native_menus' => $access['menus'], 'native_company_ids' => $access['company_ids'],
|
|
'company_permissions' => [...$hospitalPermissions, ...$access['permissions']]]);
|
|
}
|
|
|
|
public function roleAccess(array $profile): RoleAccessService { return new RoleAccessService($this->store); }
|
|
|
|
private function requireRoleAccess(array $profile, bool $write = false): void
|
|
{
|
|
$permissions = $profile['source_permissions'] ?? $profile['permissions'];
|
|
$allowed = $write ? ['auth.role/add', 'auth.role/edit']
|
|
: ['auth.role/lists', 'auth.role/add', 'auth.role/edit', 'auth.admin/add', 'auth.admin/edit'];
|
|
foreach ($allowed as $permission) { if (SourceMapper::can($permissions, $permission)) { return; } }
|
|
throw new ApiError(403, '没有角色菜单授权权限');
|
|
}
|
|
|
|
public function roleMenuTree(array $profile): array
|
|
{
|
|
$permissions = $profile['source_permissions'] ?? $profile['permissions'];
|
|
if (!SourceMapper::can($permissions, 'auth.role/lists') && !SourceMapper::can($permissions, 'auth.role/add')
|
|
&& !SourceMapper::can($permissions, 'auth.role/edit')) { throw new ApiError(403, '没有角色菜单授权权限'); }
|
|
return $this->roleAccess($profile)->grantTree();
|
|
}
|
|
|
|
public function roleNativeMenuIds(array $profile, int $roleId): array
|
|
{
|
|
return $this->roleNativeMenuIdsForRoles($profile, [$roleId])[$roleId] ?? [];
|
|
}
|
|
|
|
public function roleNativeMenuIdsForRoles(array $profile, array $roleIds): array
|
|
{
|
|
$this->requireRoleAccess($profile);
|
|
return $this->roleAccess($profile)->menuIdsForRoles($roleIds);
|
|
}
|
|
|
|
public function validateRoleNativeMenuIds(array $profile, array $ids, ?int $roleId = null): void
|
|
{
|
|
$this->requireRoleAccess($profile, true);
|
|
$access = $this->roleAccess($profile);
|
|
$existing = $roleId === null ? [] : ($access->menuIdsForRoles([$roleId])[$roleId] ?? []);
|
|
$ids = $access->validateMenuIds($ids, $existing);
|
|
if ($roleId !== null) { $this->nativeGrantPlans[$roleId] = ['ids' => $ids, 'retained' => $existing]; }
|
|
}
|
|
|
|
public function replaceRoleNativeMenus(array $profile, int $roleId, array $ids): void
|
|
{
|
|
$this->requireRoleAccess($profile, true);
|
|
$ids = Input::ids($ids, '集团菜单');
|
|
$plan = $this->nativeGrantPlans[$roleId] ?? null;
|
|
unset($this->nativeGrantPlans[$roleId]);
|
|
$retained = $plan && $plan['ids'] === $ids ? $plan['retained'] : [];
|
|
$this->roleAccess($profile)->replace($roleId, $ids, (int) $profile['id'], $retained);
|
|
}
|
|
|
|
public function clearRoleNativeMenus(array $profile, int $roleId): void
|
|
{
|
|
$permissions = $profile['source_permissions'] ?? $profile['permissions'];
|
|
if (!SourceMapper::can($permissions, 'auth.role/delete')) { $this->requireRoleAccess($profile, true); }
|
|
$this->roleAccess($profile)->replace($roleId, [], (int) $profile['id']);
|
|
}
|
|
|
|
public function dispatch(string $operation, array $profile, array $session, string $bridgeToken, array $data, array $query): array
|
|
{
|
|
if (in_array($operation,['group.application.access','group.application.sync','group.application.access-options','group.application.access-update'],true)) {
|
|
$this->requireOwner($profile);
|
|
$service=new KefuApplicationService($this->store,$this->source,$this->metadata,$this->authorization);
|
|
if ($operation==='group.application.access') { Input::only($data,[]);return $service->access($query,$session['source_token']); }
|
|
if ($operation==='group.application.access-options') { Input::only($data,[]);return $service->accessOptions($query,$session['source_token']); }
|
|
if ($operation==='group.application.access-update') { Input::only($query,[]);return $service->accessUpdate($data,$session['source_token'],(int)$profile['id']); }
|
|
Input::only($query,[]);return $service->sync($data,(int)$profile['id']);
|
|
}
|
|
$this->store->identity((int) $profile['id']);
|
|
return match ($operation) {
|
|
'group.context' => $this->context($profile),
|
|
'group.company.save' => $this->saveCompany($profile, $data),
|
|
'group.members' => $this->members($profile, $session, $query),
|
|
'group.member.save' => $this->saveMember($profile, $session, $data),
|
|
'group.sso.authorize' => $this->authorize($profile, $bridgeToken, $data),
|
|
default => throw new ApiError(404, '接口不存在'),
|
|
};
|
|
}
|
|
|
|
public function context(array $profile): array
|
|
{
|
|
$id = (int) $profile['id'];
|
|
$identity = $this->store->identity($id);
|
|
$owner = $this->isOwner($profile);
|
|
$access = $this->roleAccess($profile)->effective($profile);
|
|
$kefu = $this->kefuCompany();
|
|
$rows = $this->store->all('SELECT c.*,m.member_status,m.can_login FROM company c LEFT JOIN membership m ON m.company_id=c.id AND m.source_id=? ORDER BY c.id', [$id]);
|
|
$companies = [];
|
|
foreach ($rows as $row) {
|
|
if (!$owner && !in_array((int) $row['id'], $access['company_ids'], true)
|
|
&& !((int) $row['id'] === 1 && $this->hasHospitalAccess($profile))
|
|
&& !($kefu && (int) $row['id'] === (int) $kefu['id'] && $this->accountReady($profile))) { continue; }
|
|
$companies[] = $this->publicCompany($row, $profile, $access) + ['member_status' => (int) ($row['member_status'] ?? 0),
|
|
'can_login' => (int) ($row['can_login'] ?? 0), 'effective_disable' => $this->companyActive((int) $row['id']) ? 0 : 1];
|
|
}
|
|
$hospital = array_values(array_filter($companies, static fn (array $company): bool => $company['id'] === 1))[0] ?? null;
|
|
$entry = self::hospitalEntry();
|
|
$permitted = $hospital && $hospital['effective_disable'] === 0 && $this->hasHospitalAccess($profile);
|
|
$applications = $hospital ? [['id' => 'internet-hospital', 'company_id' => 1, 'name' => '互联网医院',
|
|
'entry_url' => $entry, 'ready' => $entry !== '', 'can_login' => (bool) $permitted,
|
|
'status_message' => !$permitted ? '当前角色未获医院访问权限' : ($entry === '' ? '医院入口待配置' : '可进入')]] : [];
|
|
if ($kefu && $this->accountReady($profile)) {
|
|
$active = $this->companyActive((int) $kefu['id']);
|
|
$applications[] = ['id' => KefuClient::ID, 'company_id' => (int) $kefu['id'], 'name' => '企微客服',
|
|
'entry_url' => KefuClient::entry(), 'ready' => true, 'can_login' => $active,
|
|
'http_entry_allowed' => KefuClient::isExplicitHttpOriginAllowed(KefuClient::entry()),
|
|
'status_message' => $active ? '可进入,业务权限由客服或集团管理员分配' : '客服所属公司或上级公司已停用'];
|
|
}
|
|
return ['group' => ['name' => Settings::get('IAM_GROUP_NAME', '集团身份中心')],
|
|
'identity' => ['gid' => $identity['gid'], 'source_admin_id' => $id], 'is_group_admin' => $owner,
|
|
'default_company_id' => 1, 'companies' => $companies,
|
|
'applications' => $applications];
|
|
}
|
|
|
|
private function publicCompany(array $row, array $profile, ?array $access = null): array
|
|
{
|
|
$id = (int) $row['id'];
|
|
$structurePermissions = $this->structurePermissions($profile, $id, $access);
|
|
return ['id' => $id, 'code' => $row['code'], 'name' => $row['name'], 'parent_id' => (int) $row['parent_id'],
|
|
'disable' => (int) $row['disable'], 'is_directory_company' => $id === 1,
|
|
'structure_mode' => $id === 1 ? 'hospital' : 'group', 'can_manage_structure' => $structurePermissions !== [],
|
|
'structure_permissions' => $structurePermissions,
|
|
'permission_prefix' => 'company.' . $row['code'] . ($id === 1 ? '.application.internet-hospital' : '')];
|
|
}
|
|
|
|
private function structurePermissions(array $profile, int $companyId, ?array $access = null): array
|
|
{
|
|
if (!$this->companyActive($companyId)) { return []; }
|
|
$result = []; $company = $this->company($companyId);
|
|
if ($companyId !== 1 && !$this->isOwner($profile)) { $access ??= $this->roleAccess($profile)->effective($profile); }
|
|
foreach (['dept', 'menu'] as $kind) {
|
|
foreach (['lists', 'add', 'edit', 'delete'] as $action) {
|
|
$operation = $kind . '.' . $action;
|
|
if ($companyId === 1) {
|
|
$permission = ($kind === 'dept' ? 'dept.dept' : 'auth.menu') . '/' . $action;
|
|
$can = SourceMapper::can($profile['source_permissions'] ?? $profile['permissions'], $permission);
|
|
} else { $can = $this->isOwner($profile) || $this->roleAccess($profile)->canStructure($profile, $company, $operation, $access); }
|
|
if ($can) { $result[] = $operation; }
|
|
}
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
private function hasHospitalAccess(array $profile): bool
|
|
{
|
|
foreach ($profile['source_permissions'] ?? $profile['permissions'] as $permission) {
|
|
if (is_string($permission) && $permission !== '') { return true; }
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private function company(int $id): array
|
|
{
|
|
return $this->store->one('SELECT * FROM company WHERE id=?', [$id]) ?? throw new ApiError(404, '公司不存在');
|
|
}
|
|
|
|
private function companyActive(int $id): bool
|
|
{
|
|
$seen = [];
|
|
while ($id !== 0) {
|
|
if (isset($seen[$id])) { return false; }
|
|
$seen[$id] = true;
|
|
$row = $this->store->one('SELECT * FROM company WHERE id=?', [$id]);
|
|
if (!$row) { return false; }
|
|
if ((int) $row['disable'] === 1) { return false; }
|
|
$id = (int) $row['parent_id'];
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private function requireOwner(array $profile): void
|
|
{
|
|
if (!$this->isOwner($profile)) { throw new ApiError(403, '仅集团管理员可管理公司和成员资格'); }
|
|
}
|
|
|
|
private function requireLogin(array $profile, int $companyId): void
|
|
{
|
|
$this->company($companyId);
|
|
if ($companyId !== 1 || !$this->companyActive($companyId) || !$this->hasHospitalAccess($profile)) {
|
|
throw new ApiError(403, '当前角色没有该医院的访问权限');
|
|
}
|
|
}
|
|
|
|
private function accountReady(array $profile): bool
|
|
{
|
|
return (int) ($profile['id'] ?? 0) > 0 && ($profile['disable'] ?? null) === 0
|
|
&& empty($profile['requires_password_change']) && empty($profile['requires_wecom_binding']);
|
|
}
|
|
|
|
private function kefuCompany(): ?array
|
|
{
|
|
if (KefuClient::entry() === '' || KefuClient::companyCode() === '') { return null; }
|
|
return $this->store->one('SELECT * FROM company WHERE code=?', [KefuClient::companyCode()]);
|
|
}
|
|
|
|
private function requireClientLogin(array $profile, array $client, ?int $grantCompanyId = null): void
|
|
{
|
|
if ($client['id'] === 'internet-hospital') {
|
|
$this->requireLogin($profile, $grantCompanyId ?? $client['company_id']);
|
|
return;
|
|
}
|
|
if (!$this->accountReady($profile)) { throw new ApiError(403, '请先完成账号验证'); }
|
|
if (($grantCompanyId !== null && $grantCompanyId !== $client['company_id'])
|
|
|| !$this->companyActive($client['company_id'])) {
|
|
throw new ApiError(403, '客服所属公司或上级公司已停用,或应用登记已变化');
|
|
}
|
|
}
|
|
|
|
public function requireDirectory(array $profile, ?int $companyId): void
|
|
{
|
|
$companyId ??= 1;
|
|
$this->store->identity((int) $profile['id']);
|
|
if ($companyId !== 1) { throw new ApiError(409, '当前公司尚未接入子系统,不提供医院目录数据'); }
|
|
if (!$this->companyActive($companyId)) { throw new ApiError(403, '当前公司或上级公司已停用'); }
|
|
}
|
|
|
|
public function dispatchStructure(string $operation, array $profile, int $companyId, array $data, array $query): array
|
|
{
|
|
if ($companyId <= 1) { throw new ApiError(409, '医院结构只能由原医院目录管理'); }
|
|
$company = $this->company($companyId);
|
|
$guard = function () use ($profile, $companyId, $company, $operation): void {
|
|
if (!$this->companyActive($companyId)) { throw new ApiError(403, '当前公司或上级公司已停用'); }
|
|
if (!$this->isOwner($profile) && !$this->roleAccess($profile)->canStructure($profile, $company, $operation)) {
|
|
throw new ApiError(403, '当前角色没有该公司结构操作权限');
|
|
}
|
|
};
|
|
$guard();
|
|
if ($operation==='menu.lists' && $this->isOwner($profile)) {
|
|
(new KefuApplicationService($this->store,$this->source,$this->metadata))->refreshIfDue($companyId,(int)$profile['id']);
|
|
}
|
|
return (new CompanyStructureService($this->store, $company, (int) $profile['id'], $guard))->dispatch($operation, $data, $query);
|
|
}
|
|
|
|
public function decorateRecords(string $operation, array $result): array
|
|
{
|
|
if ($operation === 'admin.lists') {
|
|
foreach ($result['lists'] as &$row) { $row['gid'] = $this->store->identity((int) $row['id'])['gid']; }
|
|
unset($row);
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
private function saveCompany(array $profile, array $data): array
|
|
{
|
|
$this->requireOwner($profile);
|
|
Input::only($data, ['id', 'code', 'name', 'parent_id', 'disable']);
|
|
$id = isset($data['id']) && $data['id'] !== 0 ? Input::integer($data['id']) : 0;
|
|
$name = Input::text($data['name'] ?? null, '公司名称', 1, 64);
|
|
$parent = Input::integer($data['parent_id'] ?? 0, '上级公司', 0);
|
|
$disable = Input::integer($data['disable'] ?? 0, '公司状态', 0, 1);
|
|
return $this->store->write(function () use ($profile, $id, $name, $parent, $disable, $data): array {
|
|
$old = $id ? $this->company($id) : null;
|
|
if ($old && isset($data['code']) && $data['code'] !== $old['code']) { throw new ApiError(422, '公司编码创建后不可更改'); }
|
|
$code = $old['code'] ?? ($data['code'] ?? '');
|
|
if (!is_string($code) || !preg_match('/^[a-z][a-z0-9-]{1,31}$/D', $code)) { throw new ApiError(422, '公司编码须为2-32位小写字母、数字或短横线'); }
|
|
$cursor = $parent;
|
|
$seen = [];
|
|
while ($cursor) {
|
|
if ($cursor === $id || isset($seen[$cursor])) { throw new ApiError(422, '不能设置公司循环层级'); }
|
|
$seen[$cursor] = true;
|
|
$cursor = (int) $this->company($cursor)['parent_id'];
|
|
}
|
|
if ($this->store->one('SELECT id FROM company WHERE code=? AND id<>?', [$code, $id])) { throw new ApiError(409, '公司编码已存在'); }
|
|
if ($id) {
|
|
$this->store->execute('UPDATE company SET name=?,parent_id=?,disable=?,update_time=? WHERE id=?', [$name, $parent, $disable, ($this->clock)(), $id]);
|
|
} else {
|
|
if ((int) $this->store->one('SELECT COUNT(*) AS n FROM company')['n'] >= 200) { throw new ApiError(422, '公司数量已达当前上限'); }
|
|
$this->store->execute('INSERT INTO company(code,name,parent_id,disable,create_time,update_time) VALUES(?,?,?,?,?,?)', [$code, $name, $parent, $disable, ($this->clock)(), ($this->clock)()]);
|
|
$id = (int) $this->store->one('SELECT id FROM company WHERE code=?', [$code])['id'];
|
|
}
|
|
$this->store->audit((int) $profile['id'], $old ? 'company.update' : 'company.create', $id);
|
|
return $this->publicCompany($this->company($id), $profile);
|
|
});
|
|
}
|
|
|
|
private function sourceUsers(array $profile, array $session): array
|
|
{
|
|
$service = new SharedRecordsService($this->source, $session['source_token'], $profile);
|
|
$result = [];
|
|
for ($page = 1; $page <= 100; $page++) {
|
|
$batch = $service->dispatch('admin.lists', [], ['page_no' => $page, 'page_size' => 100]);
|
|
array_push($result, ...$batch['lists']);
|
|
if (count($result) >= $batch['count']) { return $result; }
|
|
}
|
|
throw new ApiError(502, '员工目录超过读取范围');
|
|
}
|
|
|
|
private function members(array $profile, array $session, array $query): array
|
|
{
|
|
$this->requireOwner($profile);
|
|
Input::only($query, ['company_id']);
|
|
$companyId = Input::integer($query['company_id'] ?? 1);
|
|
$this->company($companyId);
|
|
$rows = [];
|
|
foreach ($this->sourceUsers($profile, $session) as $user) {
|
|
$identity = $this->store->identity((int) $user['id']);
|
|
$member = $this->store->membership($companyId, (int) $user['id']);
|
|
$rows[] = ['id' => $user['id'], 'gid' => $identity['gid'], 'account' => $user['account'], 'name' => $user['name'],
|
|
'disable' => $user['disable'], 'member_status' => (int) ($member['member_status'] ?? 0), 'can_login' => (int) ($member['can_login'] ?? 0)];
|
|
}
|
|
return ['lists' => $rows, 'company_id' => $companyId];
|
|
}
|
|
|
|
private function saveMember(array $profile, array $session, array $data): array
|
|
{
|
|
$this->requireOwner($profile);
|
|
Input::only($data, ['company_id', 'admin_id', 'member_status', 'can_login']);
|
|
$companyId = Input::integer($data['company_id'] ?? null);
|
|
$adminId = Input::integer($data['admin_id'] ?? null);
|
|
$status = Input::integer($data['member_status'] ?? null, '任职状态', 0, 1);
|
|
$canLogin = Input::integer($data['can_login'] ?? null, '应用登录资格', 0, 1);
|
|
// 成员关系只是组织信息;兼容旧字段不联动业务权限,也不阻止独立调整归属。
|
|
$this->company($companyId);
|
|
$source = $this->source->request('GET', 'auth.admin/detail', ['id' => $adminId], $session['source_token']);
|
|
if ((int) ($source['id'] ?? 0) !== $adminId) { throw new ApiError(404, '员工不存在'); }
|
|
$this->store->identity($adminId);
|
|
$this->store->write(function () use ($profile, $companyId, $adminId, $status, $canLogin): void {
|
|
$now = ($this->clock)();
|
|
$this->store->execute('INSERT OR IGNORE INTO membership(company_id,source_id,member_status,can_login,update_time) VALUES(?,?,?,?,?)',
|
|
[$companyId, $adminId, $status, $canLogin, $now]);
|
|
$this->store->execute('UPDATE membership SET member_status=?,can_login=?,update_time=? WHERE company_id=? AND source_id=?',
|
|
[$status, $canLogin, $now, $companyId, $adminId]);
|
|
$this->store->audit((int) $profile['id'], 'membership.update', $companyId, $adminId);
|
|
});
|
|
return [];
|
|
}
|
|
|
|
private function registeredClient(mixed $clientId, mixed $redirect): array
|
|
{
|
|
$client = null;
|
|
if ($clientId === 'internet-hospital' && self::hospitalEntry() !== '') {
|
|
$client = ['id' => 'internet-hospital', 'company_id' => 1, 'entry' => self::hospitalEntry()];
|
|
} elseif ($clientId === KefuClient::ID && ($company = $this->kefuCompany())) {
|
|
$client = ['id' => KefuClient::ID, 'company_id' => (int) $company['id'], 'entry' => KefuClient::entry()];
|
|
}
|
|
if (!$client || !is_string($redirect) || !hash_equals($client['entry'], $redirect)) {
|
|
throw new ApiError(422, '应用或回调地址未注册');
|
|
}
|
|
return $client;
|
|
}
|
|
|
|
/** Registered kefu client and company gates apply equally to password proof and SSO. */
|
|
public function kefuPasswordLogin(callable $profileResolver): array
|
|
{
|
|
$client = $this->registeredClient(KefuClient::ID, KefuClient::entry());
|
|
if (!$this->companyActive($client['company_id'])) { throw new ApiError(403, '客服所属公司或上级公司已停用'); }
|
|
$profile = $profileResolver();
|
|
$this->requireClientLogin($profile, $client);
|
|
$this->store->audit((int) $profile['id'], 'kefu.password.login', $client['company_id'], (int) $profile['id']);
|
|
return $this->kefuIdentity($profile, $client);
|
|
}
|
|
|
|
private function kefuIdentity(array $profile, array $client): array
|
|
{
|
|
// Only source identity crosses this boundary; authorization belongs to kefu administrators.
|
|
return ['client_id' => KefuClient::ID, 'gid' => $this->store->identity((int) $profile['id'])['gid'],
|
|
'source_admin_id' => (int) $profile['id'], 'account' => $profile['account'], 'name' => $profile['name'],
|
|
'company_id' => $client['company_id']];
|
|
}
|
|
|
|
private function authorize(array $profile, string $bridgeToken, array $data): array
|
|
{
|
|
Input::only($data, ['client_id', 'redirect_uri', 'state', 'code_challenge', 'code_challenge_method']);
|
|
$client = $this->registeredClient($data['client_id'] ?? null, $data['redirect_uri'] ?? null);
|
|
$state = $data['state'] ?? null;
|
|
$challenge = $data['code_challenge'] ?? null;
|
|
if (!is_string($state) || !preg_match('/^[A-Za-z0-9_-]{32,128}$/D', $state) || !is_string($challenge)
|
|
|| !preg_match('/^[A-Za-z0-9_-]{43}$/D', $challenge) || ($data['code_challenge_method'] ?? '') !== 'S256') {
|
|
throw new ApiError(422, '登录校验参数无效');
|
|
}
|
|
$this->requireClientLogin($profile, $client);
|
|
$code = $this->store->issueCode(['session_ref' => hash('sha256', $bridgeToken), 'source_id' => (int) $profile['id'],
|
|
'company_id' => $client['company_id'], 'client_id' => $data['client_id'], 'redirect_uri' => $data['redirect_uri'], 'challenge' => $challenge], ($this->clock)());
|
|
$this->store->audit((int) $profile['id'], 'sso.authorize', $client['company_id'], (int) $profile['id']);
|
|
return ['redirect_url' => $data['redirect_uri'] . '?' . http_build_query(['code' => $code, 'state' => $state], '', '&', PHP_QUERY_RFC3986)];
|
|
}
|
|
|
|
public function exchange(array $data, callable $profileResolver): array
|
|
{
|
|
Input::only($data, ['client_id', 'redirect_uri', 'code', 'code_verifier']);
|
|
$client = $this->registeredClient($data['client_id'] ?? null, $data['redirect_uri'] ?? null);
|
|
$code = $data['code'] ?? null;
|
|
$verifier = $data['code_verifier'] ?? null;
|
|
if (!is_string($code) || !preg_match('/^[a-f0-9]{64}$/D', $code) || !is_string($verifier)
|
|
|| !preg_match('/^[A-Za-z0-9._~-]{43,128}$/D', $verifier)) { throw new ApiError(422, '登录凭证格式无效'); }
|
|
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
|
|
$grant = $this->store->consumeCode($code, $data['client_id'], $data['redirect_uri'], $challenge, ($this->clock)());
|
|
$session = $this->sessions->resolveReference($grant['session_ref'], $this->source->sourceKey());
|
|
$profile = $profileResolver($session['source_token']);
|
|
if ((int) $session['admin_id'] !== (int) $grant['source_id'] || (int) $profile['id'] !== (int) $grant['source_id']) { throw new ApiError(401, '登录状态已变化,请重新登录'); }
|
|
if (!empty($profile['requires_password_change']) || !empty($profile['requires_wecom_binding'])) { throw new ApiError(403, '请先完成账号验证'); }
|
|
$this->requireClientLogin($profile, $client, (int) $grant['company_id']);
|
|
if ($client['id'] === KefuClient::ID) {
|
|
$this->store->audit((int) $profile['id'], 'sso.exchange', $client['company_id'], (int) $profile['id']);
|
|
// 仅证明来源身份;绝不把原 root、角色、菜单或集团任职解释为客服业务授权。
|
|
return $this->kefuIdentity($profile, $client);
|
|
}
|
|
$result = $this->source->request('POST', 'identity.hospitalSso/issue', ['code_challenge' => $challenge, 'code_challenge_method' => 'S256'], $session['source_token']);
|
|
if (!is_string($result['ticket'] ?? null) || !preg_match('/^[a-f0-9]{64}$/D', $result['ticket'])) { throw new ApiError(502, '医院登录响应无效'); }
|
|
$this->store->audit((int) $profile['id'], 'sso.exchange', 1, (int) $profile['id']);
|
|
return ['ticket' => $result['ticket'], 'gid' => $this->store->identity((int) $profile['id'])['gid'],
|
|
'company_id' => 1, 'exchange_path' => '/adminapi/identity.hospitalSso/exchange'];
|
|
}
|
|
}
|