feat: port upstream custom pages, notifications, recovery codes, account security

- schema: custom_pages, notifications, recovery_codes tables + UNIQUE(conversations) + posts.edited_at
- API: custom-pages CRUD (public + admin), notifications (list/read/read-all), recovery-codes (generate/count/reset-password), user avatar/password/email, post edit
- UI: custom page nav links + iframe rendering, admin custom pages tab with editor modal, messages page shows notifications, settings page gains avatar upload, password/email change, recovery codes manager
- Sync globals.css with upstream rewrite
This commit is contained in:
lezi-fun committed 2026-08-10 09:07:06 +08:00
1 parent 9e72e4de8e
commit 4732e7d61d
28 files changed
+1196 -255

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
// PUT /api/admin/custom-pages/[id], DELETE /api/admin/custom-pages/[id]
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
if (!UUID_RE.test(params.id)) {
return Response.json({ error: '页面不存在' }, { status: 404 });
}
const { title, content, enabled } = await req.json();
try {
const r = await pool.query(
`UPDATE custom_pages
SET title = $1, content = $2, enabled = $3, updated_at = NOW()
WHERE id = $4
RETURNING *`,
[title, content, enabled, params.id]
);
if (r.rows.length === 0) {
return Response.json({ error: '页面不存在' }, { status: 404 });
}
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
}
}
export async function DELETE(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
if (!UUID_RE.test(params.id)) {
return Response.json({ error: '页面不存在' }, { status: 404 });
}
try {
await pool.query('DELETE FROM custom_pages WHERE id = $1', [params.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+46
View File
@@ -0,0 +1,46 @@
// GET /api/admin/custom-pages, POST /api/admin/custom-pages — 管理 CRUD
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
try {
const r = await pool.query(
'SELECT id, name, title, content, enabled, created_at, updated_at FROM custom_pages ORDER BY created_at'
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { name, title, content } = await req.json();
if (!name || !title || !content) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
return Response.json({ error: '页面名称只允许字母、数字、短横线和下划线' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO custom_pages (name, title, content)
VALUES ($1, $2, $3)
RETURNING *`,
[name, title, content]
);
return Response.json(r.rows[0]);
} catch (err) {
if (err.code === '23505') {
return Response.json({ error: '页面名称已存在' }, { status: 400 });
}
return Response.json({ error: '创建失败,请稍后重试' }, { status: 500 });
}
}
@@ -0,0 +1,17 @@
// GET /api/auth/recovery-codes/count — 剩余恢复码数量
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
const r = await pool.query(
'SELECT COUNT(*) FROM recovery_codes WHERE user_id = $1 AND is_used = false',
[user.id]
);
return Response.json({ count: parseInt(r.rows[0].count) || 0 });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
@@ -0,0 +1,35 @@
// POST /api/auth/recovery-codes/generate — 生成 10 个恢复码
import bcrypt from 'bcrypt';
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
function generateRecoveryCode() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < 20; i++) {
code += chars[Math.floor(Math.random() * chars.length)];
if (i === 4 || i === 9 || i === 14) code += '-';
}
return code;
}
export async function POST(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
await pool.query('DELETE FROM recovery_codes WHERE user_id = $1', [user.id]);
const codes = [];
for (let i = 0; i < 10; i++) {
const code = generateRecoveryCode();
codes.push(code);
const hash = await bcrypt.hash(code, 10);
await pool.query(
'INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2)',
[user.id, hash]
);
}
return Response.json({ success: true, codes });
} catch {
return Response.json({ error: '生成失败,请稍后重试' }, { status: 500 });
}
}
+38
View File
@@ -0,0 +1,38 @@
// POST /api/auth/reset-password — 用恢复码重置密码(公开)
import bcrypt from 'bcrypt';
import pool from '@/lib/db';
export async function POST(req) {
const { email, recoveryCode, newPassword } = await req.json();
if (!email || !recoveryCode || !newPassword) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (newPassword.length < 6) {
return Response.json({ error: '密码至少6位' }, { status: 400 });
}
try {
const user = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
if (user.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
const codes = await pool.query(
'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false',
[user.rows[0].id]
);
let matched = false;
let matchedId = null;
for (const row of codes.rows) {
const valid = await bcrypt.compare(recoveryCode, row.code_hash);
if (valid) { matched = true; matchedId = row.id; break; }
}
if (!matched) {
return Response.json({ error: '恢复码无效或已使用' }, { status: 400 });
}
await pool.query('UPDATE recovery_codes SET is_used = true WHERE id = $1', [matchedId]);
const hash = await bcrypt.hash(newPassword, 10);
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, user.rows[0].id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '重置失败,请稍后重试' }, { status: 500 });
}
}
+17
View File
@@ -0,0 +1,17 @@
// GET /api/custom-pages/[name] — 公开单个页面
import pool from '@/lib/db';
export async function GET(req, { params }) {
try {
const r = await pool.query(
'SELECT id, name, title, content FROM custom_pages WHERE name = $1 AND enabled = true',
[params.name]
);
if (r.rows.length === 0) {
return Response.json({ error: '页面不存在' }, { status: 404 });
}
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+13
View File
@@ -0,0 +1,13 @@
// GET /api/custom-pages — 公开页面列表
import pool from '@/lib/db';
export async function GET() {
try {
const r = await pool.query(
'SELECT id, name, title FROM custom_pages WHERE enabled = true ORDER BY created_at'
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+22
View File
@@ -0,0 +1,22 @@
// PUT /api/notifications/[id]/read — 标记单条已读
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if (!UUID_RE.test(params.id)) {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
try {
await pool.query(
'UPDATE notifications SET is_read = true WHERE id = $1 AND user_id = $2',
[params.id, user.id]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+14
View File
@@ -0,0 +1,14 @@
// PUT /api/notifications/read-all — 全部标记已读
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
await pool.query('UPDATE notifications SET is_read = true WHERE user_id = $1', [user.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+17
View File
@@ -0,0 +1,17 @@
// GET /api/notifications — 我的通知列表
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
const r = await pool.query(
'SELECT id, type, title, content, link, is_read, created_at FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50',
[user.id]
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+26
View File
@@ -27,6 +27,32 @@ export async function GET(req, { params }) {
} }
} }
export async function PUT(req, { params }) {
if (!UUID_RE.test(params.id)) return invalidId();
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { title, content } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写内容' }, { status: 400 });
}
try {
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [params.id]);
if (post.rows.length === 0) return invalidId();
if (post.rows[0].user_id !== user.id) {
return Response.json({ error: '无权限编辑此帖子' }, { status: 403 });
}
const r = await pool.query(
`UPDATE posts SET title = $1, content = $2, edited_at = NOW() WHERE id = $3 RETURNING *`,
[title || '无标题', content, params.id]
);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '编辑失败,请稍后重试' }, { status: 500 });
}
}
export async function DELETE(req, { params }) { export async function DELETE(req, { params }) {
if (!UUID_RE.test(params.id)) return invalidId(); if (!UUID_RE.test(params.id)) return invalidId();
const user = getUser(req); const user = getUser(req);
+21
View File
@@ -0,0 +1,21 @@
// PUT /api/users/[id]/avatar — 修改头像
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if (params.id !== user.id) {
return Response.json({ error: '无权限修改他人头像' }, { status: 403 });
}
const { avatar_url } = await req.json();
if (!avatar_url) {
return Response.json({ error: '请提供头像地址' }, { status: 400 });
}
try {
await pool.query('UPDATE users SET avatar_url = $1 WHERE id = $2', [avatar_url, params.id]);
return Response.json({ success: true, avatar_url });
} catch {
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
}
}
+34
View File
@@ -0,0 +1,34 @@
// PUT /api/users/[id]/email — 修改邮箱(需密码验证)
import bcrypt from 'bcrypt';
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if (params.id !== user.id) {
return Response.json({ error: '无权限' }, { status: 403 });
}
const { password, newEmail } = await req.json();
if (!password || !newEmail) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
try {
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [params.id]);
if (u.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
const valid = await bcrypt.compare(password, u.rows[0].password_hash);
if (!valid) {
return Response.json({ error: '密码错误' }, { status: 400 });
}
const existing = await pool.query('SELECT id FROM users WHERE email = $1 AND id != $2', [newEmail, params.id]);
if (existing.rows.length > 0) {
return Response.json({ error: '邮箱已被占用' }, { status: 400 });
}
await pool.query('UPDATE users SET email = $1 WHERE id = $2', [newEmail, params.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
}
}
+34
View File
@@ -0,0 +1,34 @@
// PUT /api/users/[id]/password — 修改密码
import bcrypt from 'bcrypt';
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function PUT(req, { params }) {
const user = getUser(req);
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
if (params.id !== user.id) {
return Response.json({ error: '无权限' }, { status: 403 });
}
const { oldPassword, newPassword } = await req.json();
if (!oldPassword || !newPassword) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (newPassword.length < 6) {
return Response.json({ error: '新密码至少6位' }, { status: 400 });
}
try {
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [params.id]);
if (u.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
const valid = await bcrypt.compare(oldPassword, u.rows[0].password_hash);
if (!valid) {
return Response.json({ error: '当前密码错误' }, { status: 400 });
}
const hash = await bcrypt.hash(newPassword, 10);
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, params.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
}
}
+172 -220
View File
@@ -41,191 +41,6 @@
--modal-overlay: rgba(0, 0, 0, 0.7); --modal-overlay: rgba(0, 0, 0, 0.7);
} }
/* 暗色模式下的输入框修复 */
[data-theme="dark"] input,
[data-theme="dark"] textarea,
[data-theme="dark"] select {
background: #0f1117 !important;
color: #e8edf5 !important;
border-color: #2a2d3a !important;
}
[data-theme="dark"] input::placeholder,
[data-theme="dark"] textarea::placeholder {
color: #6b7280 !important;
}
[data-theme="dark"] input:focus,
[data-theme="dark"] textarea:focus,
[data-theme="dark"] select:focus {
background: #1a1d27 !important;
border-color: var(--primary) !important;
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15) !important;
}
[data-theme="dark"] .modal-content input,
[data-theme="dark"] .modal-content textarea,
[data-theme="dark"] .modal-content select {
background: #0f1117 !important;
color: #e8edf5 !important;
border-color: #2a2d3a !important;
}
[data-theme="dark"] .modal-content input:focus,
[data-theme="dark"] .modal-content textarea:focus,
[data-theme="dark"] .modal-content select:focus {
background: #1a1d27 !important;
border-color: var(--primary) !important;
}
[data-theme="dark"] #settingsUsername,
[data-theme="dark"] #settingsBio,
[data-theme="dark"] #postTitle,
[data-theme="dark"] #postContent,
[data-theme="dark"] #replyContent {
background: #0f1117 !important;
color: #e8edf5 !important;
border-color: #2a2d3a !important;
}
[data-theme="dark"] #settingsUsername:focus,
[data-theme="dark"] #settingsBio:focus,
[data-theme="dark"] #postTitle:focus,
[data-theme="dark"] #postContent:focus,
[data-theme="dark"] #replyContent:focus {
background: #1a1d27 !important;
border-color: var(--primary) !important;
}
[data-theme="dark"] .captcha-row input {
background: #0f1117 !important;
color: #e8edf5 !important;
border-color: #2a2d3a !important;
}
[data-theme="dark"] .captcha-row input:focus {
background: #1a1d27 !important;
border-color: var(--primary) !important;
}
[data-theme="dark"] #reportReason {
background: #0f1117 !important;
color: #e8edf5 !important;
border-color: #2a2d3a !important;
}
[data-theme="dark"] #reportReason option {
background: #0f1117 !important;
color: #e8edf5 !important;
}
[data-theme="dark"] .post-card {
background: var(--surface);
}
[data-theme="dark"] .post-card:hover {
border-color: var(--primary-light);
}
[data-theme="dark"] .stats-box,
[data-theme="dark"] .links-box {
background: var(--surface);
}
[data-theme="dark"] .reply-item {
background: var(--surface);
}
[data-theme="dark"] .dropdown-menu {
background: var(--surface);
border-color: var(--border);
}
[data-theme="dark"] .dropdown-menu a:hover {
background: var(--border-light);
}
[data-theme="dark"] .tab {
color: var(--text-secondary);
}
[data-theme="dark"] .tab:hover {
color: var(--text);
}
[data-theme="dark"] .tab.active {
color: #fff;
}
[data-theme="dark"] .admin-tab {
background: var(--surface);
border-color: var(--border);
color: var(--text-secondary);
}
[data-theme="dark"] .admin-tab:hover {
background: var(--border-light);
}
[data-theme="dark"] .admin-tab.active {
background: var(--primary);
color: #fff;
}
[data-theme="dark"] .btn-ghost {
border-color: var(--border);
color: var(--text-secondary);
}
[data-theme="dark"] .btn-ghost:hover {
background: var(--border-light);
color: var(--text);
}
[data-theme="dark"] .report-item {
background: var(--surface);
}
[data-theme="dark"] #adminContent table {
background: var(--surface);
}
[data-theme="dark"] #adminContent th {
background: var(--border-light);
color: var(--text-secondary);
}
[data-theme="dark"] #adminContent td {
border-bottom-color: var(--border-light);
}
[data-theme="dark"] .captcha-row span {
background: var(--border-light);
color: var(--primary-light);
}
[data-theme="dark"] .page-slide {
background: var(--bg);
}
[data-theme="dark"] .post-detail-card {
background: var(--surface);
}
[data-theme="dark"] #replyArea textarea {
background: #0f1117 !important;
color: #e8edf5 !important;
border-color: #2a2d3a !important;
}
[data-theme="dark"] #replyArea textarea:focus {
background: #1a1d27 !important;
border-color: var(--primary) !important;
}
[data-theme="dark"] .modal-content {
background: var(--surface);
}
[data-theme="dark"] .modal-content .close svg {
stroke: var(--text-secondary);
}
[data-theme="dark"] .modal-content .close:hover svg {
stroke: var(--text);
}
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
@@ -445,6 +260,8 @@ svg {
/* ===== 主布局 ===== */ /* ===== 主布局 ===== */
#app { #app {
display: flex; display: flex;
justify-content: center;
align-items: flex-start;
max-width: 1200px; max-width: 1200px;
margin: 0 auto; margin: 0 auto;
padding: 24px 32px 40px; padding: 24px 32px 40px;
@@ -806,7 +623,7 @@ svg {
inset: 0; inset: 0;
background: var(--bg); background: var(--bg);
z-index: 50; z-index: 50;
padding: 24px 32px 40px; padding: 84px 32px 40px;
overflow-y: auto; overflow-y: auto;
transition: background var(--transition); transition: background var(--transition);
} }
@@ -1048,6 +865,153 @@ svg {
border-bottom: none; border-bottom: none;
} }
/* ===== 暗色模式修复 ===== */
[data-theme="dark"] input,
[data-theme="dark"] textarea,
[data-theme="dark"] select {
background: #0f1117 !important;
color: #e8edf5 !important;
border-color: #2a2d3a !important;
}
[data-theme="dark"] input::placeholder,
[data-theme="dark"] textarea::placeholder {
color: #6b7280 !important;
}
[data-theme="dark"] input:focus,
[data-theme="dark"] textarea:focus,
[data-theme="dark"] select:focus {
background: #1a1d27 !important;
border-color: var(--primary) !important;
}
[data-theme="dark"] .modal-content input,
[data-theme="dark"] .modal-content textarea,
[data-theme="dark"] .modal-content select {
background: #0f1117 !important;
color: #e8edf5 !important;
}
[data-theme="dark"] .modal-content input:focus,
[data-theme="dark"] .modal-content textarea:focus {
background: #1a1d27 !important;
}
[data-theme="dark"] #settingsUsername,
[data-theme="dark"] #settingsBio,
[data-theme="dark"] #postTitle,
[data-theme="dark"] #postContent,
[data-theme="dark"] #replyContent {
background: #0f1117 !important;
color: #e8edf5 !important;
}
[data-theme="dark"] #settingsUsername:focus,
[data-theme="dark"] #settingsBio:focus,
[data-theme="dark"] #postTitle:focus,
[data-theme="dark"] #postContent:focus,
[data-theme="dark"] #replyContent:focus {
background: #1a1d27 !important;
}
[data-theme="dark"] .captcha-row input {
background: #0f1117 !important;
color: #e8edf5 !important;
}
[data-theme="dark"] .captcha-row input:focus {
background: #1a1d27 !important;
}
[data-theme="dark"] #reportReason {
background: #0f1117 !important;
color: #e8edf5 !important;
}
[data-theme="dark"] #reportReason option {
background: #0f1117 !important;
color: #e8edf5 !important;
}
[data-theme="dark"] .post-card {
background: var(--surface);
}
[data-theme="dark"] .post-card:hover {
border-color: var(--primary-light);
}
[data-theme="dark"] .stats-box,
[data-theme="dark"] .links-box {
background: var(--surface);
}
[data-theme="dark"] .reply-item {
background: var(--surface);
}
[data-theme="dark"] .dropdown-menu {
background: var(--surface);
border-color: var(--border);
}
[data-theme="dark"] .dropdown-menu a:hover {
background: var(--border-light);
}
[data-theme="dark"] .tab {
color: var(--text-secondary);
}
[data-theme="dark"] .tab:hover {
color: var(--text);
}
[data-theme="dark"] .tab.active {
color: #fff;
}
[data-theme="dark"] .admin-tab {
background: var(--surface);
border-color: var(--border);
color: var(--text-secondary);
}
[data-theme="dark"] .admin-tab:hover {
background: var(--border-light);
}
[data-theme="dark"] .admin-tab.active {
background: var(--primary);
color: #fff;
}
[data-theme="dark"] .btn-ghost {
border-color: var(--border);
color: var(--text-secondary);
}
[data-theme="dark"] .btn-ghost:hover {
background: var(--border-light);
color: var(--text);
}
[data-theme="dark"] .report-item {
background: var(--surface);
}
[data-theme="dark"] #adminContent table {
background: var(--surface);
}
[data-theme="dark"] #adminContent th {
background: var(--border-light);
color: var(--text-secondary);
}
[data-theme="dark"] #adminContent td {
border-bottom-color: var(--border-light);
}
[data-theme="dark"] .captcha-row span {
background: var(--border-light);
color: var(--primary-light);
}
[data-theme="dark"] .page-slide {
background: var(--bg);
}
[data-theme="dark"] .post-detail-card {
background: var(--surface);
}
[data-theme="dark"] #replyArea textarea {
background: #0f1117 !important;
color: #e8edf5 !important;
}
[data-theme="dark"] #replyArea textarea:focus {
background: #1a1d27 !important;
}
[data-theme="dark"] .modal-content {
background: var(--surface);
}
[data-theme="dark"] .modal-content .close svg {
stroke: var(--text-secondary);
}
[data-theme="dark"] .modal-content .close:hover svg {
stroke: var(--text);
}
/* ===== 响应式 ===== */ /* ===== 响应式 ===== */
@media (max-width: 768px) { @media (max-width: 768px) {
#sidebar { #sidebar {
@@ -1088,7 +1052,7 @@ svg {
max-height: 100px; max-height: 100px;
} }
.page-slide { .page-slide {
padding: 16px; padding: 84px 16px 20px;
} }
.post-detail-card { .post-detail-card {
padding: 16px !important; padding: 16px !important;
@@ -1104,37 +1068,25 @@ svg {
} }
} }
/* ===== 独立页面内容居中 ===== */ @media (max-width: 480px) {
.page-slide .page-header, .forum-name {
.page-slide > div, font-size: 17px;
#postDetailContent, }
#replyArea { .btn-primary,
max-width: 700px; .btn-ghost {
margin: 0 auto; padding: 6px 14px;
width: 100%; font-size: 13px;
} }
.modal-content {
/* 帖子详情页内容居中 */ padding: 20px 16px;
#pagePost .post-detail-card { }
max-width: 700px; .post-actions {
margin: 0 auto; gap: 12px;
} font-size: 12px;
flex-wrap: wrap;
/* 设置页面居中 */ }
#pageSettings > div { #customNavLinks a {
max-width: 400px; font-size: 12px !important;
margin: 0 auto; padding: 2px 6px !important;
} }
/* 发布新帖居中 */
#pageNew > div {
max-width: 600px;
margin: 0 auto;
}
/* 管理后台居中 */
#pageAdmin .admin-tabs,
#adminContent {
max-width: 900px;
margin: 0 auto;
} }
+5 -9
View File
@@ -11,11 +11,13 @@ import NewPost from '@/components/NewPost';
import AdminPage from '@/components/AdminPage'; import AdminPage from '@/components/AdminPage';
import SettingsPage from '@/components/SettingsPage'; import SettingsPage from '@/components/SettingsPage';
import UserProfile from '@/components/UserProfile'; import UserProfile from '@/components/UserProfile';
import CustomPage from '@/components/CustomPage';
import MessagesPage from '@/components/MessagesPage';
import ChatManager from '@/components/chat/ChatManager'; import ChatManager from '@/components/chat/ChatManager';
import Modals from '@/components/Modals'; import Modals from '@/components/Modals';
function HomeInner() { function HomeInner() {
const { view, currentPostId, currentUsername } = useApp(); const { view, currentPostId, currentUsername, currentPageName } = useApp();
const [modal, setModal] = useState(null); // null | login | register | report const [modal, setModal] = useState(null); // null | login | register | report
const [reportPostId, setReportPostId] = useState(null); const [reportPostId, setReportPostId] = useState(null);
@@ -40,17 +42,11 @@ function HomeInner() {
<div style={{ display: view !== 'feed' ? 'block' : 'none' }}> <div style={{ display: view !== 'feed' ? 'block' : 'none' }}>
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} />} {view === 'post' && currentPostId && <PostDetail postId={currentPostId} />}
{view === 'user' && currentUsername && <UserProfile username={currentUsername} />} {view === 'user' && currentUsername && <UserProfile username={currentUsername} />}
{view === 'custom' && currentPageName && <CustomPage pageName={currentPageName} />}
{view === 'new' && <NewPost />} {view === 'new' && <NewPost />}
{view === 'admin' && <AdminPage />} {view === 'admin' && <AdminPage />}
{view === 'settings' && <SettingsPage />} {view === 'settings' && <SettingsPage />}
{view === 'messages' && ( {view === 'messages' && <MessagesPage />}
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<h2><Icon name="message" size={20} /> 消息</h2>
</div>
<p style={{ color: '#94a3b8', padding: '20px 0', maxWidth: 700, margin: '0 auto', width: '100%' }}>暂无消息</p>
</div>
)}
</div> </div>
<Modals modal={modal} onClose={() => setModal(null)} reportPostId={reportPostId} /> <Modals modal={modal} onClose={() => setModal(null)} reportPostId={reportPostId} />
+71
View File
@@ -0,0 +1,71 @@
'use client';
// 账户安全:修改密码 + 修改邮箱
import { useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
export default function AccountSecurity() {
const { currentUser } = useApp();
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [pwStatus, setPwStatus] = useState(null);
const [emailPassword, setEmailPassword] = useState('');
const [newEmail, setNewEmail] = useState('');
const [emailStatus, setEmailStatus] = useState(null);
const changePassword = async () => {
if (!oldPassword || !newPassword) { alert('请填写完整信息'); return; }
if (newPassword.length < 6) { alert('新密码至少6位'); return; }
try {
await API.updatePassword(currentUser.id, oldPassword, newPassword);
setPwStatus({ ok: true, msg: '✅ 密码修改成功' });
setOldPassword('');
setNewPassword('');
} catch (err) {
setPwStatus({ ok: false, msg: '❌ ' + err.message });
}
};
const changeEmail = async () => {
if (!emailPassword || !newEmail) { alert('请填写完整信息'); return; }
try {
await API.updateEmail(currentUser.id, emailPassword, newEmail);
setEmailStatus({ ok: true, msg: '✅ 邮箱修改成功' });
setEmailPassword('');
setNewEmail('');
} catch (err) {
setEmailStatus({ ok: false, msg: '❌ ' + err.message });
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 12 }}>🔒 账户安全</h3>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>当前密码</label>
<input type="password" value={oldPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setOldPassword(e.target.value)} />
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>新密码</label>
<input type="password" value={newPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewPassword(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changePassword}>修改密码</button>
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444' }}>{pwStatus.msg}</div>}
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }}></div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>当前密码(验证身份)</label>
<input type="password" value={emailPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setEmailPassword(e.target.value)} />
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>新邮箱</label>
<input type="email" value={newEmail} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewEmail(e.target.value)} />
</div>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changeEmail}>修改邮箱</button>
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444' }}>{emailStatus.msg}</div>}
</div>
);
}
+3
View File
@@ -8,12 +8,14 @@ import AdminUsers from './admin/AdminUsers';
import AdminLogs from './admin/AdminLogs'; import AdminLogs from './admin/AdminLogs';
import AdminLinks from './admin/AdminLinks'; import AdminLinks from './admin/AdminLinks';
import AdminForumSettings from './admin/AdminForumSettings'; import AdminForumSettings from './admin/AdminForumSettings';
import AdminCustomPages from './admin/AdminCustomPages';
const TABS = [ const TABS = [
{ key: 'reports', label: '举报', icon: 'shieldAlert' }, { key: 'reports', label: '举报', icon: 'shieldAlert' },
{ key: 'users', label: '用户', icon: 'users' }, { key: 'users', label: '用户', icon: 'users' },
{ key: 'logs', label: '日志', icon: 'file' }, { key: 'logs', label: '日志', icon: 'file' },
{ key: 'links', label: '友链', icon: 'link' }, { key: 'links', label: '友链', icon: 'link' },
{ key: 'custom', label: '自定义页面', icon: 'file' },
{ key: 'settings', label: '论坛设置', icon: 'settings' }, { key: 'settings', label: '论坛设置', icon: 'settings' },
]; ];
@@ -41,6 +43,7 @@ export default function AdminPage() {
{tab === 'users' && <AdminUsers />} {tab === 'users' && <AdminUsers />}
{tab === 'logs' && <AdminLogs />} {tab === 'logs' && <AdminLogs />}
{tab === 'links' && <AdminLinks />} {tab === 'links' && <AdminLinks />}
{tab === 'custom' && <AdminCustomPages />}
{tab === 'settings' && <AdminForumSettings />} {tab === 'settings' && <AdminForumSettings />}
</div> </div>
</div> </div>
+21 -1
View File
@@ -14,9 +14,10 @@ export default function AppProvider({ children }) {
const [currentUser, setCurrentUser] = useState(null); const [currentUser, setCurrentUser] = useState(null);
const [forumName, setForumName] = useState('Forumlify'); const [forumName, setForumName] = useState('Forumlify');
const [theme, setThemeState] = useState('light'); const [theme, setThemeState] = useState('light');
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
const [currentPostId, setCurrentPostId] = useState(null); const [currentPostId, setCurrentPostId] = useState(null);
const [currentUsername, setCurrentUsername] = useState(null); const [currentUsername, setCurrentUsername] = useState(null);
const [currentPageName, setCurrentPageName] = useState(null);
const [sort, setSort] = useState('latest'); const [sort, setSort] = useState('latest');
const [refreshKey, setRefreshKey] = useState(0); const [refreshKey, setRefreshKey] = useState(0);
const loadedRef = useRef(false); const loadedRef = useRef(false);
@@ -77,6 +78,10 @@ export default function AppProvider({ children }) {
setCurrentUsername(userParam); setCurrentUsername(userParam);
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) { } else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
setView(pageParam); setView(pageParam);
} else if (pageParam) {
// 未知 page 参数视为自定义页面
setView('custom');
setCurrentPageName(pageParam);
} }
}, []); }, []);
@@ -116,6 +121,16 @@ export default function AppProvider({ children }) {
setCurrentUsername(username); setCurrentUsername(username);
}, []); }, []);
const openCustomPage = useCallback((pageName) => {
const url = new URL(window.location);
url.searchParams.set('page', pageName);
url.searchParams.delete('post');
url.searchParams.delete('user');
window.history.pushState({ page: 'custom', pageName }, '', url);
setView('custom');
setCurrentPageName(pageName);
}, []);
// 浏览器前进后退 // 浏览器前进后退
useEffect(() => { useEffect(() => {
const onPop = (e) => { const onPop = (e) => {
@@ -126,10 +141,14 @@ export default function AppProvider({ children }) {
} else if (state.username) { } else if (state.username) {
setView('user'); setView('user');
setCurrentUsername(state.username); setCurrentUsername(state.username);
} else if (state.pageName) {
setView('custom');
setCurrentPageName(state.pageName);
} else { } else {
setView(state.page || 'feed'); setView(state.page || 'feed');
setCurrentPostId(null); setCurrentPostId(null);
setCurrentUsername(null); setCurrentUsername(null);
setCurrentPageName(null);
} }
}; };
window.addEventListener('popstate', onPop); window.addEventListener('popstate', onPop);
@@ -173,6 +192,7 @@ export default function AppProvider({ children }) {
view, navigate, view, navigate,
currentPostId, openPost, currentPostId, openPost,
currentUsername, openUser, currentUsername, openUser,
currentPageName, openCustomPage,
sort, setSort, sort, setSort,
refreshKey, refresh, refreshKey, refresh,
login, register, logout, login, register, logout,
+61
View File
@@ -0,0 +1,61 @@
'use client';
// 自定义页面:以 iframe srcdoc 渲染 HTML 内容(与原版一致)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
export default function CustomPage({ pageName }) {
const [html, setHtml] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
setHtml(null);
setError(null);
API.getCustomPage(pageName)
.then((page) => setHtml(page.content))
.catch((err) => setError(err.message));
}, [pageName]);
if (error) {
return (
<div style={{ padding: '84px 32px', textAlign: 'center', color: '#ef4444' }}>
页面加载失败:{error}
</div>
);
}
if (html === null) {
return <div style={{ padding: '84px 32px', textAlign: 'center', color: '#94a3b8' }}>加载中...</div>;
}
const srcdoc = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 24px;
background: var(--bg, #f6f8fc);
color: var(--text, #0a0e1a);
}
@media (prefers-color-scheme: dark) {
body { background: #0f1117; color: #e8edf5; }
}
</style>
</head>
<body>${html}</body>
</html>`;
return (
<div style={{ padding: '84px 32px 40px', background: 'var(--bg)', minHeight: '100vh' }}>
<iframe
style={{ width: '100%', minHeight: '70vh', border: 'none', borderRadius: 8, background: 'var(--surface)' }}
sandbox="allow-scripts allow-modals allow-same-origin"
srcDoc={srcdoc}
title={pageName}
/>
</div>
);
}
+67
View File
@@ -0,0 +1,67 @@
'use client';
// 消息页:通知列表(回复/删除/举报处理/系统)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
const TYPE_MAP = { reply: '💬', post_deleted: '🗑️', report_handled: '🛡️', system: '📢' };
export default function MessagesPage() {
const { currentUser } = useApp();
const [notifications, setNotifications] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
if (!currentUser) return;
API.getNotifications()
.then((data) => {
setNotifications(data || []);
setError(null);
API.markAllNotificationsRead().catch(() => {});
})
.catch((e) => { setError(e.message); setNotifications([]); });
}, [currentUser]);
if (!currentUser) {
return <div className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>请先登录</div>;
}
return (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<h2><Icon name="message" size={20} /> 消息</h2>
</div>
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
{error ? (
<div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>
) : notifications === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
) : notifications.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>
<Icon name="message" size={48} />
<p style={{ fontSize: 16 }}>暂无消息</p>
<p style={{ fontSize: 13 }}>当有人回复你的帖子或处理你的举报时,会在这里通知你</p>
</div>
) : (
notifications.map((n) => {
const icon = TYPE_MAP[n.type] || '📌';
const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : '';
return (
<div key={n.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', borderBottom: '1px solid var(--border-light)', background: 'var(--surface)', borderRadius: 6, marginBottom: 6 }}>
<span style={{ fontSize: 20 }}>{icon}</span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 14 }}>{n.title}</div>
<div style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 2 }}>{n.content}</div>
{n.link && <a href={n.link} style={{ color: 'var(--primary)', fontSize: 13, textDecoration: 'none', marginTop: 4, display: 'inline-block' }}>查看详情 →</a>}
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 4 }}>{time}</div>
</div>
</div>
);
})
)}
</div>
</div>
);
}
+25 -3
View File
@@ -1,13 +1,19 @@
'use client'; 'use client';
// 导航栏:论坛名、登录/注册按钮、用户下拉菜单、主题切换 // 导航栏:论坛名、自定义页面链接、登录/注册、用户菜单、主题切换
import { useState } from 'react'; import { useState, useEffect } from 'react';
import { useApp } from './AppProvider'; import { useApp } from './AppProvider';
import { Icon } from './Icons'; import { Icon } from './Icons';
import { API } from '@/lib/api';
export default function Navbar({ onOpenModal }) { export default function Navbar({ onOpenModal }) {
const { currentUser, forumName, theme, toggleTheme, navigate, logout } = useApp(); const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp();
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
const [customPages, setCustomPages] = useState([]);
useEffect(() => {
API.getCustomPages().then(setCustomPages).catch(() => {});
}, []);
const avatarSrc = currentUser?.avatar_url || const avatarSrc = currentUser?.avatar_url ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') + 'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
@@ -35,6 +41,22 @@ export default function Navbar({ onOpenModal }) {
<span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}> <span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}>
{forumName} {forumName}
</span> </span>
<span id="customNavLinks" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 16 }}>
{customPages.map((p) => (
<a
key={p.id}
href="#"
className="custom-page-nav-link"
data-custom={p.name}
onClick={(e) => { e.preventDefault(); openCustomPage(p.name); }}
style={{ color: 'var(--text-secondary)', textDecoration: 'none', fontSize: 14, padding: '4px 10px', borderRadius: 4, transition: 'color 0.15s' }}
onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--text)'; }}
onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-secondary)'; }}
>
{p.title}
</a>
))}
</span>
</div> </div>
<div className="nav-right"> <div className="nav-right">
<div id="userMenu"> <div id="userMenu">
+65
View File
@@ -0,0 +1,65 @@
'use client';
// 恢复码管理:查看 + 重新生成
import { useState, useEffect } from 'react';
import { API } from '@/lib/api';
export default function RecoveryCodes() {
const [count, setCount] = useState(0);
const [modal, setModal] = useState(null); // null | {codes, isNew}
const loadCount = () => {
API.getRecoveryCodeCount().then((d) => setCount(d.count || 0)).catch(() => {});
};
useEffect(loadCount, []);
const regenerate = async () => {
if (!confirm('重新生成将使所有旧恢复码失效,确定继续吗?')) return;
try {
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: true });
loadCount();
} catch (err) {
alert('生成失败:' + err.message);
}
};
const view = async () => {
try {
// 生成后直接展示;若已有恢复码则重新生成展示(与原版一致:查看即生成新码)
const d = await API.generateRecoveryCodes();
setModal({ codes: d.codes || [], isNew: false });
loadCount();
} catch (err) {
alert('获取失败:' + err.message);
}
};
return (
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<h3 style={{ fontSize: 16, marginBottom: 8 }}>🔑 恢复码</h3>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>用于忘记密码时重置账户。每个恢复码只能使用一次。</p>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={view}>📋 查看恢复码</button>
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={regenerate}>🔄 重新生成</button>
</div>
<div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>剩余 {count} 个可用恢复码</div>
{modal && (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setModal(null); }}>
<div className="modal-content" style={{ maxWidth: 480, position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setModal(null)}>&times;</span>
<h2 style={{ marginBottom: 12 }}>{modal.isNew ? '🆕 新恢复码' : '🔑 恢复码'}</h2>
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12 }}>⚠️ 请妥善保存这些恢复码,关闭窗口后无法再次查看。</p>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
{modal.codes.map((c, i) => (
<code key={i} style={{ background: 'var(--bg)', padding: '8px 12px', borderRadius: 6, fontSize: 13, textAlign: 'center', userSelect: 'all' }}>{c}</code>
))}
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={() => setModal(null)}>我已保存</button>
</div>
</div>
)}
</div>
);
}
+62 -20
View File
@@ -1,15 +1,35 @@
'use client'; 'use client';
// 个人设置页 // 个人设置页:头像 + 基本资料 + 账户安全 + 恢复码
import { useState } from 'react'; import { useState, useRef } from 'react';
import { API } from '@/lib/api'; import { API, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider'; import { useApp } from './AppProvider';
import { Icon } from './Icons'; import { Icon } from './Icons';
import AccountSecurity from './AccountSecurity';
import RecoveryCodes from './RecoveryCodes';
export default function SettingsPage() { export default function SettingsPage() {
const { currentUser, setCurrentUser } = useApp(); const { currentUser, setCurrentUser } = useApp();
const [username, setUsername] = useState(currentUser?.username || ''); const [username, setUsername] = useState(currentUser?.username || '');
const [bio, setBio] = useState(currentUser?.bio || ''); const [bio, setBio] = useState(currentUser?.bio || '');
const [avatarUrl, setAvatarUrl] = useState(currentUser?.avatar_url || '');
const [avatarStatus, setAvatarStatus] = useState(null);
const avatarInputRef = useRef(null);
const handleAvatar = async (file) => {
if (!file) return;
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: '❌ 请选择图片文件' }); return; }
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: '❌ 图片不能超过 5MB' }); return; }
try {
const url = await uploadImage(file);
await API.updateAvatar(currentUser.id, url);
setAvatarUrl(url);
setCurrentUser({ ...currentUser, avatar_url: url });
setAvatarStatus({ ok: true, msg: '✅ 头像已更新' });
} catch (err) {
setAvatarStatus({ ok: false, msg: '❌ ' + err.message });
}
};
const handleSave = async () => { const handleSave = async () => {
if (!currentUser) { alert('请先登录'); return; } if (!currentUser) { alert('请先登录'); return; }
@@ -24,27 +44,49 @@ export default function SettingsPage() {
} }
}; };
const avatarSrc = avatarUrl ||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') + '&background=6366f1&color=fff&size=128';
return ( return (
<div className="page-slide active"> <div className="page-slide active">
<div className="page-header" style={{ maxWidth: 400, margin: '0 auto', width: '100%' }}> <div className="page-header" style={{ maxWidth: 500, margin: '0 auto', width: '100%' }}>
<h2><Icon name="settings" size={20} /> 设置</h2> <h2><Icon name="settings" size={20} /> 设置</h2>
</div> </div>
<div style={{ maxWidth: 400, margin: '0 auto', width: '100%' }}> <div style={{ maxWidth: 500, margin: '0 auto', width: '100%', padding: '20px 0' }}>
<label style={{ fontWeight: 600, fontSize: 14 }}>用户名</label> {/* 头像 */}
<input <div style={{ textAlign: 'center', marginBottom: 24 }}>
type="text" <div style={{ position: 'relative', display: 'inline-block' }}>
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, margin: '6px 0 12px' }} <img src={avatarSrc} style={{ width: 100, height: 100, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
value={username} <button
onChange={(e) => setUsername(e.target.value)} style={{ position: 'absolute', bottom: 0, right: 0, background: 'var(--primary)', color: '#fff', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(99,102,241,0.4)' }}
/> onClick={() => avatarInputRef.current?.click()}
<label style={{ fontWeight: 600, fontSize: 14 }}>个人简介</label> >
<textarea 📷
rows={3} </button>
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, margin: '6px 0 12px' }} </div>
value={bio} <input type="file" ref={avatarInputRef} accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files?.[0]) handleAvatar(e.target.files[0]); }} />
onChange={(e) => setBio(e.target.value)} <h2 style={{ margin: '12px 0 4px' }}>{currentUser?.username}</h2>
/> <p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || '这个人很懒,什么都没写'}</p>
<button className="btn-primary" onClick={handleSave}>保存设置</button> {avatarStatus && (
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444' }}>{avatarStatus.msg}</div>
)}
</div>
{/* 基本资料 */}
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>用户名</label>
<input type="text" value={username} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setUsername(e.target.value)} />
</div>
<div style={{ marginBottom: 16 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>个人简介</label>
<textarea rows={3} value={bio} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }} onChange={(e) => setBio(e.target.value)} />
</div>
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>保存设置</button>
</div>
<AccountSecurity />
<RecoveryCodes />
</div> </div>
</div> </div>
); );
+86
View File
@@ -0,0 +1,86 @@
'use client';
// 管理后台 - 自定义页面管理(列表)
import { useEffect, useState } from 'react';
import { API } from '@/lib/api';
import CustomPageEditor from './CustomPageEditor';
export default function AdminCustomPages() {
const [pages, setPages] = useState(null);
const [error, setError] = useState(null);
const [editing, setEditing] = useState(null); // null | 'new' | page对象
const load = () => {
API.adminGetCustomPages()
.then((data) => { setPages(data || []); setError(null); })
.catch((e) => { setError(e.message); setPages([]); });
};
useEffect(load, []);
const handleDelete = async (p) => {
if (!confirm('确定要删除这个页面吗?')) return;
try {
await API.adminDeleteCustomPage(p.id);
load();
} catch (err) {
alert('删除失败:' + err.message);
}
};
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<h3 style={{ margin: 0 }}>📄 自定义页面</h3>
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}>➕ 添加页面</button>
</div>
<div id="customPageList">
{pages === null ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>
) : pages.length === 0 ? (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>暂无自定义页面</div>
) : (
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
<th style={{ padding: '8px 12px' }}>名称</th>
<th style={{ padding: '8px 12px' }}>标题</th>
<th style={{ padding: '8px 12px' }}>URL</th>
<th style={{ padding: '8px 12px' }}>状态</th>
<th style={{ padding: '8px 12px', textAlign: 'center' }}>操作</th>
</tr>
</thead>
<tbody>
{pages.map((p) => (
<tr key={p.id} style={{ borderBottom: '1px solid var(--border-light)' }}>
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>{p.name}</code></td>
<td style={{ padding: '8px 12px' }}>{p.title}</td>
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>?custom={p.name}</code></td>
<td style={{ padding: '8px 12px' }}>
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444' }}>{p.enabled ? '✅ 启用' : '❌ 禁用'}</span>
</td>
<td style={{ padding: '8px 12px', textAlign: 'center', display: 'flex', gap: 6, justifyContent: 'center' }}>
<button className="btn-sm btn-secondary" onClick={() => setEditing(p)}>✏️</button>
<button className="btn-sm btn-danger" onClick={() => handleDelete(p)}>🗑️</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{editing && (
<CustomPageEditor
page={editing === 'new' ? null : editing}
onClose={() => setEditing(null)}
onSaved={() => { setEditing(null); load(); }}
/>
)}
</>
);
}
+88
View File
@@ -0,0 +1,88 @@
'use client';
// 管理后台 - 自定义页面编辑器(modal)
import { useState } from 'react';
import { API } from '@/lib/api';
export default function CustomPageEditor({ page, onClose, onSaved }) {
const isEdit = !!page;
const [name, setName] = useState(page?.name || '');
const [title, setTitle] = useState(page?.title || '');
const [content, setContent] = useState(page?.content || '');
const [enabled, setEnabled] = useState(page?.enabled !== false);
const handleSave = async () => {
if (!name.trim()) { alert('请输入页面名称'); return; }
if (!title.trim()) { alert('请输入导航栏显示名称'); return; }
if (!content.trim()) { alert('请输入页面内容'); return; }
if (!/^[a-zA-Z0-9\-_]+$/.test(name.trim())) {
alert('页面名称只允许字母、数字、短横线和下划线');
return;
}
try {
if (isEdit) {
await API.adminUpdateCustomPage(page.id, title.trim(), content.trim(), enabled);
} else {
await API.adminCreateCustomPage(name.trim(), title.trim(), content.trim());
}
onSaved();
} catch (err) {
alert('保存失败:' + err.message);
}
};
return (
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<div className="modal-content" style={{ maxWidth: 600, maxHeight: '90vh', overflowY: 'auto', position: 'relative' }}>
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}>&times;</span>
<h2 style={{ marginBottom: 16 }}>{isEdit ? '✏️ 编辑页面' : '📄 添加页面'}</h2>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面名称</label>
<input
type="text"
value={name}
readOnly={isEdit}
placeholder="about (用于 URL: ?custom=about)"
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: isEdit ? 'var(--border-light)' : 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setName(e.target.value)}
/>
{isEdit
? <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>⚠️ 名称不可修改</div>
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>只允许字母、数字、短横线和下划线</div>}
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>导航栏显示名称</label>
<input
type="text"
value={title}
placeholder="关于我们"
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>状态</label>
<select
value={String(enabled)}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
onChange={(e) => setEnabled(e.target.value === 'true')}
>
<option value="true">启用</option>
<option value="false">禁用</option>
</select>
</div>
<div style={{ marginBottom: 12 }}>
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面内容(HTML + CSS + JS)</label>
<textarea
rows={12}
value={content}
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, fontFamily: 'monospace', background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }}
onChange={(e) => setContent(e.target.value)}
/>
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div>
</div>
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>保存</button>
</div>
</div>
);
}
+38
View File
@@ -57,6 +57,9 @@ export const API = {
createPost(title, content, images) { createPost(title, content, images) {
return apiFetch('/posts', { method: 'POST', body: JSON.stringify({ title, content, images: images || [] }) }); return apiFetch('/posts', { method: 'POST', body: JSON.stringify({ title, content, images: images || [] }) });
}, },
updatePost(postId, title, content) {
return apiFetch('/posts/' + postId, { method: 'PUT', body: JSON.stringify({ title, content }) });
},
deletePost(postId) { return apiFetch('/posts/' + postId, { method: 'DELETE' }); }, deletePost(postId) { return apiFetch('/posts/' + postId, { method: 'DELETE' }); },
// 回复 // 回复
@@ -75,6 +78,15 @@ export const API = {
updateProfile(userId, username, bio) { updateProfile(userId, username, bio) {
return apiFetch('/users/' + userId, { method: 'PUT', body: JSON.stringify({ username, bio }) }); return apiFetch('/users/' + userId, { method: 'PUT', body: JSON.stringify({ username, bio }) });
}, },
updateAvatar(userId, avatar_url) {
return apiFetch('/users/' + userId + '/avatar', { method: 'PUT', body: JSON.stringify({ avatar_url }) });
},
updatePassword(userId, oldPassword, newPassword) {
return apiFetch('/users/' + userId + '/password', { method: 'PUT', body: JSON.stringify({ oldPassword, newPassword }) });
},
updateEmail(userId, password, newEmail) {
return apiFetch('/users/' + userId + '/email', { method: 'PUT', body: JSON.stringify({ password, newEmail }) });
},
// 举报 // 举报
getReports() { return apiFetch('/reports'); }, getReports() { return apiFetch('/reports'); },
@@ -115,6 +127,32 @@ export const API = {
markMessageRead(messageId) { markMessageRead(messageId) {
return apiFetch('/messages/' + messageId + '/read', { method: 'PUT' }); return apiFetch('/messages/' + messageId + '/read', { method: 'PUT' });
}, },
// 自定义页面
getCustomPages() { return apiFetch('/custom-pages'); },
getCustomPage(name) { return apiFetch('/custom-pages/' + name); },
adminGetCustomPages() { return apiFetch('/admin/custom-pages'); },
adminCreateCustomPage(name, title, content) {
return apiFetch('/admin/custom-pages', { method: 'POST', body: JSON.stringify({ name, title, content }) });
},
adminUpdateCustomPage(id, title, content, enabled) {
return apiFetch('/admin/custom-pages/' + id, { method: 'PUT', body: JSON.stringify({ title, content, enabled }) });
},
adminDeleteCustomPage(id) {
return apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' });
},
// 通知
getNotifications() { return apiFetch('/notifications'); },
markNotificationRead(id) { return apiFetch('/notifications/' + id + '/read', { method: 'PUT' }); },
markAllNotificationsRead() { return apiFetch('/notifications/read-all', { method: 'PUT' }); },
// 恢复码
generateRecoveryCodes() { return apiFetch('/auth/recovery-codes/generate', { method: 'POST' }); },
getRecoveryCodeCount() { return apiFetch('/auth/recovery-codes/count'); },
resetPassword(email, recoveryCode, newPassword) {
return apiFetch('/auth/reset-password', { method: 'POST', body: JSON.stringify({ email, recoveryCode, newPassword }) });
},
}; };
// 图片上传 (multipart) // 图片上传 (multipart)
+50 -2
View File
@@ -18,7 +18,8 @@ CREATE TABLE IF NOT EXISTS posts (
content TEXT NOT NULL, content TEXT NOT NULL,
images TEXT[] DEFAULT '{}', images TEXT[] DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT now(), created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now() updated_at TIMESTAMPTZ DEFAULT now(),
edited_at TIMESTAMPTZ
); );
-- 回复表 -- 回复表
@@ -97,7 +98,8 @@ CREATE TABLE IF NOT EXISTS conversations (
user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
last_message_at TIMESTAMPTZ DEFAULT now(), last_message_at TIMESTAMPTZ DEFAULT now(),
created_at TIMESTAMPTZ DEFAULT now() created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE(user1_id, user2_id)
); );
CREATE TABLE IF NOT EXISTS messages ( CREATE TABLE IF NOT EXISTS messages (
@@ -112,3 +114,49 @@ CREATE TABLE IF NOT EXISTS messages (
CREATE INDEX IF NOT EXISTS idx_conversations_user1 ON conversations(user1_id); CREATE INDEX IF NOT EXISTS idx_conversations_user1 ON conversations(user1_id);
CREATE INDEX IF NOT EXISTS idx_conversations_user2 ON conversations(user2_id); CREATE INDEX IF NOT EXISTS idx_conversations_user2 ON conversations(user2_id);
CREATE INDEX IF NOT EXISTS idx_messages_conversation ON messages(conversation_id); CREATE INDEX IF NOT EXISTS idx_messages_conversation ON messages(conversation_id);
CREATE INDEX IF NOT EXISTS idx_messages_sender ON messages(sender_id);
-- ============================================================
-- 自定义页面表
-- ============================================================
CREATE TABLE IF NOT EXISTS custom_pages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(50) NOT NULL UNIQUE,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
enabled BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_custom_pages_name ON custom_pages(name);
-- ============================================================
-- 通知系统
-- ============================================================
CREATE TABLE IF NOT EXISTS notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(30) NOT NULL,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
link TEXT,
is_read BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(user_id);
CREATE INDEX IF NOT EXISTS idx_notifications_read ON notifications(is_read);
-- ============================================================
-- 恢复码系统(密码重置)
-- ============================================================
CREATE TABLE IF NOT EXISTS recovery_codes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash VARCHAR(255) NOT NULL,
is_used BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user ON recovery_codes(user_id);