pdo = new PDO('sqlite:' . $path, null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false]); chmod($path, 0600); $this->pdo->exec('PRAGMA foreign_keys=ON'); $this->pdo->exec('PRAGMA busy_timeout=5000'); $this->pdo->exec('CREATE TABLE IF NOT EXISTS group_meta (name TEXT PRIMARY KEY,value TEXT NOT NULL)'); $this->pdo->exec('CREATE TABLE IF NOT EXISTS company (id INTEGER PRIMARY KEY AUTOINCREMENT,code TEXT NOT NULL UNIQUE,name TEXT NOT NULL,parent_id INTEGER NOT NULL DEFAULT 0,disable INTEGER NOT NULL DEFAULT 0,create_time INTEGER NOT NULL,update_time INTEGER NOT NULL)'); $this->pdo->exec('CREATE TABLE IF NOT EXISTS subject (source_id INTEGER PRIMARY KEY,gid TEXT NOT NULL UNIQUE,create_time INTEGER NOT NULL)'); $this->pdo->exec('CREATE TABLE IF NOT EXISTS membership (company_id INTEGER NOT NULL REFERENCES company(id),source_id INTEGER NOT NULL REFERENCES subject(source_id),member_status INTEGER NOT NULL,can_login INTEGER NOT NULL,update_time INTEGER NOT NULL,PRIMARY KEY(company_id,source_id))'); $this->pdo->exec('CREATE TABLE IF NOT EXISTS authorization_code (code_hash TEXT PRIMARY KEY,session_ref TEXT NOT NULL,source_id INTEGER NOT NULL,company_id INTEGER NOT NULL,client_id TEXT NOT NULL,redirect_uri TEXT NOT NULL,challenge TEXT NOT NULL,expires INTEGER NOT NULL,used_at INTEGER)'); $this->pdo->exec('CREATE TABLE IF NOT EXISTS group_audit (id INTEGER PRIMARY KEY AUTOINCREMENT,actor_id INTEGER NOT NULL,action TEXT NOT NULL,company_id INTEGER NOT NULL,subject_id INTEGER NOT NULL,created INTEGER NOT NULL)'); // 公司自建结构与医院目录分开存储;kind 与 company_id 同时参与所有结构查询。 $this->pdo->exec("CREATE TABLE IF NOT EXISTS company_structure_node (id INTEGER PRIMARY KEY AUTOINCREMENT,company_id INTEGER NOT NULL REFERENCES company(id),kind TEXT NOT NULL CHECK(kind IN ('dept','menu')),pid INTEGER NOT NULL DEFAULT 0,name TEXT NOT NULL,sort INTEGER NOT NULL DEFAULT 0,disable INTEGER NOT NULL DEFAULT 0,type TEXT NOT NULL DEFAULT 'M',paths TEXT NOT NULL DEFAULT '',component TEXT NOT NULL DEFAULT '',perms TEXT NOT NULL DEFAULT '',icon TEXT NOT NULL DEFAULT '',is_show INTEGER NOT NULL DEFAULT 1,is_cache INTEGER NOT NULL DEFAULT 0,selected TEXT NOT NULL DEFAULT '',params TEXT NOT NULL DEFAULT '',create_time INTEGER NOT NULL,update_time INTEGER NOT NULL,CHECK(company_id>1),CHECK(pid>=0))"); $this->pdo->exec('CREATE INDEX IF NOT EXISTS company_structure_scope ON company_structure_node(company_id,kind,pid)'); // 源角色编号保持原值;只把集团菜单授权保存在本地,绝不写入医院角色菜单表。 $this->pdo->exec('CREATE TABLE IF NOT EXISTS role_native_menu (source_role_id INTEGER NOT NULL CHECK(source_role_id>0),menu_id INTEGER NOT NULL REFERENCES company_structure_node(id) ON DELETE CASCADE,update_time INTEGER NOT NULL,PRIMARY KEY(source_role_id,menu_id))'); $this->pdo->exec('CREATE INDEX IF NOT EXISTS role_native_menu_node ON role_native_menu(menu_id)'); $this->pdo->exec('CREATE TABLE IF NOT EXISTS application_catalog_node (client_id TEXT NOT NULL,company_id INTEGER NOT NULL REFERENCES company(id),external_key TEXT NOT NULL,node_id INTEGER NOT NULL REFERENCES company_structure_node(id) ON DELETE CASCADE,PRIMARY KEY(client_id,company_id,external_key))'); $this->pdo->exec("CREATE TABLE IF NOT EXISTS application_catalog_state (node_id INTEGER PRIMARY KEY REFERENCES company_structure_node(id) ON DELETE CASCADE,baseline TEXT NOT NULL,applied TEXT NOT NULL,overrides TEXT NOT NULL,local_disable INTEGER NOT NULL DEFAULT 0,source_disable INTEGER NOT NULL DEFAULT 0)"); $this->write(function () use ($sourceKey): void { $existing = $this->one('SELECT value FROM group_meta WHERE name=?', ['source_key']); if ($existing && !hash_equals($existing['value'], $sourceKey)) { throw new ApiError(503, '集团身份源已变化,请先执行受控迁移'); } $this->execute('INSERT OR IGNORE INTO group_meta(name,value) VALUES(?,?)', ['source_key', $sourceKey]); $this->execute('INSERT OR IGNORE INTO company(id,code,name,parent_id,disable,create_time,update_time) VALUES(1,?,?,0,0,?,?)', ['zyt-hospital', '甄养堂互联网医院', time(), time()]); }); } public function all(string $sql, array $params = []): array { $query = $this->pdo->prepare($sql); $query->execute($params); return $query->fetchAll(); } public function one(string $sql, array $params = []): ?array { return $this->all($sql, $params)[0] ?? null; } public function execute(string $sql, array $params = []): int { $query = $this->pdo->prepare($sql); $query->execute($params); return $query->rowCount(); } public function write(callable $work): mixed { $this->pdo->exec('BEGIN IMMEDIATE'); try { $result = $work(); $this->pdo->exec('COMMIT'); return $result; } catch (\Throwable $error) { $this->pdo->exec('ROLLBACK'); throw $error; } } public function identity(int $sourceId): array { if ($sourceId < 1) { throw new ApiError(401, '身份无效'); } return $this->write(function () use ($sourceId): array { $this->execute('INSERT OR IGNORE INTO subject(source_id,gid,create_time) VALUES(?,?,?)', [$sourceId, 'gid_' . bin2hex(random_bytes(16)), time()]); // 此身份源就是现有医院员工目录;撤销的任职绝不被登录/刷新重新开通。 $this->execute('INSERT OR IGNORE INTO membership(company_id,source_id,member_status,can_login,update_time) VALUES(1,?,1,1,?)', [$sourceId, time()]); return $this->one('SELECT source_id,gid FROM subject WHERE source_id=?', [$sourceId]); }); } public function membership(int $companyId, int $sourceId): ?array { return $this->one('SELECT * FROM membership WHERE company_id=? AND source_id=?', [$companyId, $sourceId]); } public function audit(int $actorId, string $action, int $companyId, int $subjectId = 0): void { $this->execute('INSERT INTO group_audit(actor_id,action,company_id,subject_id,created) VALUES(?,?,?,?,?)', [$actorId, $action, $companyId, $subjectId, time()]); } public function issueCode(array $context, int $now): string { return $this->write(function () use ($context, $now): string { $this->execute('DELETE FROM authorization_code WHERE expires<=? OR used_at IS NOT NULL', [$now]); $pending = $this->one('SELECT COUNT(*) AS n FROM authorization_code WHERE session_ref=? AND expires>? AND used_at IS NULL', [$context['session_ref'], $now]); if ((int) $pending['n'] >= 8) { throw new ApiError(429, '登录请求过于频繁,请稍后重试'); } $code = bin2hex(random_bytes(32)); $this->execute('INSERT INTO authorization_code(code_hash,session_ref,source_id,company_id,client_id,redirect_uri,challenge,expires) VALUES(?,?,?,?,?,?,?,?)', [hash('sha256', $code), $context['session_ref'], $context['source_id'], $context['company_id'], $context['client_id'], $context['redirect_uri'], $context['challenge'], $now + 60]); return $code; }); } public function consumeCode(string $code, string $clientId, string $redirect, string $challenge, int $now): array { return $this->write(function () use ($code, $clientId, $redirect, $challenge, $now): array { $row = $this->one('SELECT * FROM authorization_code WHERE code_hash=?', [hash('sha256', $code)]); if (!$row || $row['used_at'] !== null || (int) $row['expires'] <= $now || !hash_equals($row['client_id'], $clientId) || !hash_equals($row['redirect_uri'], $redirect) || !hash_equals($row['challenge'], $challenge)) { throw new ApiError(422, '登录凭证无效或已过期,请重新进入医院'); } $this->execute('UPDATE authorization_code SET used_at=? WHERE code_hash=?', [$now, hash('sha256', $code)]); return $row; }); } }