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,20 @@
<?php
declare(strict_types=1);
use app\service\Settings;
use app\service\shared\SourceApiClient;
use app\service\group\GroupStore;
use app\service\group\KefuMenuCatalog;
require dirname(__DIR__) . '/vendor/autoload.php';
try {
(new think\App(dirname(__DIR__) . DIRECTORY_SEPARATOR))->initialize();
$options = getopt('', ['company-code:', 'actor-id:']);
$actor = filter_var($options['actor-id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if (!$actor || !in_array((string) $actor, array_map('trim', explode(',', Settings::get('IAM_GROUP_OWNER_IDS'))), true)) throw new RuntimeException('请指定已配置的集团管理员 actor-id');
$code = $options['company-code'] ?? Settings::get('IAM_KEFU_COMPANY_CODE');
if (!is_string($code) || !preg_match('/^[a-z][a-z0-9-]{1,47}$/D', $code)) throw new RuntimeException('请指定客服所属公司编码');
$catalog = json_decode(file_get_contents(dirname(__DIR__, 2) . '/integration/kefu-menu-catalog.json'), true, 64, JSON_THROW_ON_ERROR);
$store = new GroupStore((new SourceApiClient())->sourceKey());
echo json_encode((new KefuMenuCatalog($store))->import($catalog, $code, (int) $actor), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n";
} catch (Throwable $error) {
fwrite(STDERR, $error instanceof \app\exception\ApiError || get_class($error) === RuntimeException::class ? $error->getMessage() . "\n" : "客服目录导入失败,请检查配置和目录结构。\n"); exit(1);
}
+64
View File
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
use app\repository\Database;
use app\repository\IdentityRepository;
use app\service\Input;
use app\service\Settings;
$root = dirname(__DIR__);
if (!is_file($root . '/vendor/autoload.php')) {
fwrite(STDERR, "请先在此目录运行 composer install\n");
exit(1);
}
require $root . '/vendor/autoload.php';
$lock = null;
$database = null;
$mysqlLock = '';
try {
(new think\App($root . DIRECTORY_SEPARATOR))->initialize();
if (Settings::get('IAM_DATA_MODE', 'standalone') !== 'standalone') {
throw new RuntimeException('共享数据模式禁止初始化数据库;请使用原项目管理真实数据');
}
$arguments = getopt('', ['account:', 'password:', 'name:']);
$account = Input::account($arguments['account'] ?? 'admin');
$password = Input::password($arguments['password'] ?? Settings::get('IAM_ADMIN_PASSWORD'));
$name = Input::text($arguments['name'] ?? '管理员', '名称');
$database = new Database(true);
if ($database->driver === 'sqlite') {
$lock = fopen(Settings::sqlitePath() . '.init.lock', 'c');
if (!$lock || !flock($lock, LOCK_EX)) { throw new RuntimeException('无法取得初始化锁'); }
$tables = $database->all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
} else {
$mysqlLock = 'iam-init-' . sha1(Settings::get('IAM_DB_DATABASE'));
$result = $database->one('SELECT GET_LOCK(?,10) AS acquired', [$mysqlLock]);
if ((int) ($result['acquired'] ?? 0) !== 1) { throw new RuntimeException('无法取得初始化锁'); }
$tables = $database->all('SHOW TABLES');
}
if ($tables !== []) {
throw new RuntimeException('数据库非空,拒绝初始化;现有账号与密码未修改');
}
require __DIR__ . '/schema.php';
require __DIR__ . '/seed.php';
if ($database->driver === 'sqlite') {
$database->transaction(static function () use ($database, $account, $password, $name): void {
identitySchema($database);
identitySeed(new IdentityRepository($database), $account, $password, $name);
});
} else {
// MySQL DDL commits implicitly; all credentials were validated before creating any table.
identitySchema($database);
$database->transaction(static fn () => identitySeed(new IdentityRepository($database), $account, $password, $name));
}
fwrite(STDOUT, "独立数据库初始化完成:{$account}(密码未输出)\n");
} catch (Throwable $error) {
// Do not print PDO connection diagnostics, SQL parameters or credential values.
$message = $error instanceof app\exception\ApiError || $error instanceof RuntimeException && !$error instanceof PDOException
? $error->getMessage() : '初始化失败,请检查独立数据库及目录权限';
fwrite(STDERR, $message . "\n");
exit(1);
} finally {
if (is_resource($lock)) { flock($lock, LOCK_UN); fclose($lock); }
if ($database && $mysqlLock !== '') { $database->one('SELECT RELEASE_LOCK(?)', [$mysqlLock]); }
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
// 本地互通辅助入口:只加载原项目配置,不复制其中的数据库或第三方凭据。
$root = getenv('IAM_SOURCE_PROJECT_ROOT');
$root = is_string($root) ? realpath($root) : false;
$path = strtolower((string) parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH));
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$read = ['auth.admin/myself', 'auth.admin/lists', 'auth.admin/all', 'auth.admin/detail',
'auth.role/lists', 'auth.role/all', 'auth.role/detail', 'auth.menu/lists', 'auth.menu/all', 'auth.menu/detail',
'dept.dept/lists', 'dept.dept/all', 'dept.dept/detail'];
$write = ['identity.session/login', 'identity.session/verify', 'identity.session/password', 'identity.session/logout', 'identity.hospitalsso/issue', 'identity.hospitalsso/exchange'];
foreach (['auth.admin', 'auth.role', 'auth.menu', 'dept.dept'] as $controller) {
foreach (['add', 'edit', 'delete'] as $action) { $write[] = $controller . '/' . $action; }
}
$allowed = array_map(static fn ($route) => '/adminapi/' . $route, $method === 'GET' ? $read : ($method === 'POST' ? $write : []));
if (!in_array($path, $allowed, true) || array_key_exists('s', $_GET)) {
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
echo '{"code":0,"msg":"接口不存在","data":{}}';
exit;
}
if (!$root || !is_file($root . '/vendor/autoload.php') || !is_file($root . '/config/install.lock')) {
http_response_code(503);
header('Content-Type: application/json; charset=utf-8');
echo '{"code":0,"msg":"原项目服务尚未配置","data":{}}';
exit;
}
require $root . '/vendor/autoload.php';
// 多应用组件根据入口文件名选应用;保持原 index.php 语义,避免把本辅助器当成应用名。
$_SERVER['SCRIPT_FILENAME'] = $root . '/public/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['PHP_SELF'] = '/index.php';
$_SERVER['PATH_INFO'] = (string) parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
$application = new class($root . DIRECTORY_SEPARATOR) extends think\App {
public function loadEnv(string $envName = ''): void
{
parent::loadEnv($envName);
// 互通入口始终要求真实密码,不沿用原项目本地免密调试开关。
$this->env->set('APP_DEBUG', false);
$this->env->set('LOCAL_DEBUG_LOGIN_SKIP_PASSWORD', false);
}
};
$application->initialize();
// 即使原 Request 配置存在兼容路由,也固定到外层白名单核验过的真实地址。
$canonicalPath = str_replace('/identity.hospitalsso/', '/identity.hospitalSso/', $path);
$application->request->setPathinfo(ltrim($canonicalPath, '/'));
$http = $application->http;
$response = $http->run();
$response->send();
$http->end($response);
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
use app\repository\Database;
function identitySchema(Database $db): void
{
$id = $db->driver === 'sqlite' ? 'INTEGER PRIMARY KEY AUTOINCREMENT' : 'INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY';
$fk = $db->driver === 'sqlite' ? 'INTEGER' : 'INT UNSIGNED';
$suffix = $db->driver === 'mysql' ? ' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci' : '';
$tables = [
"CREATE TABLE admin (id {$id}, account VARCHAR(64) NOT NULL UNIQUE, name VARCHAR(64) NOT NULL,
password_hash VARCHAR(255) NOT NULL, is_root INTEGER NOT NULL DEFAULT 0, disable INTEGER NOT NULL DEFAULT 0,
create_time BIGINT NOT NULL, CHECK(is_root IN (0,1)), CHECK(disable IN (0,1)))",
"CREATE TABLE system_role (id {$id}, name VARCHAR(64) NOT NULL UNIQUE, `desc` VARCHAR(500) NOT NULL DEFAULT '',
sort INTEGER NOT NULL DEFAULT 0, disable INTEGER NOT NULL DEFAULT 0, CHECK(disable IN (0,1)))",
"CREATE TABLE dept (id {$id}, pid {$fk} NOT NULL DEFAULT 0, name VARCHAR(64) NOT NULL,
sort INTEGER NOT NULL DEFAULT 0, disable INTEGER NOT NULL DEFAULT 0, UNIQUE(pid,name), CHECK(disable IN (0,1)))",
"CREATE TABLE system_menu (id {$id}, pid {$fk} NOT NULL DEFAULT 0, type CHAR(1) NOT NULL, name VARCHAR(64) NOT NULL,
paths VARCHAR(200) NOT NULL DEFAULT '', component VARCHAR(64) NOT NULL DEFAULT '', perms VARCHAR(100) NOT NULL DEFAULT '',
icon VARCHAR(64) NOT NULL DEFAULT '', sort INTEGER NOT NULL DEFAULT 0, is_show INTEGER NOT NULL DEFAULT 1,
disable INTEGER NOT NULL DEFAULT 0, CHECK(type IN ('M','C','A')), CHECK(is_show IN (0,1)), CHECK(disable IN (0,1)))",
"CREATE TABLE admin_session (id {$id}, admin_id {$fk} NOT NULL, token_hash CHAR(64) NOT NULL UNIQUE,
expire_time BIGINT NOT NULL, create_time BIGINT NOT NULL, FOREIGN KEY(admin_id) REFERENCES admin(id) ON DELETE CASCADE)",
"CREATE TABLE admin_role (admin_id {$fk} NOT NULL, role_id {$fk} NOT NULL, PRIMARY KEY(admin_id,role_id),
FOREIGN KEY(admin_id) REFERENCES admin(id) ON DELETE CASCADE, FOREIGN KEY(role_id) REFERENCES system_role(id) ON DELETE RESTRICT)",
"CREATE TABLE admin_dept (admin_id {$fk} NOT NULL, dept_id {$fk} NOT NULL, PRIMARY KEY(admin_id,dept_id),
FOREIGN KEY(admin_id) REFERENCES admin(id) ON DELETE CASCADE, FOREIGN KEY(dept_id) REFERENCES dept(id) ON DELETE RESTRICT)",
"CREATE TABLE system_role_menu (role_id {$fk} NOT NULL, menu_id {$fk} NOT NULL, PRIMARY KEY(role_id,menu_id),
FOREIGN KEY(role_id) REFERENCES system_role(id) ON DELETE CASCADE, FOREIGN KEY(menu_id) REFERENCES system_menu(id) ON DELETE CASCADE)",
];
foreach ($tables as $sql) { $db->execute($sql . $suffix); }
foreach (['CREATE INDEX idx_session_admin ON admin_session(admin_id)', 'CREATE INDEX idx_session_expire ON admin_session(expire_time)',
'CREATE INDEX idx_menu_parent ON system_menu(pid)', 'CREATE INDEX idx_role_admin ON admin_role(role_id)',
'CREATE INDEX idx_dept_admin ON admin_dept(dept_id)', 'CREATE INDEX idx_menu_role ON system_role_menu(menu_id)'] as $sql) {
$db->execute($sql);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
use app\repository\IdentityRepository;
function identitySeed(IdentityRepository $repo, string $account, string $password, string $name): void
{
$admin = $repo->insert('admin', ['account' => $account, 'name' => $name, 'password_hash' => password_hash($password, PASSWORD_DEFAULT),
'is_root' => 1, 'disable' => 0, 'create_time' => time()]);
$department = $repo->insert('dept', ['pid' => 0, 'name' => '总部', 'sort' => 100, 'disable' => 0]);
$repo->insert('dept', ['pid' => $department, 'name' => '运营部', 'sort' => 90, 'disable' => 0]);
$repo->insert('dept', ['pid' => $department, 'name' => '技术部', 'sort' => 80, 'disable' => 0]);
$repo->replace('admin_dept', 'admin_id', $admin, 'dept_id', [$department]);
$all = [];
$read = [];
$menu = static function (array $data) use ($repo, &$all): int {
$id = $repo->insert('system_menu', $data + ['pid' => 0, 'paths' => '', 'component' => '', 'perms' => '', 'icon' => '', 'sort' => 0, 'is_show' => 1, 'disable' => 0]);
$all[] = $id;
return $id;
};
$read[] = $menu(['type' => 'C', 'name' => '首页', 'paths' => '/dashboard', 'component' => 'dashboard/index', 'sort' => 1000]);
$system = $menu(['type' => 'M', 'name' => '系统管理', 'paths' => '/system', 'sort' => 900]);
$read[] = $system;
foreach ([['admin', '用户管理', 'users'], ['role', '角色管理', 'roles'], ['menu', '菜单管理', 'menus'], ['dept', '部门管理', 'depts']] as $index => [$kind, $label, $path]) {
$page = $menu(['pid' => $system, 'type' => 'C', 'name' => $label, 'paths' => '/system/' . $path,
'component' => 'system/' . $path, 'perms' => 'auth.' . $kind . '/lists', 'sort' => 100 - $index]);
$read[] = $page;
foreach (['add' => '新增', 'edit' => '编辑', 'delete' => '删除'] as $action => $text) {
$menu(['pid' => $page, 'type' => 'A', 'name' => $text, 'perms' => 'auth.' . $kind . '/' . $action]);
}
}
$manager = $repo->insert('system_role', ['name' => '管理角色', 'desc' => '账号、角色、菜单、部门的完整管理权限', 'sort' => 100, 'disable' => 0]);
$reader = $repo->insert('system_role', ['name' => '只读角色', 'desc' => '仅能查看管理列表', 'sort' => 50, 'disable' => 0]);
$repo->replace('system_role_menu', 'role_id', $manager, 'menu_id', $all);
$repo->replace('system_role_menu', 'role_id', $reader, 'menu_id', $read);
$repo->replace('admin_role', 'admin_id', $admin, 'role_id', [$manager]);
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
use app\service\Settings;
use app\service\shared\SourceApiClient;
use app\service\group\GroupStore;
use app\service\group\KefuApplicationService;
require dirname(__DIR__) . '/vendor/autoload.php';
try {
(new think\App(dirname(__DIR__) . DIRECTORY_SEPARATOR))->initialize();
$options=getopt('', ['actor-id:']);
$actor=filter_var($options['actor-id']??null,FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);
if(!$actor||!in_array((string)$actor,array_map('trim',explode(',',Settings::get('IAM_GROUP_OWNER_IDS'))),true)){
throw new RuntimeException('请指定已配置的集团管理员 actor-id');
}
$source=new SourceApiClient();
$store=new GroupStore($source->sourceKey());
echo json_encode((new KefuApplicationService($store,$source))->sync(['client_id'=>'kefu'],(int)$actor),JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR)."\n";
}catch(Throwable $error){
fwrite(STDERR,$error instanceof \app\exception\ApiError||get_class($error)===RuntimeException::class?$error->getMessage()."\n":"客服目录同步失败,请检查只读接入配置。\n");exit(1);
}