Load site settings from dotenv and store OAuth credentials
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Config;
|
||||
|
||||
use Dotenv\Dotenv;
|
||||
|
||||
final class Environment
|
||||
{
|
||||
private static ?array $values = null;
|
||||
|
||||
public static function load(): void
|
||||
{
|
||||
if (self::$values !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$file = Dotenv::createArrayBacked(dirname(__DIR__, 2))->safeLoad();
|
||||
self::$values = getenv() + $file;
|
||||
}
|
||||
|
||||
public static function get(string $name): string|false
|
||||
{
|
||||
self::load();
|
||||
|
||||
return self::$values[$name] ?? false;
|
||||
}
|
||||
|
||||
public static function path(string $name, string $default): string
|
||||
{
|
||||
$path = self::get($name) ?: $default;
|
||||
|
||||
return str_starts_with($path, '/') ? $path : dirname(__DIR__, 2) . '/' . $path;
|
||||
}
|
||||
}
|
||||
@@ -4,26 +4,32 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use App\Config\Environment;
|
||||
use PDO;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
final class Database
|
||||
{
|
||||
private const SCHEMA_VERSION = 1;
|
||||
private const SCHEMA_VERSION = 2;
|
||||
// Avoid reusing a deleted ID that may still be open in an editing form.
|
||||
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
|
||||
COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1';
|
||||
|
||||
private static ?PDO $connection = null;
|
||||
|
||||
public static function path(): string
|
||||
{
|
||||
return Environment::path('LAYSITE_DB', 'storage/laysite.sqlite');
|
||||
}
|
||||
|
||||
public static function connect(): PDO
|
||||
{
|
||||
if (self::$connection !== null) {
|
||||
return self::$connection;
|
||||
}
|
||||
|
||||
$path = getenv('LAYSITE_DB') ?: dirname(__DIR__, 2) . '/storage/laysite.sqlite';
|
||||
$path = self::path();
|
||||
if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0750, true) && !is_dir(dirname($path))) {
|
||||
throw new RuntimeException('无法创建 SQLite 存放目录。');
|
||||
}
|
||||
@@ -65,6 +71,9 @@ final class Database
|
||||
foreach (Repository::CATEGORIES as $slug => $name) {
|
||||
$category->execute([$slug, $name]);
|
||||
}
|
||||
if ($version < 2) {
|
||||
OAuthCredentials::migrateLegacy($pdo);
|
||||
}
|
||||
if ($version < self::SCHEMA_VERSION) {
|
||||
$pdo->exec('PRAGMA user_version = ' . self::SCHEMA_VERSION);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,9 @@ final class DesignLibrary
|
||||
if ($id < 1) {
|
||||
return null;
|
||||
}
|
||||
$query = Database::connect()->prepare('SELECT * FROM design_presets WHERE id = ? AND kind = ?');
|
||||
$query = Database::connect()->prepare('SELECT design_presets.*, credentials.revision AS credential_revision
|
||||
FROM design_presets LEFT JOIN layout_oauth_credentials credentials ON credentials.layout_id = design_presets.id
|
||||
WHERE design_presets.id = ? AND kind = ?');
|
||||
$query->execute([$id, $kind]);
|
||||
$row = $query->fetch();
|
||||
if (!$row) {
|
||||
@@ -141,14 +143,14 @@ final class DesignLibrary
|
||||
throw new RuntimeException('请选择 OIDC 或 OAuth 2.0。');
|
||||
}
|
||||
$result = ['mode' => $mode];
|
||||
foreach (['client_id', 'secret_env', 'scope', 'issuer', 'authorization', 'token', 'userinfo', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
|
||||
foreach (['client_id', 'scope', 'issuer', 'authorization', 'token', 'userinfo', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
|
||||
$result[$field] = self::string($data[$field] ?? '', 600);
|
||||
}
|
||||
if (!in_array($result['token_auth'], ['', 'client_secret_basic', 'client_secret_post'], true)) {
|
||||
throw new RuntimeException('令牌端点认证方式无效。');
|
||||
}
|
||||
if ($result['client_id'] === '' || !preg_match('/^LAYSITE_OAUTH_[A-Z0-9_]{1,45}$/D', $result['secret_env'])) {
|
||||
throw new RuntimeException('填写客户端 ID 和以 LAYSITE_OAUTH_ 开头的客户端密钥环境变量名。');
|
||||
if ($result['client_id'] === '') {
|
||||
throw new RuntimeException('请填写客户端 ID。');
|
||||
}
|
||||
foreach ($mode === 'oidc' ? ['issuer'] : ['authorization', 'token', 'userinfo'] as $field) {
|
||||
$url = parse_url($result[$field]);
|
||||
@@ -164,15 +166,41 @@ final class DesignLibrary
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function save(string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default): int
|
||||
public static function hasAccount(string $preset, array $components): bool
|
||||
{
|
||||
return $preset === 'member' && in_array('account', $components, true);
|
||||
}
|
||||
|
||||
public static function identity(?array $layout): ?string
|
||||
{
|
||||
if (empty($layout['credential_revision']) || empty($layout['payload']['provider'])
|
||||
|| !self::hasAccount($layout['preset'], $layout['payload']['components'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return hash('sha256', Database::json([$layout['payload']['provider'], $layout['credential_revision']]));
|
||||
}
|
||||
|
||||
public static function save(string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default, string $secret = ''): int
|
||||
{
|
||||
$name = self::string($name, 100);
|
||||
if ($name === '') {
|
||||
throw new RuntimeException('请填写配置名称。');
|
||||
}
|
||||
$payload = Database::json(self::normalize($kind, $preset, $data));
|
||||
$clean = self::normalize($kind, $preset, $data);
|
||||
$payload = Database::json($clean);
|
||||
$provider = $clean['provider'] ?? [];
|
||||
$active = $provider !== [] && self::hasAccount($preset, $clean['components']);
|
||||
|
||||
return Database::write(function (PDO $pdo) use ($kind, $id, $name, $preset, $payload, $version, $default): int {
|
||||
return Database::write(function (PDO $pdo) use ($kind, $id, $name, $preset, $payload, $version, $default, $provider, $active, $secret): int {
|
||||
if ($active && $secret === '') {
|
||||
$saved = $id === null ? null : self::find($id, $kind);
|
||||
$fields = array_flip(['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id']);
|
||||
if (empty($saved['credential_revision'])
|
||||
|| array_intersect_key($provider, $fields) !== array_intersect_key($saved['payload']['provider'], $fields)) {
|
||||
throw new RuntimeException('启用登录或变更身份提供商时,请填写客户端密钥。');
|
||||
}
|
||||
}
|
||||
if ($id === null) {
|
||||
$pdo->prepare('INSERT INTO design_presets (kind, name, preset, payload) VALUES (?, ?, ?, ?)')->execute([$kind, $name, $preset, $payload]);
|
||||
$id = (int) $pdo->lastInsertId();
|
||||
@@ -183,6 +211,13 @@ final class DesignLibrary
|
||||
throw new RuntimeException('配置已更新,请重新打开后再保存。');
|
||||
}
|
||||
}
|
||||
if ($kind === 'header') {
|
||||
if ($provider === []) {
|
||||
$pdo->prepare('DELETE FROM layout_oauth_credentials WHERE layout_id = ?')->execute([$id]);
|
||||
} elseif ($active && $secret !== '') {
|
||||
OAuthCredentials::store($pdo, $id, $secret);
|
||||
}
|
||||
}
|
||||
if ($kind !== 'palette') {
|
||||
$site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
if ($default) {
|
||||
|
||||
@@ -19,12 +19,8 @@ final class IdentityProvider
|
||||
private readonly Client $http;
|
||||
private array $oidc = [];
|
||||
|
||||
public function __construct(private readonly array $config)
|
||||
public function __construct(private readonly array $config, string $secret)
|
||||
{
|
||||
$secret = getenv($config['secret_env']);
|
||||
if (!is_string($secret) || $secret === '') {
|
||||
throw new RuntimeException('身份服务的客户端密钥尚未配置。');
|
||||
}
|
||||
$this->http = new Client(['timeout' => 8, 'connect_timeout' => 4, 'allow_redirects' => false]);
|
||||
$scope = preg_split('/\s+/', trim($config['scope']), -1, PREG_SPLIT_NO_EMPTY);
|
||||
$authorization = $config['authorization'];
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use App\Config\Environment;
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
@@ -84,7 +85,7 @@ final class Media
|
||||
|
||||
public static function directory(): string
|
||||
{
|
||||
return rtrim(getenv('LAYSITE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
|
||||
return rtrim(Environment::path('LAYSITE_MEDIA_DIR', 'storage/media'), '/');
|
||||
}
|
||||
|
||||
public static function validateBackup(string $path, string $name, string $mime, int $size): void
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use App\Config\Environment;
|
||||
use PDO;
|
||||
use RuntimeException;
|
||||
|
||||
final class OAuthCredentials
|
||||
{
|
||||
private const CIPHER = 'aes-256-gcm';
|
||||
private const KEY_BYTES = 32;
|
||||
private const NONCE_BYTES = 12;
|
||||
private const TAG_BYTES = 16;
|
||||
|
||||
public static function store(PDO $pdo, int $layout, string $secret): void
|
||||
{
|
||||
if ($secret === '' || strlen($secret) > 4096 || str_contains($secret, "\0")) {
|
||||
throw new RuntimeException('客户端密钥为空或格式无效。');
|
||||
}
|
||||
$revision = bin2hex(random_bytes(16));
|
||||
$nonce = random_bytes(self::NONCE_BYTES);
|
||||
$ciphertext = openssl_encrypt($secret, self::CIPHER, self::key(create: true), OPENSSL_RAW_DATA, $nonce,
|
||||
$tag, self::context($layout, $revision), self::TAG_BYTES);
|
||||
if ($ciphertext === false) {
|
||||
throw new RuntimeException('无法加密客户端密钥。');
|
||||
}
|
||||
$pdo->prepare('INSERT INTO layout_oauth_credentials (layout_id, revision, encrypted_secret) VALUES (?, ?, ?)
|
||||
ON CONFLICT (layout_id) DO UPDATE SET revision = excluded.revision, encrypted_secret = excluded.encrypted_secret')
|
||||
->execute([$layout, $revision, base64_encode($nonce . $tag . $ciphertext)]);
|
||||
}
|
||||
|
||||
public static function read(int $layout, string $revision): string
|
||||
{
|
||||
$query = Database::connect()->prepare('SELECT encrypted_secret FROM layout_oauth_credentials WHERE layout_id = ? AND revision = ?');
|
||||
$query->execute([$layout, $revision]);
|
||||
$value = $query->fetchColumn();
|
||||
$encrypted = is_string($value) ? base64_decode($value, true) : false;
|
||||
if ($encrypted === false || strlen($encrypted) <= self::NONCE_BYTES + self::TAG_BYTES) {
|
||||
throw new RuntimeException('客户端密钥尚未配置或已更新。');
|
||||
}
|
||||
$secret = openssl_decrypt(substr($encrypted, self::NONCE_BYTES + self::TAG_BYTES), self::CIPHER, self::key(),
|
||||
OPENSSL_RAW_DATA, substr($encrypted, 0, self::NONCE_BYTES), substr($encrypted, self::NONCE_BYTES, self::TAG_BYTES),
|
||||
self::context($layout, $revision));
|
||||
if ($secret === false) {
|
||||
throw new RuntimeException('无法解密客户端密钥。');
|
||||
}
|
||||
|
||||
return $secret;
|
||||
}
|
||||
|
||||
public static function migrateLegacy(PDO $pdo): void
|
||||
{
|
||||
$layouts = $pdo->query("SELECT id, payload FROM design_presets WHERE kind = 'header' AND preset = 'member'")->fetchAll();
|
||||
$update = $pdo->prepare('UPDATE design_presets SET payload = ?, version = version + 1 WHERE id = ?');
|
||||
foreach ($layouts as $layout) {
|
||||
$payload = json_decode($layout['payload'], true, flags: JSON_THROW_ON_ERROR);
|
||||
$variable = $payload['provider']['secret_env'] ?? null;
|
||||
if (!is_string($variable)) {
|
||||
continue;
|
||||
}
|
||||
unset($payload['provider']['secret_env']);
|
||||
if (preg_match('/^LAYSITE_OAUTH_[A-Z0-9_]{1,45}$/D', $variable)) {
|
||||
$secret = Environment::get($variable);
|
||||
if (is_string($secret) && $secret !== '') {
|
||||
self::store($pdo, (int) $layout['id'], $secret);
|
||||
}
|
||||
}
|
||||
$update->execute([Database::json($payload), $layout['id']]);
|
||||
}
|
||||
}
|
||||
|
||||
private static function context(int $layout, string $revision): string
|
||||
{
|
||||
return 'laysite-oauth:' . $layout . ':' . $revision;
|
||||
}
|
||||
|
||||
private static function key(bool $create = false): string
|
||||
{
|
||||
$path = Database::path() . '.key';
|
||||
if (is_link($path)) {
|
||||
throw new RuntimeException('密钥文件不能使用符号链接。');
|
||||
}
|
||||
$mask = umask(0077);
|
||||
try {
|
||||
$file = is_file($path) || $create ? @fopen($path, $create ? 'c+b' : 'rb') : false;
|
||||
} finally {
|
||||
umask($mask);
|
||||
}
|
||||
if ($file === false) {
|
||||
throw new RuntimeException('无法打开站点密钥文件。');
|
||||
}
|
||||
try {
|
||||
if (!flock($file, $create ? LOCK_EX : LOCK_SH) || (fstat($file)['mode'] & 0077) !== 0) {
|
||||
throw new RuntimeException('站点密钥文件需能上锁,并且只能由运行用户访问。');
|
||||
}
|
||||
$key = stream_get_contents($file, self::KEY_BYTES + 1);
|
||||
if ($create && $key === '') {
|
||||
$key = random_bytes(self::KEY_BYTES);
|
||||
if (fwrite($file, $key) !== self::KEY_BYTES || !fflush($file)) {
|
||||
ftruncate($file, 0);
|
||||
throw new RuntimeException('无法写入站点密钥文件。');
|
||||
}
|
||||
}
|
||||
if (!is_string($key) || strlen($key) !== self::KEY_BYTES) {
|
||||
throw new RuntimeException('站点密钥文件格式无效。');
|
||||
}
|
||||
|
||||
return $key;
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,9 @@ final class SiteBackup
|
||||
|
||||
private static function replaceTables(PDO $pdo, array $tables): void
|
||||
{
|
||||
$credentials = array_column($pdo->query("SELECT layout_id, revision, encrypted_secret, payload
|
||||
FROM layout_oauth_credentials JOIN design_presets ON id = layout_id
|
||||
WHERE kind = 'header' AND preset = 'member'")->fetchAll(), null, 'layout_id');
|
||||
$revisions = [];
|
||||
foreach (self::TABLES as $table) {
|
||||
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
|
||||
@@ -250,6 +253,18 @@ final class SiteBackup
|
||||
$query->execute(array_values($row));
|
||||
}
|
||||
}
|
||||
|
||||
$insert = $pdo->prepare('INSERT INTO layout_oauth_credentials (layout_id, revision, encrypted_secret) VALUES (?, ?, ?)');
|
||||
foreach ($tables['design_presets'] as $layout) {
|
||||
$saved = $credentials[$layout['id']] ?? null;
|
||||
if (!$saved || $layout['kind'] !== 'header' || $layout['preset'] !== 'member') {
|
||||
continue;
|
||||
}
|
||||
$provider = self::decode($layout['payload'])['provider'] ?? [];
|
||||
if ($provider && $provider === (self::decode($saved['payload'])['provider'] ?? [])) {
|
||||
$insert->execute([$layout['id'], $saved['revision'], $saved['encrypted_secret']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function selection(array $designs, string $kind, mixed $id): ?int
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use App\Config\Environment;
|
||||
use App\Http\VisitorSession;
|
||||
use support\Response;
|
||||
|
||||
@@ -19,13 +20,14 @@ final class View
|
||||
$data['header'] = DesignLibrary::layout('header', $data['site'], $page);
|
||||
$data['footer'] = DesignLibrary::layout('footer', $data['site'], $page);
|
||||
$data['visitor'] = null;
|
||||
$provider = $data['header']['payload']['provider'];
|
||||
$personalized = $provider !== [] && in_array('account', $data['header']['payload']['components'], true)
|
||||
$identity = DesignLibrary::identity($data['header']);
|
||||
$data['member'] = $identity !== null;
|
||||
$personalized = $data['member']
|
||||
&& ($page['visibility']['header'] ?? true) && empty($data['previewMode']);
|
||||
if ($personalized) {
|
||||
$profile = VisitorSession::profile(request());
|
||||
if (($profile['layout'] ?? null) === $data['header']['id']
|
||||
&& ($profile['config'] ?? null) === hash('sha256', json_encode($provider, JSON_THROW_ON_ERROR))) {
|
||||
&& ($profile['config'] ?? null) === $identity) {
|
||||
$data['visitor'] = $profile;
|
||||
}
|
||||
}
|
||||
@@ -79,7 +81,7 @@ final class View
|
||||
|
||||
public static function absolute(string $path): string
|
||||
{
|
||||
return rtrim(getenv('LAYSITE_SITE_URL') ?: 'http://127.0.0.1:8787', '/') . $path;
|
||||
return rtrim(Environment::get('LAYSITE_SITE_URL') ?: 'http://127.0.0.1:8787', '/') . $path;
|
||||
}
|
||||
|
||||
public static function date(?string $value, string $format = 'Y年n月j日'): string
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Controller;
|
||||
|
||||
use App\Content\DesignLibrary;
|
||||
use App\Content\IdentityProvider;
|
||||
use App\Content\OAuthCredentials;
|
||||
use App\Content\Repository;
|
||||
use App\Content\View;
|
||||
use App\Http\VisitorSession;
|
||||
@@ -17,17 +18,18 @@ final class AccountController
|
||||
{
|
||||
public function login(Request $request, string $id): Response
|
||||
{
|
||||
$config = $this->provider((int) $id);
|
||||
if ($config === []) {
|
||||
$layout = DesignLibrary::find((int) $id, 'header');
|
||||
$identity = DesignLibrary::identity($layout);
|
||||
if ($identity === null) {
|
||||
return $this->page($request, '该用户区尚未配置登录。', 404);
|
||||
}
|
||||
try {
|
||||
$provider = new IdentityProvider($config);
|
||||
$provider = new IdentityProvider($layout['payload']['provider'], OAuthCredentials::read((int) $id, $layout['credential_revision']));
|
||||
$nonce = bin2hex(random_bytes(32));
|
||||
$url = $provider->authorization($nonce);
|
||||
$session = VisitorSession::create();
|
||||
$session->set('flow', [
|
||||
'layout' => (int) $id, 'config' => $this->fingerprint($config), 'nonce' => $nonce,
|
||||
'layout' => (int) $id, 'config' => $identity, 'nonce' => $nonce,
|
||||
'state' => $provider->client->getState(), 'proof' => $provider->client->getPkceCode(), 'expires' => time() + 600,
|
||||
]);
|
||||
$session->save();
|
||||
@@ -51,11 +53,12 @@ final class AccountController
|
||||
$session->flush();
|
||||
$session->save();
|
||||
try {
|
||||
$config = $this->provider($flow['layout']);
|
||||
if (!$config || $this->fingerprint($config) !== $flow['config']) {
|
||||
$layout = DesignLibrary::find($flow['layout'], 'header');
|
||||
if (DesignLibrary::identity($layout) !== $flow['config']) {
|
||||
return $this->page($request, '登录配置已变更,请重新登录。', 409);
|
||||
}
|
||||
$profile = (new IdentityProvider($config))->profile($code, $flow['proof'], $flow['nonce']);
|
||||
$secret = OAuthCredentials::read($flow['layout'], $layout['credential_revision']);
|
||||
$profile = (new IdentityProvider($layout['payload']['provider'], $secret))->profile($code, $flow['proof'], $flow['nonce']);
|
||||
$current = VisitorSession::create();
|
||||
$current->set('profile', $profile + [
|
||||
'layout' => $flow['layout'], 'config' => $flow['config'], 'expires' => time() + 28800, 'logout' => bin2hex(random_bytes(32)),
|
||||
@@ -91,20 +94,17 @@ final class AccountController
|
||||
{
|
||||
return View::render('account', [
|
||||
'site' => (new Repository())->site(), 'title' => '用户中心', 'description' => '', 'path' => '/account',
|
||||
'error' => $error, 'profile' => VisitorSession::profile($request), 'noindex' => true,
|
||||
'error' => $error, 'profile' => $this->profile($request), 'noindex' => true,
|
||||
], $status)->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
private function provider(int $id): array
|
||||
private function profile(Request $request): ?array
|
||||
{
|
||||
$row = DesignLibrary::find($id, 'header');
|
||||
$profile = VisitorSession::profile($request);
|
||||
if ($profile && DesignLibrary::identity(DesignLibrary::find($profile['layout'], 'header')) === $profile['config']) {
|
||||
return $profile;
|
||||
}
|
||||
|
||||
return ($row['preset'] ?? '') === 'member' && in_array('account', $row['payload']['components'], true)
|
||||
? $row['payload']['provider'] : [];
|
||||
}
|
||||
|
||||
private function fingerprint(array $config): string
|
||||
{
|
||||
return hash('sha256', json_encode($config, JSON_THROW_ON_ERROR));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ final class DesignController extends AdminController
|
||||
$default = $id !== null && ((new Repository())->site()[$kind . '_id'] ?? null) === $id;
|
||||
if ($request->method() === 'POST') {
|
||||
try {
|
||||
$savedProvider = $item['payload']['provider'] ?? [];
|
||||
$secret = '';
|
||||
$item['name'] = $this->input($request, 'name');
|
||||
$item['preset'] = $this->input($request, 'preset');
|
||||
if ($kind === 'palette') {
|
||||
@@ -58,14 +60,18 @@ final class DesignController extends AdminController
|
||||
'text' => $this->input($request, 'text'), 'legal' => $this->input($request, 'legal'),
|
||||
'links' => SiteDesign::parseLinks($this->input($request, 'links')),
|
||||
'action' => $url === '' && $label === '' ? [] : [[$url, $label, $this->input($request, 'action_style'), $request->post('action_blank') === '1']],
|
||||
'provider' => [],
|
||||
'provider' => $savedProvider,
|
||||
];
|
||||
foreach (['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id', 'secret_env', 'scope', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
|
||||
$item['payload']['provider'][$field] = $this->input($request, 'provider_' . $field);
|
||||
$components = $item['payload']['components'];
|
||||
if ($kind === 'header' && is_array($components) && DesignLibrary::hasAccount($item['preset'], $components)) {
|
||||
foreach (['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id', 'scope', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
|
||||
$item['payload']['provider'][$field] = $this->input($request, 'provider_' . $field);
|
||||
}
|
||||
$secret = $this->input($request, 'provider_secret', trimValue: false);
|
||||
}
|
||||
}
|
||||
$default = $request->post('make_default') === '1';
|
||||
$id = DesignLibrary::save($kind, $id, $item['name'], $item['preset'], $item['payload'], $this->version($request), $default);
|
||||
$id = DesignLibrary::save($kind, $id, $item['name'], $item['preset'], $item['payload'], $this->version($request), $default, $secret);
|
||||
|
||||
return $this->success($request, "/admin/design/$kind/$id?saved=1");
|
||||
} catch (RuntimeException $ex) {
|
||||
@@ -111,7 +117,7 @@ final class DesignController extends AdminController
|
||||
], $error === '' ? 200 : 422);
|
||||
}
|
||||
|
||||
public function preview(Request $request, string $kind, string $id): Response
|
||||
public function previewDesign(Request $request, string $kind, string $id): Response
|
||||
{
|
||||
if ($failure = $this->guard($request)) {
|
||||
return $failure;
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Config\Environment;
|
||||
use App\Content\BlockTemplates;
|
||||
use App\Content\Database;
|
||||
use App\Content\DesignLibrary;
|
||||
@@ -26,7 +27,7 @@ final class McpController
|
||||
if ($origin !== null && $origin !== '' && $origin !== rtrim(View::absolute(''), '/')) {
|
||||
return new Response(403, ['Cache-Control' => 'no-store']);
|
||||
}
|
||||
$secret = getenv('LAYSITE_MCP_TOKEN');
|
||||
$secret = Environment::get('LAYSITE_MCP_TOKEN');
|
||||
$header = $request->header('authorization', '');
|
||||
if (!is_string($secret) || strlen($secret) < 32 || !is_string($header) || !hash_equals('Bearer ' . $secret, $header)) {
|
||||
return new Response(401, ['WWW-Authenticate' => 'Bearer realm="LaySite MCP"', 'Cache-Control' => 'no-store']);
|
||||
|
||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use App\Config\Environment;
|
||||
|
||||
final class Request extends \support\Request
|
||||
{
|
||||
private const LOOPBACK = ['127.0.0.1', '::1'];
|
||||
@@ -21,7 +23,7 @@ final class Request extends \support\Request
|
||||
|
||||
private function fromTrustedProxy(): bool
|
||||
{
|
||||
$configured = getenv('LAYSITE_TRUSTED_PROXIES');
|
||||
$configured = Environment::get('LAYSITE_TRUSTED_PROXIES');
|
||||
$trusted = $configured === false ? self::LOOPBACK : array_map('trim', explode(',', $configured));
|
||||
|
||||
return in_array($this->getRemoteIp(), $trusted, true);
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use App\Config\Environment;
|
||||
use support\Request;
|
||||
use support\Response;
|
||||
use Workerman\Protocols\Http\Session;
|
||||
@@ -26,7 +27,7 @@ final class VisitorSession
|
||||
public static function cookie(Response $response, ?Session $session, int $seconds): Response
|
||||
{
|
||||
return $response->cookie(self::COOKIE, $session?->getId() ?? '', $seconds, '/',
|
||||
secure: getenv('LAYSITE_SECURE_COOKIES') === '1', httpOnly: true, sameSite: 'Lax');
|
||||
secure: Environment::get('LAYSITE_SECURE_COOKIES') === '1', httpOnly: true, sameSite: 'Lax');
|
||||
}
|
||||
|
||||
public static function profile(?Request $request): ?array
|
||||
|
||||
@@ -53,25 +53,28 @@ $provider = $data['provider'] ?? [];
|
||||
<?php endforeach ?></select></label>
|
||||
<label><span><input type="checkbox" name="action_blank" value="1" <?= !empty($action[3]) ? 'checked' : '' ?>> 在新标签页打开</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="admin-options form-grid" data-provider-settings><legend>用户区认证</legend>
|
||||
<fieldset class="admin-options form-grid" data-provider-settings<?= DesignLibrary::hasAccount($item['preset'], $data['components']) ? '' : ' hidden' ?>><legend>用户区认证</legend>
|
||||
<label>认证方式<select name="provider_mode"><option value="">关闭</option>
|
||||
<?php foreach (['oidc' => 'OpenID Connect', 'oauth2' => 'OAuth 2.0 + 用户资料'] as $mode => $label): ?>
|
||||
<option value="<?= $e($mode) ?>" <?= ($provider['mode'] ?? '') === $mode ? 'selected' : '' ?>><?= $e($label) ?></option>
|
||||
<?php endforeach ?>
|
||||
</select></label>
|
||||
<label>客户端 ID<input name="provider_client_id" value="<?= $e($provider['client_id'] ?? '') ?>"></label>
|
||||
<label>客户端密钥环境变量<input name="provider_secret_env" value="<?= $e($provider['secret_env'] ?? '') ?>" placeholder="LAYSITE_OAUTH_MEMBER_SECRET"></label>
|
||||
<label>令牌端点认证<select name="provider_token_auth">
|
||||
<label data-provider-field>客户端 ID<input name="provider_client_id" value="<?= $e($provider['client_id'] ?? '') ?>"></label>
|
||||
<label data-provider-field>客户端密钥
|
||||
<input type="password" name="provider_secret" maxlength="4096" autocomplete="new-password">
|
||||
<?php if (!empty($item['credential_revision'])): ?><small>留空会保留已保存的密钥。</small><?php endif ?>
|
||||
</label>
|
||||
<label data-provider-field>令牌端点认证<select name="provider_token_auth">
|
||||
<?php foreach (['' => '自动', 'client_secret_basic' => 'HTTP Basic', 'client_secret_post' => '表单客户端密钥'] as $method => $label): ?>
|
||||
<option value="<?= $e($method) ?>" <?= ($provider['token_auth'] ?? '') === $method ? 'selected' : '' ?>><?= $e($label) ?></option>
|
||||
<?php endforeach ?>
|
||||
</select></label>
|
||||
<label>权限范围<input name="provider_scope" value="<?= $e($provider['scope'] ?? '') ?>" placeholder="openid profile email"></label>
|
||||
<label data-provider-field>权限范围<input name="provider_scope" value="<?= $e($provider['scope'] ?? '') ?>" placeholder="openid profile email"></label>
|
||||
<label data-provider-mode="oidc">OIDC Issuer<input name="provider_issuer" value="<?= $e($provider['issuer'] ?? '') ?>" placeholder="https://id.example.com"></label>
|
||||
<?php foreach (['authorization' => '授权端点', 'token' => '令牌端点', 'userinfo' => '用户资料端点', 'subject_field' => '用户 ID 字段', 'name_field' => '名称字段', 'avatar_field' => '头像字段'] as $field => $label): ?>
|
||||
<label data-provider-mode="oauth2"><?= $e($label) ?><input name="provider_<?= $e($field) ?>" value="<?= $e($provider[$field] ?? '') ?>"></label>
|
||||
<?php endforeach ?>
|
||||
<p class="field-note">回调地址 <code><?= $e(View::absolute('/account/callback')) ?></code></p>
|
||||
<p class="field-note" data-provider-field>回调地址 <code><?= $e(View::absolute('/account/callback')) ?></code></p>
|
||||
</fieldset>
|
||||
<?php else: ?>
|
||||
<label>说明文字<textarea name="text" rows="3"><?= $e($data['text']) ?></textarea></label>
|
||||
|
||||
@@ -5,7 +5,6 @@ use App\Content\View;
|
||||
$e = View::escape(...);
|
||||
$data = $header['payload'];
|
||||
$brand = $data['brand'] ?: $site['name'];
|
||||
$member = $header['preset'] === 'member' && $data['provider'] !== [];
|
||||
?>
|
||||
<header class="masthead masthead-<?= $e($header['preset']) ?>"<?= $showHeader ? '' : ' hidden' ?>>
|
||||
<div class="wrap masthead-inner">
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ $showFooter = $page['visibility']['footer'] ?? true;
|
||||
<body>
|
||||
<a class="skip-link" href="#main-content">跳到内容</a>
|
||||
<?php if ($showHeader || !empty($canvas)): ?>
|
||||
<?= View::fragment('header', compact('header', 'site', 'showHeader', 'visitor', 'path')) ?>
|
||||
<?= View::fragment('header', compact('header', 'site', 'showHeader', 'visitor', 'member', 'path')) ?>
|
||||
<?php endif ?>
|
||||
<main id="main-content"<?= $theme !== '' ? ' class="page-theme theme-' . $e($theme) . '"' : '' ?> tabindex="-1"><?= $content ?></main>
|
||||
<?php if ($showFooter || !empty($canvas)): ?>
|
||||
|
||||
Reference in New Issue
Block a user