跟新
This commit is contained in:
+245
@@ -0,0 +1,245 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\controller;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\service\iam\IamOidcClient;
|
||||
use app\adminapi\service\iam\v2\{IamV2Client, IamV2Source, IamV2Manager, IamV2Flow, IamV2Target};
|
||||
|
||||
/** Every endpoint authorizes itself. Never relies on legacy unregistered-route allow rules. */
|
||||
final class IamV2Controller extends BaseAdminController
|
||||
{
|
||||
public array $notNeedLogin = ['status', 'introspect', 'checkSession', 'revocation', 'launchContinue', 'selfCallback', 'passwordContinue', 'targetConfig', 'targetPrepare', 'targetCallback', 'targetExchange', 'targetReset'];
|
||||
private function invokeV2(callable $fn)
|
||||
{
|
||||
try {
|
||||
if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$action = strtolower((string) $this->request->action());
|
||||
if (in_array($action, ['operation','preflight','batch','retry','selfstart','passwordsetup'], true) && !IamV2Client::feature('management')) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
if (in_array($action, ['launchstart','targetprepare','targetexchange'], true) && !IamV2Client::feature('launch')) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$reads = ['status','accounts','identities','operationresult','audit','job','targetconfig'];
|
||||
$read = in_array(strtolower((string) $this->request->action()), $reads, true);
|
||||
if (($read && !$this->request->isGet()) || (!$read && !$this->request->isPost())) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
return $this->data($fn())->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) {
|
||||
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
return $this->fail($code, ['error' => ['code' => $code]], 0, 0)->header(['Cache-Control' => 'no-store']);
|
||||
}
|
||||
}
|
||||
private function session(bool $recent = false): array
|
||||
{
|
||||
if (!$this->request->isGet()) {
|
||||
$expected = IamV2Client::origin((string) Config::get('iam.public_url'));
|
||||
if ((string) $this->request->header('origin') !== $expected) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
return IamV2Source::current((string) $this->request->header('token', ''), $recent);
|
||||
}
|
||||
private function input(): array { return (array) $this->request->post(); }
|
||||
private function requestId(): string
|
||||
{
|
||||
$key = (string) $this->request->header('idempotency-key', '');
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $key)) { throw new RuntimeException('INVALID_IDEMPOTENCY_KEY'); }
|
||||
return 'zyt-' . $key;
|
||||
}
|
||||
private function serviceAuth(): void
|
||||
{
|
||||
$expected = (string) Config::get('iam.v2_introspection_token', '');
|
||||
if (!$this->request->isPost() || strlen($expected) < 32 || !hash_equals('Bearer ' . $expected, (string) $this->request->header('authorization', ''))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public function status()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$token = (string) $this->request->header('token', '');
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
IamV2Source::admin((int) $legacy['admin_id']);
|
||||
$fresh = false; try { $s = IamV2Source::current($token); $fresh = $s['auth_time'] >= time() - 300; } catch (\Throwable $e) { $s = null; }
|
||||
$b = (new IamV2Manager())->binding((int) $legacy['admin_id']);
|
||||
return ['enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'session_ready' => $s !== null, 'reauth_required' => !$fresh,
|
||||
'management_capabilities' => IamV2Source::capabilities((int) $legacy['admin_id']),
|
||||
'protected_review_operator' => IamV2Source::reviewOperator((int) $legacy['admin_id']),
|
||||
'protected_account' => IamV2Source::protectedAccount((int) $legacy['admin_id'])] + $b;
|
||||
});
|
||||
}
|
||||
public function reauth()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
if ((string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
$s = IamV2Source::reauth((string) $this->request->header('token', ''), (string) $this->request->post('password', ''));
|
||||
return ['expires_at' => $s['auth_time'] + 300];
|
||||
});
|
||||
}
|
||||
public function accounts() { return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false); return (new IamV2Manager())->accounts((array) $this->request->get(), (int) $s['admin_id']); }); }
|
||||
public function identities()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
$s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
$q = http_build_query(['q' => mb_substr((string) $this->request->get('q', ''), 0, 64), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20], '', '&', PHP_QUERY_RFC3986);
|
||||
return (new IamV2Client())->call('GET', '/identities?' . $q);
|
||||
});
|
||||
}
|
||||
public function operation() { return $this->invokeV2(fn() => (new IamV2Manager())->operation($this->session(true), $this->input(), $this->requestId())); }
|
||||
public function operationResult() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'operation', (string) $this->request->param('id'))); }
|
||||
public function audit()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
IamV2Source::scope((int) $s['admin_id'], [(int) $this->request->param('id')]);
|
||||
return (new IamV2Client())->call('GET', '/audit?' . http_build_query(['externalAccountId' => (string) (int) $this->request->param('id'), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20])); });
|
||||
}
|
||||
public function preflight() { return $this->invokeV2(fn() => (new IamV2Manager())->preflight($this->session(true), (array) $this->request->post('items', []))); }
|
||||
public function batch() { return $this->invokeV2(fn() => (new IamV2Manager())->batch($this->session(true), (string) $this->request->post('preview_id'), (array) $this->request->post('indexes', []), $this->requestId())); }
|
||||
public function job() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'job', (string) $this->request->param('id'))); }
|
||||
public function retry() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(true), 'job', (string) $this->request->param('id'), true, (array) $this->request->post('indexes', []))); }
|
||||
public function introspect()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input(); return IamV2Source::introspect((string) ($b['proof'] ?? ''), (string) ($b['purpose'] ?? ''), $b['transactionId'] ?? null); });
|
||||
}
|
||||
private function serviceResult(callable $fn)
|
||||
{
|
||||
try { if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); } if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); } return json($fn())->header(['Cache-Control' => 'no-store']); }
|
||||
catch (\Throwable $e) { return json(['active' => false], 403)->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function checkSession()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input();
|
||||
return IamV2Source::liveStatus((string) ($b['sessionId'] ?? ''), (int) ($b['sessionVersion'] ?? 0),
|
||||
(string) ($b['purpose'] ?? ''), (array) ($b['targetLocalIds'] ?? [])); });
|
||||
}
|
||||
public function launchStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
IamV2Source::check($s['session_id'], (int) $s['version']);
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('launch', $intent, ['sessionId' => $s['session_id'], 'sessionVersion' => $s['version']]);
|
||||
setcookie('ZYT_IAM_V2_INTENT', $intent, ['expires' => time() + 300, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return ['url' => IamV2Client::origin((string) Config::get('iam.erp_url')) . '/iam/launch?source=zyt&intent=' . $intent]; });
|
||||
}
|
||||
public function launchContinue()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('launch');
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$intent = (string) $this->request->get('intent', ''); $cookie = (string) ($_COOKIE['ZYT_IAM_V2_INTENT'] ?? '');
|
||||
if ($intent === '' || !hash_equals($cookie, $intent)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$flow = IamV2Flow::take('launch', $intent, $s['session_id']); IamV2Source::check($s['session_id'], (int) $flow['sessionVersion']);
|
||||
$tx = (string) $this->request->get('transaction_id', '');
|
||||
$transaction = $client->call('GET', '/launch-transactions/' . rawurlencode($tx));
|
||||
if (($transaction['sourceApplicationId'] ?? '') !== 'zyt' || ($transaction['targetApplicationId'] ?? '') !== 'zmxy-erp') { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
(new IamV2Manager($client))->assertLinked((int) $s['admin_id']);
|
||||
$grant = $client->call('POST', '/launch-grants', ['transactionId' => $tx, 'proof' => IamV2Source::proof($s, 'launch', [(int) $s['admin_id']], [], $tx)]);
|
||||
$erpOrigin = IamV2Client::origin((string) Config::get('iam.erp_url'));
|
||||
$delivery = IamV2Client::https((string) Config::get('iam.erp_callback_url') ?: $erpOrigin . '/api/erp/iam/v2/launch/callback');
|
||||
if (!in_array($delivery, [$erpOrigin . '/api/erp/iam/v2/launch/callback', $erpOrigin . '/basic-api/api/erp/iam/v2/launch/callback'], true)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
if (($grant['deliveryUrl'] ?? '') !== $delivery) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return response(IamV2Flow::form($delivery, ['transaction_id' => $tx, 'grant' => $grant['grant']]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=launch_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
private function selfConfig(): array { $c = (array) Config::get('iam'); $c['redirect_uri'] = IamV2Client::origin($c['public_url']) . '/adminapi/iam/v2/self-link/callback'; return $c; }
|
||||
public function selfStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $a = IamV2Source::admin((int) $s['admin_id']);
|
||||
if (IamV2Source::protectedAccount((int) $a['id'])) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
$b = (new IamV2Manager())->binding((int) $s['admin_id'], true);
|
||||
if (($b['binding']['state'] ?? '') === 'verified') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$state = bin2hex(random_bytes(32)); $nonce = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('self_link', $state, ['sessionId' => $s['session_id'], 'nonce' => $nonce, 'verifier' => $verifier, 'version' => $b['binding']['version'] ?? null]);
|
||||
return ['url' => (new IamOidcClient($this->selfConfig()))->authorizationUrl($state, $nonce, $verifier) . '&prompt=login&max_age=300']; });
|
||||
}
|
||||
public function selfCallback()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('self_link');
|
||||
$central = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$flow = IamV2Flow::take('self_link', (string) $this->request->get('state', ''), $s['session_id']);
|
||||
$oidc = new IamOidcClient($this->selfConfig()); $oidc->exchange((string) $this->request->get('code', ''), $flow['verifier'], $flow['nonce']);
|
||||
$proof = IamV2Source::proof($s, 'self_link', [(int) $s['admin_id']], [], null, ['oidcNonce' => $flow['nonce']]);
|
||||
$body = ['idToken' => $oidc->verifiedIdToken(), 'nonce' => $flow['nonce'], 'proof' => $proof, 'externalAccountId' => (string) $s['admin_id']];
|
||||
if ($flow['version'] !== null) { $body['expectedVersion'] = (int) $flow['version']; }
|
||||
$central->call('POST', '/self-link', $body);
|
||||
(new IamV2Manager($central))->binding((int) $s['admin_id'], true);
|
||||
return redirect('/admin/user/setting?iam_result=linked')->header(['Cache-Control' => 'no-store']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=link_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function passwordSetup()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $b = (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
if (!($b['employee']['passwordSetupPending'] ?? false)) { throw new RuntimeException('PASSWORD_ALREADY_SET'); }
|
||||
$result = (new IamV2Client())->call('POST', '/password-setup', ['proof' => IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']])]);
|
||||
$url = parse_url((string) ($result['url'] ?? '')); $portal = parse_url(IamV2Client::origin((string) Config::get('iam.portal_url')));
|
||||
if (!$url || ($url['scheme'] ?? '') !== 'https' || ($url['host'] ?? '') !== $portal['host'] || ($url['port'] ?? 443) !== ($portal['port'] ?? 443) || isset($url['user']) || isset($url['pass']) || ($url['path'] ?? '') !== '/portal/password-setup') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('password_setup', $intent, ['sessionId' => $s['session_id'], 'requestId' => $result['requestId']], 900);
|
||||
setcookie('ZYT_IAM_PASSWORD_INTENT', $intent, ['expires' => time() + 900, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return $result; });
|
||||
}
|
||||
public function passwordContinue()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('password_setup');
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$f = IamV2Flow::take('password_setup', (string) ($_COOKIE['ZYT_IAM_PASSWORD_INTENT'] ?? ''), $s['session_id']);
|
||||
$id = (string) $this->request->get('request_id', ''); $state = (string) $this->request->get('state', '');
|
||||
if ($id !== $f['requestId'] || !preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $state)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$proof = IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']], [], $id, ['state' => $state]);
|
||||
$url = IamV2Client::origin((string) Config::get('iam.portal_url')) . '/portal/password-setup/authorize';
|
||||
return response(IamV2Flow::form($url, ['request_id' => $id, 'state' => $state, 'proof' => $proof]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=password_failed'); }
|
||||
}
|
||||
private function targetOrigin(): void
|
||||
{
|
||||
if (!$this->request->isPost() || (string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
public function targetConfig()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$source = (string) $this->request->get('source', 'iam-portal');
|
||||
return ['enabled' => IamV2Client::feature('launch'), 'global_enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'restart_url' => IamV2Client::origin((string) Config::get('iam.portal_url')) . ($source === 'iam-admin' ? '/admin' : '/portal')];
|
||||
});
|
||||
}
|
||||
public function targetPrepare()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
$out = (new IamV2Target())->prepare((string) $this->request->post('source', ''), (string) $this->request->post('intent', ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Target::COOKIE, $out['browser'], ['expires' => time() + 300, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['url' => $out['url']];
|
||||
});
|
||||
}
|
||||
public function targetCallback()
|
||||
{
|
||||
try {
|
||||
if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
$out = (new IamV2Target())->callback((string) $this->request->post('transaction_id', ''), (string) $this->request->post('grant', ''),
|
||||
(string) ($_COOKIE[IamV2Target::COOKIE] ?? ''), (string) $this->request->header('origin', ''));
|
||||
return redirect('/admin/iam/launch?' . http_build_query($out))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) {
|
||||
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
return redirect('/admin/iam/launch?iam_error=' . rawurlencode($code))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
}
|
||||
}
|
||||
public function targetExchange()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
return (new IamV2Target())->exchange((string) $this->request->post('ticket', ''), (string) ($_COOKIE[IamV2Target::COOKIE] ?? ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
});
|
||||
}
|
||||
public function targetReset()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
IamV2Source::revokeSession((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Source::COOKIE, '', ['expires' => 1, 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
setcookie(IamV2Target::COOKIE, '', ['expires' => 1, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['reset' => true];
|
||||
});
|
||||
}
|
||||
public function revocation()
|
||||
{
|
||||
return $this->serviceResult(fn() => \app\adminapi\service\iam\v2\IamV2Events::accept(
|
||||
(string) $this->request->getContent(), (string) $this->request->header('x-iam-signature', ''),
|
||||
(string) $this->request->header('x-iam-event-id', ''), (string) Config::get('iam.v2_event_secret', '')));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\controller\identity;
|
||||
|
||||
use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\service\IdentityHospitalSsoService;
|
||||
use app\common\service\JsonService;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
final class HospitalSsoController extends BaseAdminController
|
||||
{
|
||||
// The service authenticates the real source DB session; exchange authenticates its private PKCE ticket.
|
||||
public array $notNeedLogin = ['issue', 'exchange'];
|
||||
|
||||
public function issue()
|
||||
{
|
||||
return $this->handoff('issue');
|
||||
}
|
||||
|
||||
public function exchange()
|
||||
{
|
||||
return $this->handoff('exchange');
|
||||
}
|
||||
|
||||
private function handoff(string $operation)
|
||||
{
|
||||
$headers = ['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer'];
|
||||
if (!$this->request->isPost()) { return JsonService::fail('请使用POST请求')->code(405)->header($headers); }
|
||||
if ($this->request->get() !== []) { return JsonService::fail('请求包含不支持的字段')->header($headers); }
|
||||
$origin = (string) $this->request->header('origin', '');
|
||||
if ($operation === 'exchange' && (($origin !== '' && $origin !== $this->request->domain())
|
||||
|| $this->request->header('sec-fetch-site', '') === 'cross-site')) {
|
||||
return JsonService::fail('登录请求来源不合法')->header($headers);
|
||||
}
|
||||
try {
|
||||
$service = new IdentityHospitalSsoService();
|
||||
$result = $operation === 'issue'
|
||||
? $service->issue((string) $this->request->header('token', ''), $this->request->post())
|
||||
: $service->exchange($this->request->post());
|
||||
return JsonService::data($result)->header($headers);
|
||||
} catch (HttpResponseException $error) { return $error->getResponse()->header($headers); }
|
||||
catch (\Throwable $error) { return JsonService::fail('医院登录暂时不可用,请稍后重试')->header($headers); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\controller\identity;
|
||||
|
||||
use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\service\IdentitySessionService;
|
||||
use app\adminapi\validate\LoginValidate;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\service\JsonService;
|
||||
|
||||
/** 独立账号后台的个人会话接口,服务内部始终核验真实数据库会话。 */
|
||||
class SessionController extends BaseAdminController
|
||||
{
|
||||
// 首次改密/待绑定企微时也必须可用;这里仅跳过旧门禁,绝不跳过服务内认证。
|
||||
public array $notNeedLogin = ['login', 'verify', 'password', 'logout'];
|
||||
|
||||
public function verify()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
$params = $this->request->post();
|
||||
if (array_diff(array_keys($params), ['account', 'password']) !== []
|
||||
|| !is_string($params['account'] ?? null) || $params['account'] === '' || strlen($params['account']) > 4096
|
||||
|| str_contains($params['account'], "\0") || !is_string($params['password'] ?? null)
|
||||
|| $params['password'] === '' || strlen($params['password']) > 4096 || str_contains($params['password'], "\0")) {
|
||||
return JsonService::fail('登录参数不合法');
|
||||
}
|
||||
$params = (new LoginValidate())->post()->goCheck('verify');
|
||||
return $this->data(IdentitySessionService::verify($params));
|
||||
}
|
||||
|
||||
public function login()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
// 专用集团终端只在此入口接受;不扩大普通网页登录的终端白名单。
|
||||
$terminal = $this->request->post('terminal');
|
||||
$groupSession = in_array($terminal, [AdminTerminalEnum::GROUP_IDENTITY, (string) AdminTerminalEnum::GROUP_IDENTITY], true);
|
||||
// verify 场景保留原限流并禁用调试免密;服务仍在账号锁内校验全部参数与当前密码。
|
||||
$params = (new LoginValidate())->post()->goCheck($groupSession ? 'verify' : null);
|
||||
return $this->data(IdentitySessionService::login($params));
|
||||
}
|
||||
|
||||
public function password()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
IdentitySessionService::changePassword((string) $this->request->header('token', ''), $this->request->post());
|
||||
return $this->success('密码修改成功,请重新登录');
|
||||
}
|
||||
|
||||
public function logout()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return JsonService::fail('请使用POST请求');
|
||||
}
|
||||
$params = $this->request->post();
|
||||
if (array_diff(array_keys($params), ['all']) !== [] || !in_array($params['all'] ?? 0, [0, 1, '0', '1'], true)) {
|
||||
return JsonService::fail('退出参数不合法');
|
||||
}
|
||||
IdentitySessionService::logout((string) $this->request->header('token', ''), (int) ($params['all'] ?? 0) === 1);
|
||||
return $this->success('已退出登录');
|
||||
}
|
||||
}
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
use think\facade\Route;
|
||||
// Explicit method/path mapping; controller also fails closed for every v2 capability.
|
||||
Route::get('iam/v2/status', 'IamV2/status');
|
||||
Route::post('iam/v2/reauth', 'IamV2/reauth');
|
||||
Route::get('iam/v2/accounts', 'IamV2/accounts');
|
||||
Route::get('iam/v2/identities', 'IamV2/identities');
|
||||
Route::post('iam/v2/operations', 'IamV2/operation');
|
||||
Route::get('iam/v2/operations/:id', 'IamV2/operationResult');
|
||||
Route::get('iam/v2/accounts/:id/audit', 'IamV2/audit');
|
||||
Route::post('iam/v2/batch/preflight', 'IamV2/preflight');
|
||||
Route::post('iam/v2/batch', 'IamV2/batch');
|
||||
Route::get('iam/v2/jobs/:id', 'IamV2/job');
|
||||
Route::post('iam/v2/jobs/:id/retry', 'IamV2/retry');
|
||||
Route::post('iam/v2/proofs/introspect', 'IamV2/introspect');
|
||||
Route::post('iam/v2/sessions/check', 'IamV2/checkSession');
|
||||
Route::post('iam/v2/events/revocation', 'IamV2/revocation');
|
||||
Route::post('iam/v2/launch/start', 'IamV2/launchStart');
|
||||
Route::get('iam/v2/launch/continue', 'IamV2/launchContinue');
|
||||
Route::post('iam/v2/self-link/start', 'IamV2/selfStart');
|
||||
Route::get('iam/v2/self-link/callback', 'IamV2/selfCallback');
|
||||
Route::post('iam/v2/password-setup', 'IamV2/passwordSetup');
|
||||
Route::get('iam/v2/password-continue', 'IamV2/passwordContinue');
|
||||
|
||||
// ZYT as a target for the same person's IAM admin/portal session only.
|
||||
Route::get('iam/v2/launch/config', 'IamV2/targetConfig');
|
||||
Route::post('iam/v2/launch/prepare', 'IamV2/targetPrepare');
|
||||
Route::post('iam/v2/launch/callback', 'IamV2/targetCallback');
|
||||
Route::post('iam/v2/launch/exchange', 'IamV2/targetExchange');
|
||||
Route::post('iam/v2/launch/reset', 'IamV2/targetReset');
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use app\common\cache\AdminAuthCache;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\auth\AdminRole;
|
||||
use app\common\model\auth\AdminSession;
|
||||
use app\common\model\auth\SystemMenu;
|
||||
use app\common\model\auth\SystemRoleMenu;
|
||||
use think\facade\Log;
|
||||
|
||||
/** 原账号变更:事务内锁账号并撤销会话,提交成功后才清缓存。 */
|
||||
final class AdminAccessSyncService
|
||||
{
|
||||
public static function ids(array $ids): array
|
||||
{
|
||||
$ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn (int $id): bool => $id > 0)));
|
||||
sort($ids, SORT_NUMERIC);
|
||||
return $ids;
|
||||
}
|
||||
|
||||
public static function roleAdminIds(array $roleIds): array
|
||||
{
|
||||
return $roleIds === [] ? [] : self::ids(AdminRole::whereIn('role_id', $roleIds)->column('admin_id'));
|
||||
}
|
||||
|
||||
/** 菜单父节点变更也影响只获授子节点的账号。 */
|
||||
public static function menuAdminIds(int $menuId): array
|
||||
{
|
||||
$menuIds = [$menuId];
|
||||
$rows = SystemMenu::field('id,pid')->select()->toArray();
|
||||
do {
|
||||
$count = count($menuIds);
|
||||
foreach ($rows as $row) {
|
||||
if (in_array((int) $row['pid'], $menuIds, true)) { $menuIds[] = (int) $row['id']; }
|
||||
}
|
||||
$menuIds = self::ids($menuIds);
|
||||
} while (count($menuIds) !== $count);
|
||||
return self::roleAdminIds(self::ids(SystemRoleMenu::whereIn('menu_id', $menuIds)->column('role_id')));
|
||||
}
|
||||
|
||||
/** 调用者必须已开启事务;与密码登录、SSO签发和续期共用账号锁。 */
|
||||
public static function revoke(array $adminIds): array
|
||||
{
|
||||
$adminIds = self::ids($adminIds);
|
||||
if ($adminIds === []) { return []; }
|
||||
Admin::whereIn('id', $adminIds)->order('id')->lock(true)->field('id')->select();
|
||||
$tokens = AdminSession::whereIn('admin_id', $adminIds)->column('token');
|
||||
AdminSession::whereIn('admin_id', $adminIds)->update(['expire_time' => time() - 1, 'update_time' => time()]);
|
||||
return $tokens;
|
||||
}
|
||||
|
||||
public static function clearCommitted(array $adminIds, array $tokens): void
|
||||
{
|
||||
// DB是有效性的准绳;缓存故障不能把已提交操作伪报失败,也不能恢复旧会话。
|
||||
foreach ($tokens as $token) {
|
||||
try { (new AdminTokenCache())->deleteAdminInfo((string) $token); }
|
||||
catch (\Throwable $error) { Log::warning('账号变更已提交,会话缓存清理失败'); }
|
||||
}
|
||||
foreach (self::ids($adminIds) as $adminId) {
|
||||
try { (new AdminAuthCache($adminId))->clearAuthCache(); }
|
||||
catch (\Throwable $error) { Log::warning('账号变更已提交,权限缓存清理失败:admin_id=' . $adminId); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
/** 核心账号管理接口独立于可编辑菜单的URI登记,删除菜单也不能变成免鉴权接口。 */
|
||||
final class CoreAccountPermissionPolicy
|
||||
{
|
||||
/** null=非核心接口;[]为已登录账号自己的资料或导航接口;其余为允许的原权限别名。 */
|
||||
public static function aliases(string $uri): ?array
|
||||
{
|
||||
[$controller, $action] = array_pad(explode('/', strtolower($uri), 2), 2, '');
|
||||
if (!in_array($controller, ['auth.admin', 'auth.role', 'auth.menu', 'dept.dept'], true)) { return null; }
|
||||
if (($controller === 'auth.admin' && in_array($action, ['myself', 'editself', 'bindworkwechat', 'unbindworkwechat'], true))
|
||||
|| ($controller === 'auth.menu' && $action === 'route')) { return []; }
|
||||
$aliases = [$uri];
|
||||
if ($action === 'detail') { $aliases = array_merge($aliases, [$controller . '/lists', $controller . '/edit']); }
|
||||
if ($action === 'all' || ($controller === 'dept.dept' && $action === 'leaderdept')) {
|
||||
$aliases = array_merge($aliases, [$controller . '/lists', $controller . '/add', $controller . '/edit']);
|
||||
if (in_array($controller, ['auth.role', 'dept.dept'], true)) {
|
||||
$aliases = array_merge($aliases, ['auth.admin/add', 'auth.admin/edit']);
|
||||
}
|
||||
if ($controller === 'auth.menu') { $aliases = array_merge($aliases, ['auth.role/add', 'auth.role/edit']); }
|
||||
}
|
||||
if ($controller === 'auth.menu' && $action === 'updatestatus') { $aliases[] = 'auth.menu/edit'; }
|
||||
return $aliases;
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\auth\AdminSession;
|
||||
use app\common\service\JsonService;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
/** The hospital trusts its own live source session, never a caller-provided identity. */
|
||||
final class IdentityHospitalSsoService
|
||||
{
|
||||
private IdentityHospitalSsoTicketStore $tickets;
|
||||
|
||||
public function __construct(?IdentityHospitalSsoTicketStore $tickets = null)
|
||||
{
|
||||
$this->tickets = $tickets ?? new IdentityHospitalSsoTicketStore(app()->getRuntimePath() . 'identity-hospital-sso');
|
||||
}
|
||||
|
||||
public function issue(string $sourceToken, array $data): array
|
||||
{
|
||||
self::only($data, ['code_challenge', 'code_challenge_method']);
|
||||
if (($data['code_challenge_method'] ?? null) !== 'S256'
|
||||
|| !is_string($data['code_challenge'] ?? null)
|
||||
|| !preg_match('/^[A-Za-z0-9_-]{43}$/D', $data['code_challenge'])) {
|
||||
JsonService::throw('登录验证参数不合法');
|
||||
}
|
||||
if ($sourceToken === '' || strlen($sourceToken) > 512 || preg_match('/[\x00-\x20\x7f]/', $sourceToken)) {
|
||||
JsonService::throw('请先登录集团工作台', [], -1);
|
||||
}
|
||||
return Db::transaction(function () use ($sourceToken, $data): array {
|
||||
$candidate = AdminSession::where('token', $sourceToken)->findOrEmpty();
|
||||
[$admin, $session] = self::lockSource($candidate, hash('sha256', $sourceToken));
|
||||
self::ready($admin);
|
||||
// 交接源仍受原 IP 绑定保护;目标 exchange 才允许来自医院浏览器的不同 IP。
|
||||
$info = (new AdminTokenCache())->getAdminInfo($sourceToken);
|
||||
$ip = request()->ip();
|
||||
if (!$info || (int) ($info['admin_id'] ?? 0) !== (int) $admin['id']
|
||||
|| (($info['login_ip'] ?? '') !== $ip && !AuthMiddleware::isTrustedRpaServerRequest(
|
||||
(array) $info, $ip, env('wecom_rpa.server_ips', '')))) {
|
||||
JsonService::throw('ip地址发生变化,请重新登录', [], -1);
|
||||
}
|
||||
return ['ticket' => $this->tickets->issue((int) $session['id'], hash('sha256', $sourceToken), $data['code_challenge'])];
|
||||
});
|
||||
}
|
||||
|
||||
public function exchange(array $data): array
|
||||
{
|
||||
self::only($data, ['ticket', 'code_verifier']);
|
||||
if (!is_string($data['ticket'] ?? null) || !is_string($data['code_verifier'] ?? null)) {
|
||||
JsonService::throw('登录验证参数不合法');
|
||||
}
|
||||
try { $record = $this->tickets->consume($data['ticket'], $data['code_verifier']); }
|
||||
catch (\RuntimeException $error) { JsonService::throw('登录票据已失效,请重新从集团工作台进入'); }
|
||||
|
||||
$result = Db::transaction(static function () use ($record): array {
|
||||
$candidate = AdminSession::where('id', $record['session_id'])->findOrEmpty();
|
||||
[$admin] = self::lockSource($candidate, $record['token_hash']);
|
||||
self::ready($admin);
|
||||
$now = time();
|
||||
$target = AdminSession::where('admin_id', (int) $admin['id'])
|
||||
->where('terminal', AdminTerminalEnum::GROUP_HOSPITAL)->lock(true)->findOrEmpty();
|
||||
$oldToken = $target->isEmpty() ? '' : (string) $target['token'];
|
||||
$token = $oldToken;
|
||||
if ($target->isEmpty() || (int) $target['expire_time'] <= $now || (int) $admin['multipoint_login'] === 0) {
|
||||
// 原 admin_session.token 为 varchar(32),保持128位随机性且不修改业务表。
|
||||
$token = bin2hex(random_bytes(16));
|
||||
}
|
||||
$values = ['token' => $token, 'expire_time' => $now + (int) Config::get('project.admin_token.expire_duration'),
|
||||
'update_time' => $now];
|
||||
if ($target->isEmpty()) {
|
||||
AdminSession::create($values + ['admin_id' => (int) $admin['id'], 'terminal' => AdminTerminalEnum::GROUP_HOSPITAL]);
|
||||
} else { $target->save($values); }
|
||||
// Persist the independent session under the same account/source locks. Publish its cache only after commit.
|
||||
return ['token' => $token, 'old_token' => $oldToken, 'name' => (string) $admin['name'],
|
||||
'avatar' => (string) $admin['avatar']];
|
||||
});
|
||||
$cache = new AdminTokenCache();
|
||||
if ($result['old_token'] !== '' && $result['old_token'] !== $result['token']) {
|
||||
$cache->deleteAdminInfo($result['old_token']);
|
||||
}
|
||||
// This executes in the real hospital browser request, retaining the original per-token IP protection.
|
||||
$info = $cache->setAdminInfo($result['token']);
|
||||
if (!$info) { JsonService::throw('登录已失效,请重新进入', [], -1); }
|
||||
return ['name' => $result['name'], 'avatar' => $result['avatar'], 'role_name' => $info['role_name'],
|
||||
'token' => $result['token'], 'is_paw' => 1, 'need_bind_work_wechat' => false];
|
||||
}
|
||||
|
||||
private static function lockSource(AdminSession $candidate, string $tokenHash): array
|
||||
{
|
||||
if ($candidate->isEmpty()) { JsonService::throw('集团登录已失效,请重新登录', [], -1); }
|
||||
// Same order as IdentitySessionService and account changes: account row, then the exact session row.
|
||||
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || !empty($admin->getData('delete_time'))) {
|
||||
JsonService::throw('集团登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
$session = AdminSession::where('id', (int) $candidate['id'])->where('admin_id', (int) $admin['id'])
|
||||
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
|
||||
if ($session->isEmpty() || !hash_equals($tokenHash, hash('sha256', (string) $session['token']))
|
||||
|| (int) $session['terminal'] === AdminTerminalEnum::GROUP_HOSPITAL) {
|
||||
JsonService::throw('集团登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
return [$admin, $session];
|
||||
}
|
||||
|
||||
private static function ready(Admin $admin): void
|
||||
{
|
||||
if ((int) $admin['is_paw'] !== 1) { JsonService::throw('请先在集团工作台完成首次密码修改'); }
|
||||
if (LoginLogic::adminMustBindWorkWechat(['root' => (int) $admin['root'],
|
||||
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? '')])) {
|
||||
JsonService::throw('请先在原后台完成企业微信绑定', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
|
||||
}
|
||||
}
|
||||
|
||||
private static function only(array $data, array $allowed): void
|
||||
{
|
||||
if (array_diff(array_keys($data), $allowed) !== []) { JsonService::throw('请求包含不支持的字段'); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** Private single-server handoff tickets. Neither raw source tokens nor passwords are persisted. */
|
||||
final class IdentityHospitalSsoTicketStore
|
||||
{
|
||||
private \Closure $clock;
|
||||
|
||||
public function __construct(private string $directory, ?callable $clock = null)
|
||||
{
|
||||
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
|
||||
}
|
||||
|
||||
public function issue(int $sessionId, string $tokenHash, string $challenge): string
|
||||
{
|
||||
return $this->locked(function () use ($sessionId, $tokenHash, $challenge): string {
|
||||
foreach (array_slice(glob($this->directory . '/*.json') ?: [], 0, 200) as $path) {
|
||||
$old = $this->read($path);
|
||||
if ($old !== null && (int) ($old['expires'] ?? 0) <= ($this->clock)()) { unlink($path); }
|
||||
}
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
$record = ['session_id' => $sessionId, 'token_hash' => $tokenHash, 'challenge' => $challenge,
|
||||
'expires' => ($this->clock)() + 30];
|
||||
$path = $this->path($ticket);
|
||||
$file = fopen($path, 'x+b');
|
||||
if ($file === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
try {
|
||||
chmod($path, 0600);
|
||||
$json = json_encode($record, JSON_THROW_ON_ERROR);
|
||||
if (fwrite($file, $json) !== strlen($json) || !fflush($file)) {
|
||||
throw new RuntimeException('Hospital handoff storage unavailable');
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
fclose($file);
|
||||
unlink($path);
|
||||
throw $error;
|
||||
}
|
||||
fclose($file);
|
||||
return $ticket;
|
||||
});
|
||||
}
|
||||
|
||||
public function consume(string $ticket, string $verifier): array
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{64}$/D', $ticket)
|
||||
|| !preg_match('/^[A-Za-z0-9._~-]{43,128}$/D', $verifier)) {
|
||||
throw new RuntimeException('Hospital handoff invalid');
|
||||
}
|
||||
return $this->locked(function () use ($ticket, $verifier): array {
|
||||
$path = $this->path($ticket);
|
||||
$record = $this->read($path);
|
||||
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
|
||||
if ($record === null || !is_int($record['expires'] ?? null) || $record['expires'] <= ($this->clock)()
|
||||
|| !is_int($record['session_id'] ?? null) || $record['session_id'] < 1
|
||||
|| !is_string($record['token_hash'] ?? null) || !preg_match('/^[a-f0-9]{64}$/D', $record['token_hash'])
|
||||
|| !is_string($record['challenge'] ?? null) || !hash_equals($record['challenge'], $challenge)) {
|
||||
throw new RuntimeException('Hospital handoff invalid');
|
||||
}
|
||||
// The global private lock covers open/read/delete, so simultaneous exchanges cannot replay.
|
||||
if (!unlink($path)) { throw new RuntimeException('Hospital handoff consumption failed'); }
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
private function read(string $path): ?array
|
||||
{
|
||||
if (!is_file($path) || is_link($path) || filesize($path) > 4096) { return null; }
|
||||
try { $record = json_decode((string) file_get_contents($path), true, 8, JSON_THROW_ON_ERROR); }
|
||||
catch (\JsonException $error) { return null; }
|
||||
return is_array($record) ? $record : null;
|
||||
}
|
||||
|
||||
private function path(string $ticket): string
|
||||
{
|
||||
return $this->directory . '/' . hash('sha256', $ticket) . '.json';
|
||||
}
|
||||
|
||||
private function locked(callable $operation): mixed
|
||||
{
|
||||
if (is_link($this->directory) || (!is_dir($this->directory)
|
||||
&& !mkdir($this->directory, 0700, true) && !is_dir($this->directory))) {
|
||||
throw new RuntimeException('Hospital handoff storage unavailable');
|
||||
}
|
||||
chmod($this->directory, 0700);
|
||||
$path = $this->directory . '/.lock';
|
||||
if (is_link($path)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
$lock = fopen($path, 'c+b');
|
||||
if ($lock === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
chmod($path, 0600);
|
||||
try {
|
||||
if (!flock($lock, LOCK_EX)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
|
||||
return $operation();
|
||||
} finally { flock($lock, LOCK_UN); fclose($lock); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\auth\AdminSession;
|
||||
use app\common\service\JsonService;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
/** 共用原账号密码与原会话,不信任桥接层提供的用户编号或root标记。 */
|
||||
final class IdentitySessionService
|
||||
{
|
||||
/** 验证外部子系统的凭据,不创建、复用、刷新或注销原系统会话。 */
|
||||
public static function verify(array $params): array
|
||||
{
|
||||
if (array_diff(array_keys($params), ['account', 'password']) !== []) {
|
||||
JsonService::throw('请求包含不支持的字段');
|
||||
}
|
||||
$account = $params['account'] ?? null;
|
||||
$password = $params['password'] ?? null;
|
||||
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|
||||
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")) {
|
||||
JsonService::throw('登录参数不合法');
|
||||
}
|
||||
return Db::transaction(static function () use ($account, $password): array {
|
||||
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
|
||||
$salt = (string) Config::get('project.unique_identification');
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|
||||
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
|
||||
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
|
||||
}
|
||||
return ['id' => (int) $admin['id'], 'account' => (string) $admin['account'],
|
||||
'name' => (string) ($admin['name'] ?? ''), 'disable' => 0,
|
||||
'requires_password_change' => (int) ($admin['is_paw'] ?? 1) === 0,
|
||||
'requires_wecom_binding' => LoginLogic::adminMustBindWorkWechat([
|
||||
'root' => (int) ($admin['root'] ?? 0),
|
||||
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
|
||||
])];
|
||||
});
|
||||
}
|
||||
|
||||
/** 与个人改密共用账号行锁,绝不信任事务前验证器的密码快照或调试免密结果。 */
|
||||
public static function login(array $params): array
|
||||
{
|
||||
if (array_diff(array_keys($params), ['account', 'password', 'terminal']) !== []) {
|
||||
JsonService::throw('请求包含不支持的字段');
|
||||
}
|
||||
$account = $params['account'] ?? null;
|
||||
$password = $params['password'] ?? null;
|
||||
$terminal = $params['terminal'] ?? null;
|
||||
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|
||||
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")
|
||||
|| (!is_int($terminal) && !is_string($terminal))
|
||||
|| !in_array((string) $terminal, ['1', '2', '7', '9', (string) AdminTerminalEnum::GROUP_IDENTITY], true)) {
|
||||
JsonService::throw('登录参数不合法');
|
||||
}
|
||||
return Db::transaction(static function () use ($account, $password, $params): array {
|
||||
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
|
||||
$salt = (string) Config::get('project.unique_identification');
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|
||||
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
|
||||
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
|
||||
}
|
||||
// 原登录的资料更新和会话签发均在该账号锁释放前完成。
|
||||
return (new LoginLogic())->login($params);
|
||||
});
|
||||
}
|
||||
|
||||
public static function changePassword(string $token, array $params): void
|
||||
{
|
||||
if (array_diff(array_keys($params), ['old_password', 'password', 'password_confirm']) !== []) {
|
||||
JsonService::throw('请求包含不支持的字段');
|
||||
}
|
||||
$password = $params['password'] ?? null;
|
||||
if (!is_string($password) || strlen($password) < 6 || strlen($password) > 32 || str_contains($password, "\0")) {
|
||||
JsonService::throw('密码长度须在6-32字节');
|
||||
}
|
||||
if ($password !== ($params['password_confirm'] ?? null)) {
|
||||
JsonService::throw('两次输入的密码不一致');
|
||||
}
|
||||
$tokens = Db::transaction(static function () use ($token, $params, $password): array {
|
||||
[$admin] = self::lockContext($token);
|
||||
$firstPassword = (int) ($admin['is_paw'] ?? 1) === 0;
|
||||
if (!$firstPassword && LoginLogic::adminMustBindWorkWechat([
|
||||
'root' => (int) $admin['root'], 'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
|
||||
])) {
|
||||
JsonService::throw('请先在原后台绑定企业微信', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
|
||||
}
|
||||
$salt = (string) Config::get('project.unique_identification');
|
||||
if (!$firstPassword) {
|
||||
$oldPassword = $params['old_password'] ?? null;
|
||||
if (!is_string($oldPassword) || strlen($oldPassword) > 1024
|
||||
|| !hash_equals((string) $admin['password'], create_password($oldPassword, $salt))) {
|
||||
JsonService::throw('当前密码错误');
|
||||
}
|
||||
}
|
||||
$id = (int) $admin['id'];
|
||||
Admin::where('id', $id)->update([
|
||||
'password' => create_password($password, $salt), 'is_paw' => 1, 'update_time' => time(),
|
||||
]);
|
||||
return self::expire($id, null);
|
||||
});
|
||||
self::clearTokens($tokens);
|
||||
}
|
||||
|
||||
public static function logout(string $token, bool $all = false): void
|
||||
{
|
||||
$tokens = Db::transaction(static function () use ($token, $all): array {
|
||||
[$admin] = self::lockContext($token);
|
||||
return self::expire((int) $admin['id'], $all ? null : $token);
|
||||
});
|
||||
self::clearTokens($tokens);
|
||||
}
|
||||
|
||||
/** 先锁账号再锁会话,避免两个会话同时改密时互相等待。 */
|
||||
private static function lockContext(string $token): array
|
||||
{
|
||||
if ($token === '' || strlen($token) > 512 || preg_match('/[\x00-\x20\x7f]/', $token)) {
|
||||
JsonService::throw('请先登录', [], -1);
|
||||
}
|
||||
$candidate = AdminSession::where('token', $token)->findOrEmpty();
|
||||
if ($candidate->isEmpty()) {
|
||||
JsonService::throw('登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) {
|
||||
JsonService::throw('登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
$session = AdminSession::where('admin_id', (int) $admin['id'])->where('token', $token)
|
||||
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
|
||||
if ($session->isEmpty()) {
|
||||
JsonService::throw('登录已失效,请重新登录', [], -1);
|
||||
}
|
||||
return [$admin, $session];
|
||||
}
|
||||
|
||||
private static function expire(int $adminId, ?string $token): array
|
||||
{
|
||||
$query = static function () use ($adminId, $token) {
|
||||
$builder = AdminSession::where('admin_id', $adminId);
|
||||
return $token === null ? $builder : $builder->where('token', $token);
|
||||
};
|
||||
$tokens = $query()->column('token');
|
||||
$query()->update(['expire_time' => time() - 1, 'update_time' => time()]);
|
||||
return $tokens;
|
||||
}
|
||||
|
||||
private static function clearTokens(array $tokens): void
|
||||
{
|
||||
$cache = new AdminTokenCache();
|
||||
foreach ($tokens as $token) {
|
||||
$cache->deleteAdminInfo((string) $token);
|
||||
}
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
|
||||
/** Dedicated v2 application credential; never falls back to the v1 provisioning token. */
|
||||
final class IamV2Client
|
||||
{
|
||||
public function __construct(private ?array $settings = null, private $transport = null)
|
||||
{
|
||||
$this->settings ??= (array) Config::get('iam', []);
|
||||
if (!self::enabled($this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
self::https((string) ($this->settings['api_url'] ?? ''));
|
||||
foreach (['public_url', 'erp_url'] as $field) { self::origin((string) ($this->settings[$field] ?? '')); }
|
||||
if (strlen((string) ($this->settings['v2_token'] ?? '')) < 32) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
}
|
||||
public static function enabled(?array $settings = null): bool
|
||||
{
|
||||
$settings ??= (array) Config::get('iam', []);
|
||||
return filter_var($settings['v2_enabled'] ?? false, FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
public static function feature(string $feature, ?array $settings = null): bool
|
||||
{
|
||||
$settings ??= (array) Config::get('iam', []);
|
||||
if (!in_array($feature, ['management', 'launch'], true)) { return false; }
|
||||
return self::enabled($settings) && filter_var($settings['v2_' . $feature . '_enabled'] ?? false, FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
public static function https(string $url): string
|
||||
{
|
||||
$p = parse_url($url);
|
||||
if (!$p || ($p['scheme'] ?? '') !== 'https' || empty($p['host']) || isset($p['user']) || isset($p['pass'])
|
||||
|| isset($p['fragment']) || isset($p['query']) || preg_match('/[\x00-\x20\x7f\\\\]/', $url)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return rtrim($url, '/');
|
||||
}
|
||||
public static function origin(string $url): string
|
||||
{
|
||||
$url = self::https($url);
|
||||
if ((parse_url($url, PHP_URL_PATH) ?? '') !== '') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $url;
|
||||
}
|
||||
public function call(string $method, string $path, array $body = [], ?string $key = null): array
|
||||
{
|
||||
if (!preg_match('#^/[a-zA-Z0-9/_?=&%.:-]+$#D', $path) || str_contains($path, '..')) { throw new RuntimeException('INVALID_PATH'); }
|
||||
$url = rtrim($this->settings['api_url'], '/') . '/internal/v2/applications/' . rawurlencode($this->settings['application_id'] ?? 'zyt') . $path;
|
||||
$management = preg_match('#^/(identities|operations|audit|batch|jobs)(/|[?]|$)#D', $path) === 1;
|
||||
$credential = (string) ($this->settings[$management ? 'v2_management_token' : 'v2_token'] ?? '');
|
||||
if (strlen($credential) < 32 || preg_match('/[\r\n]/', $credential)
|
||||
|| ($management && hash_equals((string) $this->settings['v2_token'], $credential))) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$headers = ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer ' . $credential];
|
||||
if ($method !== 'GET') {
|
||||
$headers[] = 'X-Request-ID: ' . bin2hex(random_bytes(16));
|
||||
$headers[] = 'Idempotency-Key: ' . ($key ?? bin2hex(random_bytes(24)));
|
||||
}
|
||||
$data = $method === 'GET' ? '' : json_encode($body, JSON_THROW_ON_ERROR);
|
||||
if ($this->transport) { $r = ($this->transport)($method, $url, $headers, $data); }
|
||||
else {
|
||||
$c = curl_init($url); $response = '';
|
||||
curl_setopt_array($c, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_WRITEFUNCTION => static function ($c, $chunk) use (&$response) {
|
||||
if (strlen($response) + strlen($chunk) > 2097152) { return 0; } $response .= $chunk; return strlen($chunk);
|
||||
}]);
|
||||
$ok = curl_exec($c); $r = ['status' => curl_getinfo($c, CURLINFO_RESPONSE_CODE), 'body' => $ok === false ? '' : $response]; curl_close($c);
|
||||
}
|
||||
$result = json_decode($r['body'] ?? '', true);
|
||||
if (!is_array($result)) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$operationEnvelope = isset($result['id']) && is_string($result['id'])
|
||||
&& in_array($result['status'] ?? '', ['pending', 'succeeded', 'failed', 'conflict'], true)
|
||||
&& preg_match('#^/(operations|jobs|batch)(/|$)#D', $path);
|
||||
if (($r['status'] ?? 0) < 200 || $r['status'] >= 300 || (isset($result['error']) && !$operationEnvelope)) {
|
||||
$code = $result['error']['code'] ?? 'SERVICE_UNAVAILABLE';
|
||||
throw new RuntimeException(preg_match('/^[A-Z_]{3,64}$/D', $code) ? $code : 'SERVICE_UNAVAILABLE');
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Events
|
||||
{
|
||||
public static function accept(string $raw, string $signature, string $eventId, string $secret, ?callable $revoke = null, ?callable $refresh = null, ?callable $locate = null, ?callable $generation = null): array
|
||||
{
|
||||
if (strlen($raw) > 65536 || strlen($secret) < 32 || !hash_equals('sha256=' . hash_hmac('sha256', $raw, $secret), $signature)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$event = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (empty($event['employeeId']) || $eventId === '' || strlen($eventId) > 128 || $eventId !== ($event['id'] ?? '') || !in_array('zyt', (array) ($event['applicationIds'] ?? []), true)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$occurredAt = (string) ($event['occurredAt'] ?? '');
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}T.*(Z|[+-][0-9]{2}:[0-9]{2})$/D', $occurredAt)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$stamp = strtotime($occurredAt);
|
||||
if (!$stamp || $stamp > time() + 60) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$customRevoke = $revoke !== null;
|
||||
$revoke ??= fn(int $id) => IamV2Manager::revoke($id);
|
||||
$refresh ??= fn(int $id) => (new IamV2Manager())->binding($id, true);
|
||||
$generation ??= $customRevoke ? fn(int $id, int $upper) => $revoke($id) : fn(int $id, int $upper) => IamV2Source::revokeGeneration($id, $upper, (string) $event['employeeId']);
|
||||
$locate ??= static function (array $event): array {
|
||||
if (($event['eventType'] ?? '') === 'binding_revoked' && isset($event['externalAccountId'])) {
|
||||
if (!is_string($event['externalAccountId']) || !preg_match('/^[1-9][0-9]{0,9}$/D', $event['externalAccountId'])) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return [(int) $event['externalAccountId']];
|
||||
}
|
||||
$reply = (new IamV2Client())->call('GET', '/bindings?' . http_build_query(['employeeId' => $event['employeeId'], 'page' => 1, 'pageSize' => 100], '', '&', PHP_QUERY_RFC3986));
|
||||
if (($reply['total'] ?? 0) > 100) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$ids = [];
|
||||
foreach ($reply['items'] ?? [] as $item) {
|
||||
if (($item['binding']['employeeId'] ?? '') !== $event['employeeId'] || ($item['binding']['applicationId'] ?? '') !== 'zyt') { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$external = (string) ($item['binding']['externalAccountId'] ?? '');
|
||||
if (!preg_match('/^[1-9][0-9]{0,9}$/D', $external)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$ids[] = (int) $external;
|
||||
}
|
||||
return $ids;
|
||||
};
|
||||
return Db::transaction(function () use ($event, $eventId, $raw, $revoke, $refresh, $locate, $generation) {
|
||||
$existing = Db::name('iam_v2_event')->where('event_id', $eventId)->lock(true)->find();
|
||||
if ($existing) {
|
||||
if (!hash_equals($existing['digest'], hash('sha256', $raw))) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return ['accepted' => true, 'duplicate' => true];
|
||||
}
|
||||
Db::name('iam_v2_event')->insert(['event_id' => $eventId, 'digest' => hash('sha256', $raw), 'received_at' => time()]);
|
||||
$rows = Db::name('iam_v2_binding')->where('employee_id', (string) $event['employeeId'])->lock(true)->select()->toArray();
|
||||
if (!$rows && ($event['eventType'] ?? '') !== 'source_binding_revoked') {
|
||||
foreach ($locate($event) as $id) {
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$row) { $refresh($id); $row = Db::name('iam_v2_binding')->where('admin_id', $id)->find(); }
|
||||
if ($row) { $rows[] = $row; }
|
||||
}
|
||||
}
|
||||
foreach ($rows as $row) {
|
||||
$bindingEvent = ($event['eventType'] ?? '') === 'binding_revoked'
|
||||
|| in_array($event['reason'] ?? '', ['iam.v2.unbind', 'iam.v2.rebind'], true);
|
||||
// ZYT is source-only in this rollout; target-derived revocation belongs to ERP.
|
||||
if (($event['eventType'] ?? '') === 'source_binding_revoked') { continue; }
|
||||
$upper = isset($event['bindingVersion']) ? (int) $event['bindingVersion'] : null;
|
||||
if ($bindingEvent && $upper !== null && ($upper < (int) $row['version'] || $row['employee_id'] !== $event['employeeId'])) { $generation((int) $row['admin_id'], $upper); continue; }
|
||||
if (!$bindingEvent || $upper === null) {
|
||||
// Durable outbox delivery may be old. Current central state wins over a stale generic event.
|
||||
// A failed lookup rolls back event receipt, so the durable outbox can retry.
|
||||
$current = $refresh((int) $row['admin_id']);
|
||||
if (($current['binding']['state'] ?? '') === 'verified' && ($current['employee']['status'] ?? '') === 'active'
|
||||
&& ($current['access']['allowed'] ?? false)) { continue; }
|
||||
}
|
||||
$updates = ['checked_at' => 0];
|
||||
// Personnel disable/entitlement events invalidate sessions, not the binding itself.
|
||||
// A versioned binding event carries the OLD generation as its revocation upper bound.
|
||||
if ($bindingEvent && $upper !== null && $upper > 0) {
|
||||
$updates['state'] = 'revoked'; $updates['version'] = max((int) $row['version'], $upper);
|
||||
}
|
||||
Db::name('iam_v2_binding')->where('admin_id', $row['admin_id'])->update($updates);
|
||||
if ($bindingEvent && $upper !== null) { $generation((int) $row['admin_id'], $upper); }
|
||||
else { $revoke((int) $row['admin_id']); }
|
||||
}
|
||||
return ['accepted' => true];
|
||||
});
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Flow
|
||||
{
|
||||
public static function put(string $kind, string $secret, array $payload, int $ttl = 300): void
|
||||
{
|
||||
Db::name('iam_v2_flow')->insert(['flow_key' => hash('sha256', $kind . ':' . $secret), 'kind' => $kind,
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + $ttl, 'consumed' => 0]);
|
||||
}
|
||||
public static function peek(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', hash('sha256', $kind . ':' . $secret))->find();
|
||||
if (!$row || $row['expires_at'] <= time() || (int) $row['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['sessionId'] ?? '') !== $sid) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
return $p;
|
||||
}
|
||||
public static function take(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
return Db::transaction(function () use ($kind, $secret, $sid) {
|
||||
$key = hash('sha256', $kind . ':' . $secret);
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', $key)->lock(true)->find();
|
||||
if (!$row || $row['expires_at'] <= time() || (int) $row['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['sessionId'] ?? '') !== $sid) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if (Db::name('iam_v2_flow')->where('flow_key', $key)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return $p;
|
||||
});
|
||||
}
|
||||
public static function form(string $url, array $fields): string
|
||||
{
|
||||
$nonce = bin2hex(random_bytes(18));
|
||||
$escape = fn($s) => htmlspecialchars((string) $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
$inputs = '';
|
||||
foreach ($fields as $name => $value) { $inputs .= '<input type="hidden" name="' . $escape($name) . '" value="' . $escape($value) . '">'; }
|
||||
$origin = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . (parse_url($url, PHP_URL_PORT) ? ':' . parse_url($url, PHP_URL_PORT) : '');
|
||||
return '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; base-uri \'none\'; form-action ' . $escape($origin) . '; script-src \'nonce-' . $nonce . '\'"><title>正在验证身份</title><form method="post" action="' . $escape($url) . '">' . $inputs . '<button>继续</button></form><script nonce="' . $nonce . '">document.forms[0].submit()</script>';
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
|
||||
final class IamV2Manager
|
||||
{
|
||||
public function __construct(private ?IamV2Client $client = null) { $this->client ??= new IamV2Client(); }
|
||||
public function binding(int $id, bool $fresh = false): array
|
||||
{
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$fresh && $row && $row['checked_at'] > time() - 30) {
|
||||
$cached = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
$cached['checked_at'] = (int) $row['checked_at'];
|
||||
return $cached;
|
||||
}
|
||||
$result = $this->client->call('GET', '/bindings/by-external/' . $id);
|
||||
if (($result['binding']['externalAccountId'] ?? (string) $id) !== (string) $id) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ($result['binding'] ?? null) {
|
||||
$b = $result['binding']; $employee = $result['employee'] ?? [];
|
||||
if (($b['applicationId'] ?? '') !== (string) Config::get('iam.application_id', 'zyt')
|
||||
|| !is_int($b['version'] ?? null) || $b['version'] < 1
|
||||
|| !in_array($b['state'] ?? '', ['verified','revoked','pending','conflict'], true)
|
||||
|| empty($employee['id']) || ($b['employeeId'] ?? '') !== $employee['id'] || empty($employee['oidcSubject'])) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
}
|
||||
$state = $result['binding']['state'] ?? 'unlinked';
|
||||
$version = (int) ($result['binding']['version'] ?? 0);
|
||||
if ($row && $row['state'] === 'revoked' && $state === 'verified' && $version <= (int) $row['version']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($row && (int) $row['version'] > $version) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$values = ['admin_id' => $id, 'employee_id' => $result['employee']['id'] ?? '', 'subject' => $result['employee']['oidcSubject'] ?? '',
|
||||
'state' => $state, 'version' => $version, 'payload' => json_encode($result, JSON_THROW_ON_ERROR), 'checked_at' => time()];
|
||||
if ($row) { Db::name('iam_v2_binding')->where('admin_id', $id)->update($values); }
|
||||
else { Db::name('iam_v2_binding')->insert($values); }
|
||||
$changed = $row && $row['state'] === 'verified' && (($row['employee_id'] ?? '') !== ($values['employee_id'] ?? '') || (int) $row['version'] !== $version);
|
||||
if ($state === 'revoked' || (($result['employee'] ?? null) && (($result['employee']['status'] ?? '') !== 'active' || !($result['access']['allowed'] ?? false)))) {
|
||||
self::revoke($id);
|
||||
} elseif ($changed) {
|
||||
IamV2Source::revokeGeneration($id, (int) $row['version'], (string) $row['employee_id']);
|
||||
}
|
||||
$result['checked_at'] = $values['checked_at'];
|
||||
return $result;
|
||||
}
|
||||
public static function revoke(int $id): void
|
||||
{
|
||||
IamV2Source::revokeAdmin($id);
|
||||
foreach (Db::name('admin_session')->where('admin_id', $id)->column('token') as $token) { AdminLogic::expireToken($token); }
|
||||
}
|
||||
public function assertLinked(int $id): array
|
||||
{
|
||||
$b = $this->binding($id, true);
|
||||
if (($b['binding']['state'] ?? '') !== 'verified') { throw new RuntimeException('NOT_LINKED'); }
|
||||
if (($b['employee']['status'] ?? '') !== 'active' || !($b['access']['allowed'] ?? false)) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return $b;
|
||||
}
|
||||
public function accounts(array $query, int $actor): array
|
||||
{
|
||||
$page = max(1, (int) ($query['page'] ?? 1)); $size = min(20, max(1, (int) ($query['pageSize'] ?? 20)));
|
||||
$db = Db::name('admin')->whereNull('delete_time');
|
||||
$visible = IamV2Source::visibleIds($actor);
|
||||
if ($visible !== null) { $db->whereIn('id', $visible ?: [0]); }
|
||||
if (($query['q'] ?? '') !== '') { $db->whereLike('account|name', '%' . mb_substr((string) $query['q'], 0, 64) . '%'); }
|
||||
if (($query['state'] ?? '') !== '') {
|
||||
$ids = Db::name('iam_v2_binding')->where('state', (string) $query['state'])->column('admin_id');
|
||||
if ($query['state'] === 'unknown') { $db->whereNotIn('id', Db::name('iam_v2_binding')->column('admin_id')); }
|
||||
else { $db->whereIn('id', $ids ?: [0]); }
|
||||
}
|
||||
$total = (clone $db)->count();
|
||||
$items = $db->field('id,account,name,disable,root')->page($page, $size)->select()->toArray();
|
||||
// Resolve department labels only for already-scoped rows, never broaden the account query.
|
||||
$departmentNames = [];
|
||||
if ($items !== []) {
|
||||
$links = Db::name('admin_dept')->whereIn('admin_id', array_column($items, 'id'))
|
||||
->field('admin_id,dept_id')->order('dept_id', 'asc')->select()->toArray();
|
||||
$ids = array_values(array_unique(array_column($links, 'dept_id')));
|
||||
$labels = $ids ? Db::name('dept')->whereIn('id', $ids)->whereNull('delete_time')->column('name', 'id') : [];
|
||||
foreach ($links as $link) {
|
||||
if (isset($labels[$link['dept_id']])) { $departmentNames[$link['admin_id']][$link['dept_id']] = (string) $labels[$link['dept_id']]; }
|
||||
}
|
||||
}
|
||||
foreach ($items as &$r) {
|
||||
$r['dept_names'] = array_values($departmentNames[$r['id']] ?? []);
|
||||
try { $r['iam'] = $this->binding((int) $r['id']); $r['iam']['state'] = $r['iam']['binding']['state'] ?? 'unlinked'; }
|
||||
catch (\Throwable $e) {
|
||||
$last = Db::name('iam_v2_binding')->where('admin_id', $r['id'])->value('checked_at');
|
||||
$reason = in_array($e->getMessage(), ['BINDING_CONFLICT','ACCOUNT_MISMATCH','ACCOUNT_DISABLED','NOT_AUTHORIZED'], true)
|
||||
? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
$r['iam'] = ['state' => 'unknown', 'error' => $reason, 'access' => ['allowed' => null, 'reason' => $reason],
|
||||
'checked_at' => (int) $last > 0 ? (int) $last : null];
|
||||
}
|
||||
}
|
||||
unset($r);
|
||||
return ['items' => $items, 'total' => $total];
|
||||
}
|
||||
public static function input(array $input): array
|
||||
{
|
||||
$kind = (string) ($input['kind'] ?? '');
|
||||
if (!in_array($kind, ['bind', 'create_and_bind', 'unbind', 'rebind', 'reconcile'], true)) { throw new RuntimeException('INVALID_OPERATION'); }
|
||||
$id = (int) ($input['user_id'] ?? 0);
|
||||
if ($id < 1 || strlen(trim((string) ($input['reason'] ?? ''))) < 3) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out = ['kind' => $kind, 'externalAccountId' => (string) $id, 'reason' => mb_strcut(trim($input['reason']), 0, 500, 'UTF-8')];
|
||||
if (isset($input['employee_id'])) { $out['employeeId'] = (string) $input['employee_id']; }
|
||||
if (isset($input['expected_version'])) { $out['expectedVersion'] = (int) $input['expected_version']; }
|
||||
if (in_array($kind, ['unbind','rebind'], true) && !isset($out['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($kind === 'create_and_bind') {
|
||||
$n = $input['new_employee'] ?? [];
|
||||
$out['newEmployee'] = ['username' => (string) ($n['username'] ?? ''), 'displayName' => (string) ($n['display_name'] ?? '')];
|
||||
if (!preg_match('/^[A-Za-z0-9_.@-]{3,64}$/D', $out['newEmployee']['username']) || trim($out['newEmployee']['displayName']) === '') { throw new RuntimeException('INVALID_INPUT'); }
|
||||
if (!empty($n['email'])) {
|
||||
if (!filter_var($n['email'], FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out['newEmployee']['email'] = $n['email'];
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
public static function cap(string $kind): string { return ['create_and_bind' => 'create', 'reconcile' => 'bind'][$kind] ?? $kind; }
|
||||
public function operation(array $session, array $input, string $requestId): array
|
||||
{
|
||||
$body = self::input($input); $target = (int) $body['externalAccountId']; $cap = self::cap($body['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$target], true, true);
|
||||
$current = $this->binding($target, true); $caps = ['iam:' . $cap];
|
||||
if ($body['kind'] === 'create_and_bind' && ($current['binding']['state'] ?? '') === 'revoked') {
|
||||
if (!isset($body['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$target], true, true); $caps[] = 'iam:rebind';
|
||||
}
|
||||
$body['proof'] = IamV2Source::proof($session, 'management', [$target], $caps, null, ['protectedReviewEligible' => IamV2Source::reviewOperator((int) $session['admin_id'])]);
|
||||
$op = $this->client->call('POST', '/operations', $body, $requestId);
|
||||
$op = $this->reviewLink($op);
|
||||
$this->remember('operation', (string) $op['id'], $session, [$target], $caps);
|
||||
if (($op['status'] ?? '') === 'succeeded') { $this->binding($target, true); }
|
||||
return $op;
|
||||
}
|
||||
private function reviewLink(array $operation): array
|
||||
{
|
||||
if (!isset($operation['reviewUrl'])) { return $operation; }
|
||||
$origin = IamV2Client::origin((string) Config::get('iam.portal_url'));
|
||||
$parts = parse_url((string) $operation['reviewUrl']);
|
||||
$fixed = parse_url($origin);
|
||||
if (!$parts || ($parts['scheme'] ?? '') !== 'https' || ($parts['host'] ?? '') !== $fixed['host']
|
||||
|| ($parts['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($parts['path'] ?? '') !== '/admin/iam/review'
|
||||
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($parts['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['request'] ?? null) !== ($operation['id'] ?? null)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $operation;
|
||||
}
|
||||
public function remember(string $kind, string $id, array $session, array $targets, array $caps = []): void
|
||||
{
|
||||
$key = hash('sha256', $kind . ':' . $id);
|
||||
$existing = Db::name('iam_v2_resource')->where('resource_key', $key)->find();
|
||||
if ($existing) { if ((int) $existing['actor_id'] !== (int) $session['admin_id']) { throw new RuntimeException('FORBIDDEN'); } return; }
|
||||
Db::name('iam_v2_resource')->insert(['resource_key' => $key, 'kind' => $kind, 'external_id' => $id, 'actor_id' => $session['admin_id'],
|
||||
'payload' => json_encode(['targets' => $targets, 'capabilities' => $caps]), 'created_at' => time()]);
|
||||
}
|
||||
public function owned(string $kind, string $id, array $session): array
|
||||
{
|
||||
$r = Db::name('iam_v2_resource')->where('resource_key', hash('sha256', $kind . ':' . $id))->where('actor_id', $session['admin_id'])->find();
|
||||
if (!$r) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$payload = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
IamV2Source::scope((int) $session['admin_id'], $payload['targets']);
|
||||
return $payload;
|
||||
}
|
||||
public function preflight(array $session, array $items): array
|
||||
{
|
||||
if (!$items || count($items) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
IamV2Source::authorize($session, 'batch'); $mapped = []; $targets = []; $caps = ['iam:batch']; $indexMap = []; $review = []; $itemCaps = [];
|
||||
foreach ($items as $index => $input) {
|
||||
try {
|
||||
$item = self::input($input); $id = (int) $item['externalAccountId']; $cap = self::cap($item['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$id]);
|
||||
$held = ['iam:' . $cap];
|
||||
if ($item['kind'] === 'create_and_bind' && (($this->binding($id, true)['binding']['state'] ?? '') === 'revoked')) {
|
||||
if (!isset($item['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$id]); $held[] = 'iam:rebind';
|
||||
}
|
||||
$indexMap[] = (int) $index; $mapped[] = $item; $targets[] = $id; $itemCaps[] = $held; $caps = array_merge($caps, $held);
|
||||
} catch (RuntimeException $e) {
|
||||
$review[] = ['index' => (int) $index, 'externalAccountId' => (string) ($input['user_id'] ?? ''),
|
||||
'status' => $e->getMessage() === 'PROTECTED_ACCOUNT_REVIEW_REQUIRED' ? 'review' : 'invalid', 'message' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
if (!$mapped) { return ['previewId' => null, 'items' => $review, 'expiresAt' => time()]; }
|
||||
$r = $this->client->call('POST', '/batch/preflight', ['items' => $mapped,
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, array_values(array_unique($caps)))]);
|
||||
$this->remember('preview', (string) $r['previewId'], $session, $targets, $caps);
|
||||
$resource = hash('sha256', 'preview:' . $r['previewId']);
|
||||
$ready = [];
|
||||
foreach ($r['items'] as &$item) {
|
||||
$centralIndex = (int) $item['index'];
|
||||
if (!array_key_exists($centralIndex, $indexMap)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$item['index'] = $indexMap[$centralIndex];
|
||||
if ($item['status'] === 'ready') { $ready[] = $item['index']; }
|
||||
}
|
||||
unset($item);
|
||||
Db::name('iam_v2_resource')->where('resource_key', $resource)->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'indexMap' => $indexMap, 'ready' => $ready, 'itemCaps' => $itemCaps])]);
|
||||
$r['items'] = array_merge($r['items'], $review);
|
||||
usort($r['items'], fn($a, $b) => $a['index'] <=> $b['index']); return $r;
|
||||
}
|
||||
public function batch(array $session, string $preview, array $indexes, string $key): array
|
||||
{
|
||||
$scope = $this->owned('preview', $preview, $session);
|
||||
$indexes = array_values(array_unique(array_map('intval', $indexes)));
|
||||
if (!$indexes || array_diff($indexes, $scope['ready'] ?? [])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$indexes = array_map(fn($i) => array_search($i, $scope['indexMap'], true), $indexes);
|
||||
$targets = array_map(fn($i) => $scope['targets'][$i], $indexes); $caps = ['iam:batch']; $itemCaps = [];
|
||||
foreach ($indexes as $i) { $itemCaps[$i] = $scope['itemCaps'][$i] ?? $scope['capabilities']; $caps = array_merge($caps, $itemCaps[$i]); }
|
||||
$caps = array_values(array_unique($caps));
|
||||
foreach ($caps as $cap) { IamV2Source::authorize($session, substr($cap, 4), $targets); }
|
||||
$r = $this->client->call('POST', '/batch', ['previewId' => $preview, 'indexes' => $indexes,
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, $caps)], $key);
|
||||
$this->remember('job', (string) $r['id'], $session, $targets, $caps);
|
||||
Db::name('iam_v2_resource')->where('resource_key', hash('sha256', 'job:' . $r['id']))->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'itemCaps' => $itemCaps, 'centralIndexes' => $indexes])]);
|
||||
return $r;
|
||||
}
|
||||
/** Public retry indexes are job.items positions, not original central preview indexes. */
|
||||
public static function retrySelection(array $job, array $positions = []): array
|
||||
{
|
||||
$items = $job['items'] ?? []; $central = $job['indexes'] ?? [];
|
||||
if ($positions === []) { $positions = array_keys($items); }
|
||||
$indexes = []; $targets = []; $caps = ['iam:batch'];
|
||||
foreach (array_unique($positions) as $position) {
|
||||
if (!is_int($position) || !isset($items[$position], $central[$position])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$item = $items[$position];
|
||||
if (!in_array($item['status'] ?? '', ['failed', 'pending'], true)) { continue; }
|
||||
$indexes[] = $central[$position]; $targets[] = (int) $item['externalAccountId']; $caps[] = 'iam:' . self::cap($item['kind']);
|
||||
}
|
||||
return ['indexes' => $indexes, 'targets' => $targets, 'capabilities' => array_values(array_unique($caps))];
|
||||
}
|
||||
public function result(array $session, string $kind, string $id, bool $retry = false, array $indexes = []): array
|
||||
{
|
||||
$scope = $this->owned($kind, $id, $session); IamV2Source::authorize($session, 'read', [], false);
|
||||
$path = ($kind === 'job' ? '/jobs/' : '/operations/') . rawurlencode($id);
|
||||
if ($retry) {
|
||||
$job = $this->client->call('GET', $path);
|
||||
// The saved mapping prevents the central endpoint changing this operation's target set.
|
||||
if (!isset($job['indexes'])) { $job['indexes'] = $scope['centralIndexes'] ?? []; }
|
||||
$selected = self::retrySelection($job, $indexes);
|
||||
if (!$selected['indexes']) { return $job; }
|
||||
if (array_diff($selected['targets'], array_map('intval', $scope['targets']))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
foreach ($selected['indexes'] as $i) { $selected['capabilities'] = array_merge($selected['capabilities'], $scope['itemCaps'][$i] ?? []); }
|
||||
$selected['capabilities'] = array_values(array_unique($selected['capabilities']));
|
||||
foreach ($selected['capabilities'] as $cap) { IamV2Source::authorize($session, substr($cap, 4), $selected['targets']); }
|
||||
$r = $this->client->call('POST', $path . '/retry', ['indexes' => $selected['indexes'],
|
||||
'proof' => IamV2Source::proof($session, 'management', $selected['targets'], $selected['capabilities'])]);
|
||||
$scope['targets'] = $selected['targets'];
|
||||
} else { $r = $this->client->call('GET', $path); }
|
||||
foreach ($scope['targets'] as $target) { $this->binding((int) $target, true); }
|
||||
return $kind === 'operation' ? $this->reviewLink($r) : $r;
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AuthLogic;
|
||||
use app\common\cache\AdminAccountSafeCache;
|
||||
|
||||
/** Browser source sessions are separate from legacy account/terminal shared business tokens. */
|
||||
final class IamV2Source
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_SESSION';
|
||||
public static function requirePurpose(string $purpose): void
|
||||
{
|
||||
$feature = in_array($purpose, ['management', 'self_link', 'password_setup'], true) ? 'management' : ($purpose === 'launch' ? 'launch' : null);
|
||||
if ($feature !== null && !IamV2Client::feature($feature)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
}
|
||||
public static function enroll(string $token, string $method, bool $cookie = true, ?int $authTime = null): array
|
||||
{
|
||||
if (!in_array($method, ['password', 'wecom', 'oidc', 'iam_launch'], true)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (in_array($method, ['oidc', 'iam_launch'], true) && $authTime !== null && ($authTime < 0 || $authTime > time() + 60)) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $legacy['admin_id']);
|
||||
$old = (string) ($_COOKIE[self::COOKIE] ?? '');
|
||||
if ($old !== '') { self::revokeSession($old); }
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $legacy['admin_id'])->where('state', 'verified')->find();
|
||||
$sid = bin2hex(random_bytes(32));
|
||||
$row = ['session_id' => $sid, 'admin_id' => (int) $legacy['admin_id'], 'business_session_id' => $legacy['id'],
|
||||
'token_hash' => hash('sha256', $token), 'account_stamp' => self::accountStamp($admin), 'auth_method' => $method, 'auth_time' => in_array($method, ['oidc', 'iam_launch'], true) ? max(0, $authTime ?? 0) : time(),
|
||||
'version' => 1, 'revoked' => 0, 'binding_version' => (int) ($binding['version'] ?? 0), 'employee_id' => $binding['employee_id'] ?? '', 'expires_at' => min((int) $legacy['expire_time'], time() + 43200)];
|
||||
Db::name('iam_v2_source_session')->insert($row);
|
||||
if ($cookie) {
|
||||
setcookie(self::COOKIE, $sid, ['expires' => $row['expires_at'], 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
$_COOKIE[self::COOKIE] = $sid;
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
private static function accountStamp(array $admin): string
|
||||
{
|
||||
return hash('sha256', json_encode([$admin['account'], $admin['password'], $admin['work_wechat_userid'] ?? '', (int) $admin['root']], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
public static function admin(int $id): array
|
||||
{
|
||||
$a = Db::name('admin')->where('id', $id)->find();
|
||||
if (!$a || (int) $a['disable'] !== 0 || !empty($a['delete_time'])) { throw new RuntimeException('ACCOUNT_DISABLED'); }
|
||||
return $a;
|
||||
}
|
||||
public static function current(string $token, bool $recent = false): array
|
||||
{
|
||||
$s = self::check((string) ($_COOKIE[self::COOKIE] ?? ''));
|
||||
if (!hash_equals($s['token_hash'], hash('sha256', $token))) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ($recent && $s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
return $s;
|
||||
}
|
||||
public static function check(string $id, ?int $version = null): array
|
||||
{
|
||||
$s = Db::name('iam_v2_source_session')->where('session_id', $id)->find();
|
||||
if (!$s || (int) $s['revoked'] !== 0 || $s['expires_at'] <= time() || ($version !== null && (int) $s['version'] !== $version)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $s['admin_id']);
|
||||
if (!hash_equals($s['account_stamp'], self::accountStamp($admin))) { self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if (!$legacy || $legacy['expire_time'] <= time() || (int) $legacy['admin_id'] !== (int) $s['admin_id'] || !hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if ((int) ($s['binding_version'] ?? 0) > 0) {
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $s['admin_id'])->find();
|
||||
if ($binding && ($binding['state'] === 'revoked' || (int) $binding['version'] > (int) $s['binding_version'] || $binding['employee_id'] !== $s['employee_id'])) {
|
||||
self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
/** Service callback: local-only live authorization, safe while central holds its state lock. */
|
||||
public static function liveStatus(string $id, int $version, string $purpose = '', array $targets = []): array
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
$s = self::check($id, $version);
|
||||
$out = ['active' => true, 'actorLocalId' => (string) $s['admin_id'], 'sessionId' => $s['session_id'], 'sessionVersion' => (int) $s['version'],
|
||||
'authMethod' => $s['auth_method'], 'authTime' => (int) $s['auth_time'], 'expiresAt' => (int) $s['expires_at']];
|
||||
if ($purpose !== 'management') { return $out + ['protectedAccount' => self::protectedAccount((int) $s['admin_id'])]; }
|
||||
if ($s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (!$targets || count($targets) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
foreach ($targets as $target) {
|
||||
if (!is_string($target) || !preg_match('/^[1-9][0-9]{0,9}$/D', $target)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
}
|
||||
$caps = self::capabilities((int) $s['admin_id']);
|
||||
if (!$caps) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::scope((int) $s['admin_id'], $targets);
|
||||
$protected = false;
|
||||
foreach ($targets as $target) { self::admin((int) $target); $protected = self::protectedAccount((int) $target) || $protected; }
|
||||
$eligible = count($targets) === 1 && self::reviewOperator((int) $s['admin_id']);
|
||||
if ($protected && !$eligible) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
return $out + ['purpose' => 'management', 'capabilities' => array_map(fn($c) => 'iam:' . $c, $caps),
|
||||
'targetLocalIds' => $targets, 'protectedAccount' => $protected, 'protectedReviewEligible' => $eligible];
|
||||
}
|
||||
public static function reauth(string $token, string $password): array
|
||||
{
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy || $password === '' || strlen($password) > 256) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$a = self::admin((int) $legacy['admin_id']);
|
||||
$limiter = new AdminAccountSafeCache();
|
||||
if (!$limiter->isSafe()) { throw new RuntimeException('RATE_LIMITED'); }
|
||||
// Deliberately does NOT invoke LoginValidate's local-debug password bypass.
|
||||
if (!hash_equals((string) $a['password'], create_password($password, Config::get('project.unique_identification')))) {
|
||||
$limiter->record(); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
$limiter->relieve(); return self::enroll($token, 'password');
|
||||
}
|
||||
public static function capabilities(int $id): array
|
||||
{
|
||||
$admin = self::admin($id);
|
||||
$all = ['read', 'bind', 'create', 'unbind', 'rebind', 'batch'];
|
||||
if ((int) $admin['root'] === 1) { return $all; }
|
||||
$perms = AuthLogic::getAuthByAdminId($id);
|
||||
return array_values(array_filter($all, fn($p) => in_array('iamV2/' . $p, $perms, true)));
|
||||
}
|
||||
public static function reviewOperator(int $id): bool
|
||||
{
|
||||
$a = self::admin($id);
|
||||
if ((int) $a['root'] === 1) { return true; }
|
||||
$roles = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
return $roles && Db::name('system_role')->whereIn('id', $roles)->whereIn('name', ['管理员', '系统管理员', '超级管理员'])->whereNull('delete_time')->count() > 0;
|
||||
}
|
||||
public static function protectedAccount(int $id): bool
|
||||
{
|
||||
return self::reviewOperator($id) || count(array_intersect(self::capabilities($id), ['bind','create','unbind','rebind','batch'])) > 0;
|
||||
}
|
||||
public static function visibleIds(int $id): ?array
|
||||
{
|
||||
$a = self::admin($id);
|
||||
$a['role_id'] = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
return \app\common\service\DataScope\DataScopeService::getVisibleAdminIds($id, $a);
|
||||
}
|
||||
public static function scope(int $actor, array $targets): void
|
||||
{
|
||||
$visible = self::visibleIds($actor);
|
||||
if ($visible !== null && array_diff(array_map('intval', $targets), $visible)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public static function authorize(array $session, string $capability, array $targets = [], bool $recent = true, bool $protectedReview = false): void
|
||||
{
|
||||
if (!in_array($capability, self::capabilities((int) $session['admin_id']), true)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
if ($recent && $session['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
self::scope((int) $session['admin_id'], $targets);
|
||||
foreach ($targets as $id) {
|
||||
$target = self::admin((int) $id);
|
||||
// Single-target high-privilege requests may reach central review, never bypass it.
|
||||
if (self::protectedAccount((int) $id) && !($protectedReview && count($targets) === 1 && self::reviewOperator((int) $session['admin_id']))) {
|
||||
throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
}
|
||||
}
|
||||
}
|
||||
public static function proof(array $session, string $purpose, array $targets = [], array $capabilities = [], ?string $transaction = null, array $extra = []): string
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
self::check($session['session_id'], (int) $session['version']);
|
||||
$secret = bin2hex(random_bytes(32));
|
||||
$payload = ['applicationId' => (string) Config::get('iam.application_id', 'zyt'), 'actorLocalId' => (string) $session['admin_id'],
|
||||
'sessionId' => $session['session_id'], 'sessionVersion' => (int) $session['version'], 'authMethod' => $session['auth_method'],
|
||||
'authTime' => (int) $session['auth_time'], 'expiresAt' => time() + 60, 'capabilities' => $capabilities,
|
||||
'targetLocalIds' => array_map('strval', $targets), 'protectedAccount' => count(array_filter($targets, fn($id) => self::protectedAccount((int) $id))) > 0, 'transactionId' => $transaction];
|
||||
$payload += array_intersect_key($extra, array_flip(['oidcNonce', 'state', 'protectedReviewEligible']));
|
||||
Db::name('iam_v2_proof')->insert(['proof_hash' => hash('sha256', $secret), 'purpose' => $purpose, 'session_id' => $session['session_id'],
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + 60, 'consumed' => 0]);
|
||||
return $secret;
|
||||
}
|
||||
public static function introspect(string $proof, string $purpose, ?string $transaction = null): array
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
// The central Go attestor serializes an absent transaction as an empty string.
|
||||
$transaction = $transaction === '' ? null : $transaction;
|
||||
return Db::transaction(function () use ($proof, $purpose, $transaction) {
|
||||
$hash = hash('sha256', $proof);
|
||||
$r = Db::name('iam_v2_proof')->where('proof_hash', $hash)->lock(true)->find();
|
||||
if (!$r || $r['purpose'] !== $purpose || $r['expires_at'] <= time() || (int) $r['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['transactionId'] ?? null) !== $transaction) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$session = self::check($p['sessionId'], (int) $p['sessionVersion']);
|
||||
$p['protectedReviewEligible'] = ($p['protectedReviewEligible'] ?? false) === true
|
||||
&& count($p['targetLocalIds']) === 1 && self::reviewOperator((int) $session['admin_id']);
|
||||
foreach ($p['capabilities'] as $cap) {
|
||||
if (!str_starts_with($cap, 'iam:')) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::authorize($session, substr($cap, 4), $p['targetLocalIds'], true, ($p['protectedReviewEligible'] ?? false) === true && count($p['targetLocalIds']) === 1);
|
||||
}
|
||||
// Target protection can change during the proof's short lifetime. Recompute it.
|
||||
$p['protectedAccount'] = count(array_filter($p['targetLocalIds'], fn($id) => self::protectedAccount((int) $id))) > 0;
|
||||
if (Db::name('iam_v2_proof')->where('proof_hash', $hash)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return ['active' => true] + $p;
|
||||
});
|
||||
}
|
||||
public static function revokeSession(string $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('session_id', $id)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
public static function revokeGeneration(int $id, int $upper, ?string $employeeId = null): void
|
||||
{
|
||||
$query = Db::name('iam_v2_source_session')->where('admin_id', $id)->where('binding_version', '<=', $upper);
|
||||
if ($employeeId !== null) { $query->where(function ($q) use ($employeeId) { $q->where('employee_id', $employeeId)->whereOr('binding_version', 0); }); }
|
||||
$sessions = $query->select()->toArray();
|
||||
foreach ($sessions as $s) { self::revokeSession($s['session_id']); }
|
||||
foreach ($sessions as $s) {
|
||||
$newer = Db::name('iam_v2_source_session')->where('token_hash', $s['token_hash'])->where('revoked', 0)->where('expires_at', '>', time())->find();
|
||||
if ($newer) { continue; }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if ($legacy && hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { \app\adminapi\logic\auth\AdminLogic::expireToken($legacy['token']); }
|
||||
}
|
||||
}
|
||||
public static function revokeAdmin(int $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('admin_id', $id)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\adminapi\service\iam\{IamAccountProvisioner, IamOidcClient};
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\service\FileService;
|
||||
|
||||
/** ZYT target accepts only the person's own IAM admin/portal source, never ERP. */
|
||||
final class IamV2Target
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_TARGET';
|
||||
private array $settings;
|
||||
public function __construct(private ?IamV2Client $client = null, private $resolve = null, private $login = null)
|
||||
{
|
||||
$this->settings = (array) Config::get('iam');
|
||||
if (!IamV2Client::feature('launch', $this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$this->client ??= new IamV2Client();
|
||||
$this->resolve ??= fn(array $result) => $this->resolveAdmin($result);
|
||||
$this->login ??= function (int $id, array $authentication): array {
|
||||
$authTime = self::authTime($authentication['authTime'] ?? null);
|
||||
$result = $this->loginVerifiedAdmin($id);
|
||||
IamV2Source::enroll($result['token'], 'iam_launch', true, $authTime);
|
||||
return $result;
|
||||
};
|
||||
}
|
||||
/** Only exchange's verified, one-time IAM ticket may reach this session issuer. */
|
||||
private function loginVerifiedAdmin(int $id): array
|
||||
{
|
||||
return Db::transaction(static function () use ($id): array {
|
||||
$admin = Admin::where('id', $id)->lock(true)->findOrEmpty();
|
||||
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || !empty($admin['delete_time'])) {
|
||||
throw new RuntimeException('ACCOUNT_DISABLED');
|
||||
}
|
||||
$admin->login_time = time();
|
||||
$admin->login_ip = request()->ip();
|
||||
$admin->save();
|
||||
$adminInfo = AdminTokenService::setToken($admin->id, AdminTerminalEnum::PC, $admin->multipoint_login);
|
||||
if (!$adminInfo || empty($adminInfo['token'])) { throw new RuntimeException('ACCOUNT_DISABLED'); }
|
||||
$avatar = $admin->avatar ?: Config::get('project.default_image.admin_avatar');
|
||||
return [
|
||||
'name' => $adminInfo['name'],
|
||||
'avatar' => FileService::getFileUrl($avatar),
|
||||
'role_name' => $adminInfo['role_name'],
|
||||
'token' => $adminInfo['token'],
|
||||
'is_paw' => $admin->is_paw ?? 1,
|
||||
'need_bind_work_wechat' => LoginLogic::adminMustBindWorkWechat([
|
||||
'root' => (int) ($admin->root ?? 0),
|
||||
'work_wechat_userid' => (string) ($admin->work_wechat_userid ?? ''),
|
||||
]),
|
||||
];
|
||||
});
|
||||
}
|
||||
public static function authTime($value): int
|
||||
{
|
||||
$time = is_int($value) ? $value : (is_string($value) ? strtotime($value) : false);
|
||||
if (!$time || $time < 0 || $time > time() + 60) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
return $time;
|
||||
}
|
||||
private function registered(string $source): string
|
||||
{
|
||||
$sources = $this->settings['v2_sources'] ?? [];
|
||||
if (!in_array($source, ['iam-admin', 'iam-portal'], true) || !is_array($sources) || !isset($sources[$source])) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return IamV2Client::https((string) $sources[$source]);
|
||||
}
|
||||
public static function existing(string $token, string $sourceSession = ''): ?int
|
||||
{
|
||||
$id = null;
|
||||
if ($token !== '') {
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
IamV2Source::admin((int) $legacy['admin_id']); $id = (int) $legacy['admin_id'];
|
||||
}
|
||||
if ($sourceSession !== '') {
|
||||
try { $session = IamV2Source::check($sourceSession); } catch (RuntimeException $e) { $session = null; }
|
||||
if ($session) {
|
||||
if ($id !== null && $id !== (int) $session['admin_id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) $session['admin_id'];
|
||||
}
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
public function prepare(string $source, string $intent, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$registered = $this->registered($source);
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $intent)) { throw new RuntimeException('INVALID_REQUEST'); }
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
$browser = bin2hex(random_bytes(32)); $state = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
$tx = $this->client->call('POST', '/launch-transactions', ['sourceApplicationId' => $source, 'stateHash' => hash('sha256', $state),
|
||||
'codeChallenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=')]);
|
||||
$id = $tx['transactionId'] ?? '';
|
||||
if (!is_string($id) || !preg_match('/^[A-Za-z0-9_-]{1,128}$/D', $id)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$actual = parse_url((string) ($tx['sourceContinueUrl'] ?? '')); $fixed = parse_url($registered);
|
||||
if (!$actual || ($actual['scheme'] ?? '') !== $fixed['scheme'] || ($actual['host'] ?? '') !== $fixed['host']
|
||||
|| ($actual['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($actual['path'] ?? '') !== ($fixed['path'] ?? '')
|
||||
|| isset($actual['user']) || isset($actual['pass']) || isset($actual['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($actual['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['transaction_id'] ?? null) !== $id) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
IamV2Flow::put('target_launch', $id, ['sessionId' => hash('sha256', $browser), 'source' => $source, 'verifier' => $verifier,
|
||||
'stateHash' => hash('sha256', $state), 'expectedAdminId' => $existing]);
|
||||
return ['url' => $registered . '?' . http_build_query(['transaction_id' => $id, 'intent' => $intent], '', '&', PHP_QUERY_RFC3986), 'browser' => $browser];
|
||||
}
|
||||
public function callback(string $transaction, string $grant, string $browser, string $origin): array
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{64}$/D', $browser) || !preg_match('/^[A-Za-z0-9_-]{43}$/D', $grant)) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$flow = IamV2Flow::peek('target_launch', $transaction, hash('sha256', $browser));
|
||||
$source = parse_url($this->registered($flow['source']));
|
||||
$expectedOrigin = $source['scheme'] . '://' . $source['host'] . (isset($source['port']) ? ':' . $source['port'] : '');
|
||||
if ($origin !== $expectedOrigin) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
IamV2Flow::take('target_launch', $transaction, hash('sha256', $browser));
|
||||
$result = $this->client->call('POST', '/launch-grants/exchange', ['transactionId' => $transaction, 'grant' => $grant, 'codeVerifier' => $flow['verifier']]);
|
||||
$employee = $result['employee'] ?? []; $auth = $result['authentication'] ?? [];
|
||||
if (($employee['status'] ?? '') !== 'active' || !is_string($employee['oidcSubject'] ?? null) || $employee['oidcSubject'] === ''
|
||||
|| empty($employee['id']) || !($result['access']['allowed'] ?? false) || ($auth['sourceApplicationId'] ?? '') !== $flow['source']
|
||||
|| empty($auth['sessionId']) || !is_string($auth['authMethod'] ?? null) || $auth['authMethod'] === '' || !is_int($auth['sessionVersion'] ?? null) || $auth['sessionVersion'] < 1) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
self::authTime($auth['authTime'] ?? null);
|
||||
if ($flow['expectedAdminId'] !== null && (string) ($result['binding']['externalAccountId'] ?? '') !== (string) $flow['expectedAdminId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) ($this->resolve)($result);
|
||||
if ($id < 1 || ($flow['expectedAdminId'] !== null && $id !== (int) $flow['expectedAdminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
IamV2Source::admin($id);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $employee['oidcSubject']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('target_ticket', $ticket, ['sessionId' => hash('sha256', $browser), 'adminId' => $id, 'expectedAdminId' => $flow['expectedAdminId'],
|
||||
'employeeId' => $employee['id'], 'bindingVersion' => (int) $current['binding']['version'], 'source' => $flow['source'], 'authentication' => $auth], 60);
|
||||
return ['ticket' => $ticket, 'source' => $flow['source']];
|
||||
}
|
||||
private function resolveAdmin(array $result): int
|
||||
{
|
||||
$employee = $result['employee']; $subject = $employee['oidcSubject'];
|
||||
$client = new IamOidcClient($this->settings); $context = $client->provisioning($subject);
|
||||
if (($context['employee']['id'] ?? '') !== $employee['id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$binding = $result['binding'] ?? null;
|
||||
if ($binding && (($binding['applicationId'] ?? '') !== 'zyt' || ($binding['state'] ?? '') !== 'verified'
|
||||
|| (string) ($context['externalAccountId'] ?? '') !== (string) $binding['externalAccountId']
|
||||
|| (int) ($context['bindingVersion'] ?? 0) !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if (!$binding && ($context['externalAccountId'] ?? '') !== '') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$id = (new IamAccountProvisioner())->resolve($client, $this->settings, $subject);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $subject
|
||||
|| ($binding && (int) $current['binding']['version'] !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
return $id;
|
||||
}
|
||||
public function exchange(string $ticket, string $browser, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$flow = IamV2Flow::peek('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
if (($flow['expectedAdminId'] !== null && $existing !== (int) $flow['expectedAdminId']) || ($existing !== null && $existing !== (int) $flow['adminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$current = (new IamV2Manager($this->client))->assertLinked((int) $flow['adminId']);
|
||||
if (($current['employee']['id'] ?? '') !== $flow['employeeId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ((int) $current['binding']['version'] !== (int) $flow['bindingVersion']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Flow::take('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$result = ($this->login)((int) $flow['adminId'], $flow['authentication']);
|
||||
$hash = hash('sha256', $result['token']);
|
||||
$values = ['token_hash' => $hash, 'admin_id' => (int) $flow['adminId'], 'employee_id' => $flow['employeeId'],
|
||||
'source_application_id' => $flow['source'], 'source_binding_version' => (int) ($flow['authentication']['sourceBindingVersion'] ?? 0), 'checked_at' => time()];
|
||||
$old = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if ($old) { Db::name('iam_v2_target_session')->where('token_hash', $hash)->update($values); }
|
||||
else { Db::name('iam_v2_target_session')->insert($values); }
|
||||
return $result;
|
||||
}
|
||||
public static function compensate(string $token): void
|
||||
{
|
||||
$hash = hash('sha256', $token); $row = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if (!$row || $row['checked_at'] > time() - 30) { return; }
|
||||
$query = http_build_query(['employeeId' => $row['employee_id'], 'sourceApplicationId' => $row['source_application_id'],
|
||||
'sourceBindingVersion' => (int) $row['source_binding_version']], '', '&', PHP_QUERY_RFC3986);
|
||||
$check = (new IamV2Client())->call('GET', '/launch-authorizations/check?' . $query);
|
||||
if (!($check['allowed'] ?? false)) {
|
||||
Db::name('iam_v2_source_session')->where('token_hash', $hash)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
AdminLogic::expireToken($token); throw new RuntimeException('NOT_AUTHORIZED');
|
||||
}
|
||||
Db::name('iam_v2_target_session')->where('token_hash', $hash)->update(['checked_at' => time()]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user