This commit is contained in:
gr
2026-11-11 13:53:14 +08:00
parent 85ffda8fd0
commit fc347bf9a6
490 changed files with 70862 additions and 386 deletions
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace app\service\shared;
use app\exception\ApiError;
use app\service\Input;
use app\service\LoginLimiter;
use app\service\Settings;
use app\service\group\GroupService;
use app\service\group\KefuClient;
final class SharedIdentityService
{
private SourceApiClient $source;
private SessionStore $sessions;
public function __construct(?SourceApiClient $source = null, ?SessionStore $sessions = null, ?callable $clock = null)
{
$this->source = $source ?? new SourceApiClient();
$this->sessions = $sessions ?? new SessionStore(null, $clock);
}
public static function mode(): string
{
$mode = Settings::get('IAM_DATA_MODE', 'standalone');
if (!in_array($mode, ['standalone', 'shared'], true)) { throw new ApiError(503, '数据模式配置无效'); }
return $mode;
}
public static function sourceLoginUrl(): string
{
$url = Settings::get('IAM_SOURCE_LOGIN_URL');
if ($url === '') { return ''; }
$parts = parse_url($url);
return $parts && in_array($parts['scheme'] ?? '', ['http', 'https'], true) && !empty($parts['host'])
&& !isset($parts['user']) && !isset($parts['pass']) && !preg_match('/[\x00-\x20\x7f]/', $url) ? $url : '';
}
public function dispatch(string $operation, string $authorization = '', array $data = [], array $query = [], ?int $companyId = null,
string $ip = 'unknown'): array
{
if ($operation === 'login') { return $this->login($data); }
if ($operation === 'group.kefu.login') { return $this->kefuPasswordLogin($data, $query, $ip); }
if ($operation === 'group.sso.exchange') {
return (new GroupService($this->source, $this->sessions))->exchange($data, $this->profile(...));
}
if (!preg_match('/^Bearer ([a-f0-9]{64})$/D', $authorization, $match)) { throw new ApiError(401, '请先登录'); }
$token = $match[1];
$session = $this->sessions->resolve($token, $this->source->sourceKey());
try {
$profile = $this->profile($session['source_token']);
if ($profile['id'] !== (int) $session['admin_id']) { throw new ApiError(401, '登录已失效,请重新登录'); }
if ($operation === 'myself') {
return $profile;
}
if ($operation === 'logout') {
try { $this->source->request('POST', 'identity.session/logout', ['all' => 0], $session['source_token']); }
finally { $this->sessions->revoke($token); }
return [];
}
if ($operation === 'password') {
Input::only($data, ['old_password', 'password', 'password_confirm']);
$password = self::password($data['password'] ?? null);
if ($password !== ($data['password_confirm'] ?? null)) { throw new ApiError(422, '两次密码不一致'); }
$old = $data['old_password'] ?? '';
if (!is_string($old) || strlen($old) > 4096 || str_contains($old, "\0") || (!$profile['requires_password_change'] && $old === '')) {
throw new ApiError(422, '请填写当前密码');
}
$this->source->request('POST', 'identity.session/password', ['old_password' => $old,
'password' => $password, 'password_confirm' => $password], $session['source_token']);
$this->sessions->revokeAll($this->source->sourceKey(), $profile['id']);
return [];
}
if ($profile['requires_password_change']) { throw new ApiError(403, '请先修改首次登录密码'); }
if ($profile['requires_wecom_binding']) { throw new ApiError(403, '请先到原后台完成企业微信绑定'); }
$group = GroupService::enabled() ? new GroupService($this->source, $this->sessions) : null;
if (str_starts_with($operation, 'group.')) {
if (!$group) { throw new ApiError(503, '集团身份中心尚未启用'); }
return $group->dispatch($operation, $profile, $session, $token, $data, $query);
}
if ($group && $companyId !== null && $companyId > 1
&& preg_match('/^(dept|menu)\.(lists|add|edit|delete)$/D', $operation)) {
return $group->dispatchStructure($operation, $profile, $companyId, $data, $query);
}
if (!$group && $companyId !== null && $companyId !== 1) {
throw new ApiError(409, '集团公司结构尚未启用');
}
// 用户与角色是全局目录;公司选择仅决定部门、菜单结构的数据归属。
if ($group && !($operation === 'options' || preg_match('/^(admin|role)\./D', $operation))) {
$group->requireDirectory($profile, $companyId);
}
$result = (new SharedRecordsService($this->source, $session['source_token'], $profile, $group))->dispatch($operation, $data, $query);
return $group ? $group->decorateRecords($operation, $result) : $result;
} catch (ApiError $error) {
if ($error->status === 401) { $this->sessions->revoke($token); }
throw $error;
} finally {
if ($operation === 'logout') { $this->sessions->revoke($token); }
}
}
private function login(array $data): array
{
Input::only($data, ['account', 'password']);
$account = Input::text($data['account'] ?? null, '账号', 1, 32);
$password = $data['password'] ?? null;
if (!is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")) {
throw new ApiError(401, '账号或密码错误');
}
$result = $this->source->request('POST', 'identity.session/login', ['account' => $account, 'password' => $password,
'terminal' => GroupService::enabled() ? 11 : 1]);
$sourceToken = $result['token'] ?? null;
if (!is_string($sourceToken) || $sourceToken === '' || strlen($sourceToken) > 2048 || preg_match('/[\x00-\x20\x7f]/', $sourceToken)) {
throw new ApiError(502, '共享数据源响应异常');
}
$profile = $this->profile($sourceToken);
$ttl = max(300, min(604800, (int) Settings::get('IAM_SESSION_TTL', '28800')));
$token = $this->sessions->create($this->source->sourceKey(), $sourceToken, $profile['id'], $ttl);
return ['token' => $token, 'data_mode' => 'shared'];
}
/** Password proof never creates either a source session or a bridge session. */
private function kefuPasswordLogin(array $data, array $query, string $ip): array
{
Input::only($data, ['client_id', 'account', 'password']);
Input::only($query, []);
if (($data['client_id'] ?? null) !== KefuClient::ID) { throw new ApiError(422, '应用未注册'); }
$account = Input::text($data['account'] ?? null, '账号', 1, 32);
$password = $data['password'] ?? null;
if (!is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")) {
throw new ApiError(401, '账号或密码错误');
}
$limiter = new LoginLimiter();
$result = (new GroupService($this->source, $this->sessions))->kefuPasswordLogin(function () use ($limiter, $ip, $account, $password): array {
$limiter->reserve($ip, strtolower($account));
// A regular login may reuse or rotate somebody else's source token. Do not use it here.
$result = $this->source->request('POST', 'identity.session/verify', ['account' => $account, 'password' => $password]);
$keys = array_keys($result); sort($keys);
$expected = ['account', 'disable', 'id', 'name', 'requires_password_change', 'requires_wecom_binding']; sort($expected);
if ($keys !== $expected || !is_int($result['id']) || $result['id'] < 1
|| !is_string($result['account']) || $result['account'] === '' || strlen($result['account']) > 128
|| !is_string($result['name']) || strlen($result['name']) > 256
|| preg_match('/[\x00-\x1f\x7f]/', $result['account'] . $result['name'])
|| !is_int($result['disable']) || !in_array($result['disable'], [0, 1], true)
|| !is_bool($result['requires_password_change']) || !is_bool($result['requires_wecom_binding'])) {
throw new ApiError(502, '共享数据源响应异常');
}
if ($result['disable'] !== 0) { throw new ApiError(401, '账号或密码错误,或账号已停用'); }
return $result;
});
$limiter->success($ip, strtolower($account));
return $result;
}
private function profile(string $token): array
{
$data = $this->source->request('GET', 'auth.admin/mySelf', [], $token);
if (!is_array($data['user'] ?? null) || !is_array($data['menu'] ?? null)) { throw new ApiError(502, '共享数据源响应异常'); }
$user = SourceMapper::user($data['user']);
if ($user['disable'] !== 0) { throw new ApiError(401, '账号已停用,请重新登录'); }
$permissions = SourceMapper::permissions($data['permissions'] ?? null);
$profile = $user + ['permissions' => $permissions, 'menus' => SourceMapper::navigation($data['menu'], $permissions),
'data_mode' => 'shared', 'source_login_url' => self::sourceLoginUrl(),
'requires_password_change' => (int) ($data['user']['is_paw'] ?? 1) === 0,
'requires_wecom_binding' => (bool) ($data['user']['need_bind_work_wechat'] ?? false)];
// 每次都以原系统的当前角色重新聚合,不能把登录时的授权快照永久缓存。
return GroupService::enabled() ? (new GroupService($this->source, $this->sessions))->enrich($profile) : $profile;
}
public static function password(mixed $value): string
{
if (!is_string($value) || strlen($value) < 6 || strlen($value) > 32 || str_contains($value, "\0")) {
throw new ApiError(422, '密码必须为6至32字节');
}
return $value;
}
}