Fix CMS login and restore PAGEPAN feature icons

This commit is contained in:
2026-11-21 18:47:07 +08:00
parent d9bda755d1
commit 908f9385fb
32 changed files with 519 additions and 156 deletions
+6
View File
@@ -79,6 +79,12 @@ final class Database
self::json($item['tags']), $item['status'], $item['date'], $item['date'], $item['legacy'],
]);
}
$migration = $pdo->prepare('INSERT OR IGNORE INTO schema_migrations (name) VALUES (?)');
$migration->execute(['restore_pagepan_feature_icons']);
if ($migration->rowCount() === 1) {
PagepanFeatureIcons::migrate($pdo);
}
});
}
+1 -1
View File
@@ -14,7 +14,7 @@ final class Html
private const TAGS = [
'a' => ['href'], 'article' => [], 'b' => [], 'blockquote' => [], 'br' => [],
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
'dl' => [], 'dt' => [], 'em' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'hr' => [], 'i' => [],
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
+55
View File
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use PDO;
final class PagepanFeatureIcons
{
public static function migrate(PDO $pdo): void
{
$query = $pdo->query("SELECT body FROM sections WHERE page_slug = 'pagepan' AND key = 'features'");
$body = $query->fetchColumn();
if (!is_string($body) || $body === '') {
return;
}
$paths = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/pagepan-feature-icons.json'), true, flags: JSON_THROW_ON_ERROR);
$document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $body . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$xpath = new DOMXPath($document);
$changed = false;
foreach ($xpath->query('//article[contains(concat(" ", normalize-space(@class), " "), " feature-card ")]') as $card) {
$heading = $xpath->query('(./h2 | ./h3 | ./h4)[1]', $card)->item(0);
if (!$heading instanceof DOMElement || $card->getElementsByTagName('img')->length > 0) {
continue;
}
$title = trim($heading->textContent);
if (!isset($paths[$title])) {
continue;
}
$icon = $document->createElement('img');
foreach (['src' => $paths[$title], 'alt' => '', 'width' => '50', 'height' => '50', 'loading' => 'lazy'] as $key => $value) {
$icon->setAttribute($key, $value);
}
$card->insertBefore($icon, $card->firstChild);
$changed = true;
}
if ($changed) {
$updated = '';
foreach ($document->getElementsByTagName('body')->item(0)->childNodes as $child) {
$updated .= $document->saveHTML($child);
}
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = 'pagepan' AND key = 'features'")
->execute([trim($updated)]);
$pdo->prepare("UPDATE pages SET updated_at = ? WHERE slug = 'pagepan'")
->execute([(new \DateTimeImmutable('now', new \DateTimeZone('Asia/Shanghai')))->format('Y-m-d H:i:s')]);
}
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class Passwords
{
public const MIN_LENGTH = 8;
public static function isSupported(string $password): bool
{
return strlen($password) <= 72 && !str_contains($password, "\0") && mb_check_encoding($password, 'UTF-8');
}
public static function isValidNew(string $password): bool
{
return self::isSupported($password) && mb_strlen($password, 'UTF-8') >= self::MIN_LENGTH;
}
}
+19 -11
View File
@@ -168,28 +168,36 @@ final class Repository
return $this->one('SELECT id, email, password_hash FROM users WHERE id = ?', [$id]);
}
public function recordLoginAttempt(string $address): bool
public function changePassword(array $user, string $newHash): bool
{
return Database::write(function (PDO $pdo) use ($address): bool {
$now = time();
$query = $this->pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?');
$query->execute([$newHash, $user['id'], $user['password_hash']]);
return $query->rowCount() === 1;
}
public function recordFailedLogin(string $address): int
{
$now = time();
$current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
if ($current && $current['attempts'] >= 12 && $current['expires_at'] > $now) {
return $current['expires_at'] - $now;
}
return Database::write(function (PDO $pdo) use ($address, $now): int {
$pdo->prepare('DELETE FROM login_attempts WHERE expires_at <= ?')->execute([$now]);
$current = $this->one('SELECT attempts FROM login_attempts WHERE address = ?', [$address]);
$current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
if ($current && $current['attempts'] >= 12) {
return false;
return $current['expires_at'] - $now;
}
$query = $pdo->prepare('INSERT INTO login_attempts (address, attempts, expires_at) VALUES (?, 1, ?)
ON CONFLICT (address) DO UPDATE SET attempts = attempts + 1');
$query->execute([$address, $now + 900]);
return true;
return 0;
});
}
public function clearLoginAttempts(string $address): void
{
$this->pdo->prepare('DELETE FROM login_attempts WHERE address = ?')->execute([$address]);
}
private function one(string $sql, array $args): ?array
{
$query = $this->pdo->prepare($sql);
+125 -52
View File
@@ -4,11 +4,13 @@ declare(strict_types=1);
namespace App\Controller;
use App\Content\Database;
use App\Content\Html;
use App\Content\Passwords;
use App\Content\Repository;
use App\Content\View;
use App\Http\Request;
use RuntimeException;
use support\Request;
use support\Response;
final class AdminController
@@ -18,41 +20,41 @@ final class AdminController
public function login(Request $request): Response
{
if ($this->signedIn($request)) {
return View::redirect('/admin');
}
$error = '';
$email = '';
$status = 200;
if ($request->method() === 'POST') {
if (!$this->validToken($request)) {
return $this->error($request, '表单已过期,请刷新后重试。', 403);
}
$email = strtolower($this->input($request, 'email'));
$password = $this->input($request, 'password', trimValue: false);
$repo = new Repository();
$address = $this->address($request);
if (!$repo->recordLoginAttempt($address)) {
$error = '尝试次数过多,请在 15 分钟后重试。';
$status = 429;
} else {
$user = strlen($email) <= 254 ? $repo->administrator($email) : null;
$hash = $user['password_hash'] ?? '$2y$12$XGNKW.dBbfpUrZT8MYvWquCW1dBN3fIlVb29tlaoFIge3YDWG0AzG';
if (strlen($password) <= 72 && password_verify($password, $hash) && $user) {
$request->sessionRegenerateId(true);
$request->session()->flush();
$request->session()->set('admin_id', $user['id']);
$request->session()->set('auth_version', hash('sha256', $user['password_hash']));
$request->session()->set('admin_since', time());
$repo->clearLoginAttempts($address);
return View::redirect('/admin');
}
$error = '邮箱或密码有误。';
$status = 422;
}
return $this->success($request, '/admin');
}
return $this->render($request, 'admin-login', ['title' => '登录内容管理', 'error' => $error, 'email' => $email], $status);
$data = ['title' => '登录内容管理', 'error' => '', 'email' => ''];
if ($request->method() !== 'POST') {
return $this->render($request, 'admin-login', $data);
}
$data['email'] = strtolower($this->input($request, 'email'));
if (!$this->validToken($request)) {
$data['error'] = '登录表单已更新,请重新提交。若反复出现此提示,请确认浏览器允许本站 Cookie。';
return $this->render($request, 'admin-login', $data, 403);
}
$password = $this->input($request, 'password', trimValue: false);
$repo = new Repository();
$user = strlen($data['email']) <= 254 ? $repo->administrator($data['email']) : null;
$hash = $user['password_hash'] ?? '$2y$12$XGNKW.dBbfpUrZT8MYvWquCW1dBN3fIlVb29tlaoFIge3YDWG0AzG';
if (Passwords::isSupported($password) && password_verify($password, $hash) && $user) {
$this->openSession($request, $user);
return $this->success($request, '/admin');
}
$retryAfter = $repo->recordFailedLogin($request->clientAddress());
if ($retryAfter > 0) {
$data['error'] = '当前来源的密码验证失败次数过多,请核对密码或稍后再试。';
return $this->render($request, 'admin-login', $data, 429)->withHeader('Retry-After', (string) $retryAfter);
}
$data['error'] = '邮箱或密码有误。';
return $this->render($request, 'admin-login', $data, 422);
}
public function logout(Request $request): Response
@@ -61,9 +63,47 @@ final class AdminController
return $failure;
}
$request->session()->flush();
$request->session()->save();
$request->sessionRegenerateId(true);
return View::redirect('/admin/login');
return $this->success($request, '/admin/login');
}
public function password(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$error = '';
if ($request->method() === 'POST') {
$current = $this->input($request, 'current_password', trimValue: false);
$password = $this->input($request, 'new_password', trimValue: false);
$confirmation = $this->input($request, 'confirm_password', trimValue: false);
if (!Passwords::isSupported($current) || !password_verify($current, $this->user['password_hash'])) {
$error = '当前密码有误。';
} elseif (!Passwords::isValidNew($password)) {
$error = '新密码至少 8 个字符,最多 72 字节。';
} elseif ($password !== $confirmation) {
$error = '两次输入的新密码不一致。';
} else {
try {
$newHash = password_hash($password, PASSWORD_DEFAULT);
if (!(new Repository())->changePassword($this->user, $newHash)) {
throw new RuntimeException('密码已在其他会话中更新,请重新登录。');
}
$this->openSession($request, array_replace($this->user, ['password_hash' => $newHash]));
return $this->success($request, '/admin/password?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
}
return $this->render($request, 'admin-password', [
'title' => '修改密码', 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200);
}
public function dashboard(Request $request): Response
@@ -121,7 +161,7 @@ final class AdminController
}
$saved = $repo->saveArticle($id === null ? null : (int) $id, $data, $this->version($request));
return View::redirect('/admin/articles/' . $saved . '?saved=1');
return $this->success($request, '/admin/articles/' . $saved . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
@@ -171,7 +211,7 @@ final class AdminController
}
$repo->savePage($slug, $data, $this->version($request));
return View::redirect('/admin/pages/' . $slug . '?saved=1');
return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
@@ -206,7 +246,7 @@ final class AdminController
$data['body'] = Html::sanitize($data['body']);
$repo->saveSection($slug, $key, $data, $this->version($request));
return View::redirect('/admin/pages/' . $slug . '/' . $key . '?saved=1');
return $this->success($request, '/admin/pages/' . $slug . '/' . $key . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
@@ -224,7 +264,7 @@ final class AdminController
}
$body = $this->input($request, 'body');
if (strlen($body) > 300000) {
return new Response(413, ['Cache-Control' => 'no-store'], '正文太长。');
return $this->error($request, '正文太长。', 413);
}
$html = $this->input($request, 'format') === 'html' ? Html::sanitize($body) : Html::markdown($body);
@@ -237,10 +277,12 @@ final class AdminController
private function guard(Request $request): ?Response
{
if (!$this->signedIn($request)) {
return View::redirect('/admin/login');
return $request->isAjax()
? $this->json(['message' => '登录已过期。请在新标签页重新登录,再返回继续编辑。'], 401)
: View::redirect('/admin/login');
}
if ($request->method() === 'POST' && !$this->validToken($request)) {
return $this->error($request, '表单已过期,请刷新后重试。', 403);
return $this->error($request, '表单凭证已更新,请重新提交。', 403);
}
return null;
@@ -256,6 +298,7 @@ final class AdminController
$user = (new Repository())->administratorById($id);
if (!$user || !hash_equals(hash('sha256', $user['password_hash']), (string) $session->get('auth_version'))) {
$session->flush();
$session->save();
return false;
}
@@ -264,6 +307,19 @@ final class AdminController
return true;
}
private function openSession(Request $request, array $user): void
{
$request->sessionRegenerateId(true);
$session = $request->session();
$session->flush();
$session->put([
'admin_id' => $user['id'],
'auth_version' => hash('sha256', $user['password_hash']),
'admin_since' => time(),
]);
$this->token($request);
}
private function token(Request $request): string
{
$session = $request->session();
@@ -271,6 +327,7 @@ final class AdminController
if (!is_string($token)) {
$token = bin2hex(random_bytes(32));
$session->set('csrf', $token);
$session->save();
}
return $token;
@@ -278,7 +335,9 @@ final class AdminController
private function validToken(Request $request): bool
{
return hash_equals($this->token($request), $this->input($request, 'csrf'));
$token = $request->session()->get('csrf');
return is_string($token) && hash_equals($token, $this->input($request, 'csrf'));
}
private function input(Request $request, string $key, bool $trimValue = true): string
@@ -313,15 +372,6 @@ final class AdminController
return $data;
}
private function address(Request $request): string
{
$peer = $request->getRemoteIp();
$trusted = explode(',', getenv('LAYSENSE_TRUSTED_PROXIES') ?: '');
$candidate = $request->header('x-real-ip', '');
return in_array($peer, $trusted, true) && filter_var($candidate, FILTER_VALIDATE_IP) ? $candidate : $peer;
}
private function validationMessage(RuntimeException $exception): string
{
if ($exception instanceof \PDOException) {
@@ -333,9 +383,32 @@ final class AdminController
return $exception->getMessage();
}
private function success(Request $request, string $path): Response
{
return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path);
}
private function json(array $payload, int $status = 200): Response
{
return new Response($status, [
'Content-Type' => 'application/json; charset=utf-8',
'Cache-Control' => 'no-store',
'X-Content-Type-Options' => 'nosniff',
'X-Robots-Tag' => 'noindex, nofollow',
], Database::json($payload));
}
private function render(Request $request, string $view, array $data, int $status = 200): Response
{
return View::render($view, $data + ['token' => $this->token($request), 'user' => $this->user], $status, true);
$token = $this->token($request);
if ($request->isAjax() && $status >= 400) {
return $this->json([
'message' => $data['error'] ?? $data['title'],
...($status === 403 ? ['csrf' => $token] : []),
], $status);
}
return View::render($view, $data + ['token' => $token, 'user' => $this->user], $status, true);
}
private function error(Request $request, string $message, int $status): Response
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Http;
final class Request extends \support\Request
{
private const LOOPBACK = ['127.0.0.1', '::1'];
public function clientAddress(): string
{
$peer = $this->getRemoteIp();
$forwarded = $this->header('x-real-ip', '');
if (!$this->fromTrustedProxy() || !filter_var($forwarded, FILTER_VALIDATE_IP)) {
return $peer;
}
return inet_ntop(inet_pton($forwarded));
}
protected function setSidCookie(string $sessionName, string $sid, array $cookieParams): void
{
$proto = $this->fromTrustedProxy() ? $this->header('x-forwarded-proto', '') : '';
if ($proto === 'https') {
$cookieParams['secure'] = true;
} elseif (getenv('LAYSENSE_SECURE_COOKIES') === false
&& in_array($this->getRemoteIp(), self::LOOPBACK, true)
&& in_array(strtolower((string) $this->host(true)), ['localhost', '127.0.0.1', '[::1]', '::1'], true)
&& in_array($proto, ['', 'http'], true)) {
$cookieParams['secure'] = false;
}
parent::setSidCookie($sessionName, $sid, $cookieParams);
}
private function fromTrustedProxy(): bool
{
$configured = getenv('LAYSENSE_TRUSTED_PROXIES');
$trusted = $configured === false ? self::LOOPBACK : array_map('trim', explode(',', $configured));
return in_array($this->getRemoteIp(), $trusted, true);
}
}
+2
View File
@@ -13,6 +13,7 @@ $e = View::escape(...);
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="stylesheet" href="/assets/site.css">
<link rel="stylesheet" href="/assets/admin.css">
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/admin.js" defer></script>
</head>
<body class="admin-body">
@@ -24,6 +25,7 @@ $e = View::escape(...);
<nav aria-label="后台导航">
<a href="/admin">页面</a>
<a href="/admin/articles">文章</a>
<a href="/admin/password">修改密码</a>
<a href="/">访问网站</a>
<form method="post" action="/admin/logout">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
+1
View File
@@ -13,4 +13,5 @@ $e = View::escape(...);
<label>密码<input name="password" type="password" autocomplete="current-password" required></label>
<button class="button button-primary" type="submit">登录</button>
</form>
<p class="field-note">忘记密码时,可请服务器管理员通过命令行重设。</p>
</div>
+14
View File
@@ -0,0 +1,14 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><h1><?= $e($title) ?></h1></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel password-form" method="post" action="/admin/password">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>当前密码<input name="current_password" type="password" autocomplete="current-password" required></label>
<label>新密码<input name="new_password" type="password" autocomplete="new-password" minlength="8" required><small>至少 8 个字符,最多 72 字节。</small></label>
<label>再次输入新密码<input name="confirm_password" type="password" autocomplete="new-password" minlength="8" required></label>
<div class="form-submit"><button class="button button-primary" type="submit">修改密码</button></div>
</form>
+1
View File
@@ -42,6 +42,7 @@ $nav = [
<meta name="twitter:card" content="summary_large_image">
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="stylesheet" href="/assets/site.css">
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/site.js" defer></script>
</head>
<body>