feat: migrate to Next.js 14 (App Router + Route Handlers)

- Replace Express server with Next.js Route Handlers (16 API routes)
- Rewrite index.html SPA as React components (feed, post, admin, modals)
- Move style.css to app/globals.css with dark/light themes intact
- Add lib/db.js, lib/auth.js (JWT), lib/api.js (client API wrapper)
- Server binds 0.0.0.0 by default; host/port configurable via config.js
- Uploads served via /api/uploads route (rewrite keeps /uploads/ URLs)
- Multi-stage dockerfile using standalone output
This commit is contained in:
lezi-fun committed 2026-08-09 17:02:11 +08:00
1 parent ef1318da66
commit 281460fb03
52 files changed
+2833 -3372

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
// POST /api/auth/login
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import pool from '@/lib/db';
import { JWT_SECRET } from '@/lib/auth';
export async function POST(req) {
const { email, password } = await req.json();
if (!email || !password) {
return Response.json({ error: '请填写邮箱和密码' }, { status: 400 });
}
try {
const r = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
const user = r.rows[0];
if (!user) {
return Response.json({ error: '邮箱或密码错误' }, { status: 401 });
}
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) {
return Response.json({ error: '邮箱或密码错误' }, { status: 401 });
}
const token = jwt.sign(
{ id: user.id, email: user.email, role: user.role },
JWT_SECRET,
{ expiresIn: '7d' }
);
return Response.json({
token,
user: {
id: user.id,
username: user.username,
avatar_url: user.avatar_url,
bio: user.bio,
role: user.role,
},
});
} catch {
return Response.json({ error: '登录失败,请稍后重试' }, { status: 500 });
}
}
+22
View File
@@ -0,0 +1,22 @@
// GET /api/auth/me
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, username, avatar_url, bio, role, created_at FROM users WHERE id = $1',
[user.id]
);
if (!r.rows[0]) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+38
View File
@@ -0,0 +1,38 @@
// POST /api/auth/register
import bcrypt from 'bcrypt';
import pool from '@/lib/db';
export async function POST(req) {
const { email, password, username } = await req.json();
if (!email || !password || !username) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
if (password.length < 6) {
return Response.json({ error: '密码至少6位' }, { status: 400 });
}
try {
const countResult = await pool.query('SELECT COUNT(*) FROM users');
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
const hash = await bcrypt.hash(password, 10);
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
const role = isFirstUser ? 'admin' : 'user';
const r = await pool.query(
`INSERT INTO users (email, password_hash, username, avatar_url, role)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, username, avatar_url, role, created_at`,
[email, hash, username, avatar, role]
);
return Response.json({
user: r.rows[0],
message: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功',
});
} catch (err) {
if (err.code === '23505') {
return Response.json({ error: '邮箱或用户名已被注册' }, { status: 400 });
}
return Response.json({ error: '注册失败,请稍后重试' }, { status: 500 });
}
}
+42
View File
@@ -0,0 +1,42 @@
// GET /api/event-logs, POST /api/event-logs
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export async function GET(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
try {
const r = await pool.query(
`SELECT el.*, u.username
FROM event_logs el
LEFT JOIN users u ON el.user_id = u.id
ORDER BY el.created_at DESC
LIMIT 100`
);
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 { action } = await req.json();
try {
await pool.query(
`INSERT INTO event_logs (user_id, action, ip)
VALUES ($1, $2, $3)`,
[user.id, action, req.headers.get('x-forwarded-for') || '0.0.0.0']
);
return Response.json({ success: true });
} catch {
return Response.json({ success: true });
}
}
+18
View File
@@ -0,0 +1,18 @@
// DELETE /api/links/[id]
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
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;
try {
await pool.query('DELETE FROM friendly_links WHERE id = $1', [params.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+37
View File
@@ -0,0 +1,37 @@
// GET /api/links, POST /api/links
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export async function GET() {
try {
const r = await pool.query('SELECT * FROM friendly_links ORDER BY sort_order');
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 { title, url } = await req.json();
if (!title || !url) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO friendly_links (title, url)
VALUES ($1, $2)
RETURNING *`,
[title, url]
);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '添加失败,请稍后重试' }, { status: 500 });
}
}
+42
View File
@@ -0,0 +1,42 @@
// GET /api/posts/[id]/replies, POST /api/posts/[id]/replies
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function GET(req, { params }) {
try {
const r = await pool.query(
`SELECT r.*, u.username, u.avatar_url
FROM replies r
JOIN users u ON r.user_id = u.id
WHERE r.post_id = $1
ORDER BY r.created_at ASC`,
[params.id]
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function POST(req, { params }) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { content } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写回复内容' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO replies (post_id, user_id, content)
VALUES ($1, $2, $3)
RETURNING *`,
[params.id, user.id, content]
);
await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [params.id]);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '回复失败,请稍后重试' }, { status: 500 });
}
}
+50
View File
@@ -0,0 +1,50 @@
// GET /api/posts/[id], DELETE /api/posts/[id]
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;
function invalidId() {
return Response.json({ error: '帖子不存在' }, { status: 404 });
}
export async function GET(req, { params }) {
if (!UUID_RE.test(params.id)) return invalidId();
try {
const r = await pool.query(
`SELECT p.*, u.username, u.avatar_url
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE p.id = $1`,
[params.id]
);
if (r.rows.length === 0) {
return invalidId();
}
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function DELETE(req, { params }) {
if (!UUID_RE.test(params.id)) return invalidId();
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
try {
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [params.id]);
if (post.rows.length === 0) {
return invalidId();
}
const u = await pool.query('SELECT role FROM users WHERE id = $1', [user.id]);
if (post.rows[0].user_id !== user.id && u.rows[0]?.role !== 'admin') {
return Response.json({ error: '无权限删除此帖子' }, { status: 403 });
}
await pool.query('DELETE FROM posts WHERE id = $1', [params.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+45
View File
@@ -0,0 +1,45 @@
// GET /api/posts, POST /api/posts
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
export async function GET(req) {
const url = new URL(req.url);
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
try {
const r = await pool.query(`
SELECT
p.*,
u.username,
u.avatar_url,
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
FROM posts p
JOIN users u ON p.user_id = u.id
ORDER BY ${sort} DESC
`);
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 { title, content, images } = await req.json();
if (!content || content.trim().length === 0) {
return Response.json({ error: '请填写内容' }, { status: 400 });
}
try {
const r = await pool.query(
`INSERT INTO posts (user_id, title, content, images)
VALUES ($1, $2, $3, $4)
RETURNING *`,
[user.id, title || '无标题', content, images || []]
);
return Response.json(r.rows[0]);
} catch {
return Response.json({ error: '发布失败,请稍后重试' }, { status: 500 });
}
}
+29
View File
@@ -0,0 +1,29 @@
// DELETE /api/replies/[id]
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 DELETE(req, { params }) {
if (!UUID_RE.test(params.id)) {
return Response.json({ error: '回复不存在' }, { status: 404 });
}
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
try {
const reply = await pool.query('SELECT user_id FROM replies WHERE id = $1', [params.id]);
if (reply.rows.length === 0) {
return Response.json({ error: '回复不存在' }, { status: 404 });
}
const u = await pool.query('SELECT role FROM users WHERE id = $1', [user.id]);
if (reply.rows[0].user_id !== user.id && u.rows[0]?.role !== 'admin') {
return Response.json({ error: '无权限删除此回复' }, { status: 403 });
}
await pool.query('DELETE FROM replies WHERE id = $1', [params.id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
}
}
+33
View File
@@ -0,0 +1,33 @@
// PUT /api/reports/[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 }) {
if (!UUID_RE.test(params.id)) {
return Response.json({ error: '操作失败,请稍后重试' }, { status: 404 });
}
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { status, note } = await req.json();
if (!['pending', 'approved', 'rejected'].includes(status)) {
return Response.json({ error: '无效的状态' }, { status: 400 });
}
try {
await pool.query(
`UPDATE reports
SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3
WHERE id = $4`,
[status, user.id, note || '', params.id]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
}
}
+55
View File
@@ -0,0 +1,55 @@
// GET /api/reports, POST /api/reports
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
r.*,
reporter.username as reporter_name,
handler.username as handler_name,
p.title as post_title,
p.content as post_content
FROM reports r
JOIN users reporter ON r.reporter_id = reporter.id
LEFT JOIN users handler ON r.handler_id = handler.id
LEFT JOIN posts p ON r.post_id = p.id
ORDER BY r.created_at DESC
`);
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 { post_id, reason } = await req.json();
if (!post_id || !reason) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
try {
const existing = await pool.query(
'SELECT id FROM reports WHERE post_id = $1 AND reporter_id = $2 AND status = $3',
[post_id, user.id, 'pending']
);
if (existing.rows.length > 0) {
return Response.json({ error: '你已经举报过此帖子,请等待处理' }, { status: 400 });
}
await pool.query(
`INSERT INTO reports (post_id, reporter_id, reason)
VALUES ($1, $2, $3)`,
[post_id, user.id, reason]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '举报失败,请稍后重试' }, { status: 500 });
}
}
+35
View File
@@ -0,0 +1,35 @@
// GET /api/settings, PUT /api/settings
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export async function GET() {
try {
const r = await pool.query('SELECT key, value FROM settings');
const settings = {};
r.rows.forEach((row) => { settings[row.key] = row.value; });
return Response.json(settings);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
export async function PUT(req) {
const user = getUser(req);
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { forum_name } = await req.json();
if (!forum_name || forum_name.trim().length === 0) {
return Response.json({ error: '论坛名称不能为空' }, { status: 400 });
}
try {
await pool.query(
`INSERT INTO settings (key, value) VALUES ($1, $2)
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
['forum_name', forum_name.trim()]
);
return Response.json({ success: true });
} catch {
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
}
}
+19
View File
@@ -0,0 +1,19 @@
// GET /api/stats
import pool from '@/lib/db';
export async function GET() {
try {
const [postsRes, usersRes] = await Promise.all([
pool.query('SELECT COUNT(*) FROM posts'),
pool.query('SELECT COUNT(*) FROM users'),
]);
return Response.json({
posts: parseInt(postsRes.rows[0].count) || 0,
users: parseInt(usersRes.rows[0].count) || 0,
topics: parseInt(postsRes.rows[0].count) || 0,
online: Math.floor(Math.random() * 20) + 5,
});
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+40
View File
@@ -0,0 +1,40 @@
// POST /api/upload — 图片上传 (multipart/form-data)
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';
import { getUser } from '@/lib/auth';
const ALLOWED = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const MAX_SIZE = 5 * 1024 * 1024;
export const runtime = 'nodejs';
export async function POST(req) {
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const form = await req.formData();
const file = form.get('file');
if (!file || typeof file === 'string') {
return Response.json({ error: '请选择图片' }, { status: 400 });
}
if (!ALLOWED.includes(file.type)) {
return Response.json({ error: '不支持的图片格式' }, { status: 400 });
}
if (file.size > MAX_SIZE) {
return Response.json({ error: '图片大小不能超过 5MB' }, { status: 400 });
}
try {
const ext = path.extname(file.name) || '.png';
const name = Date.now() + '-' + Math.round(Math.random() * 10000) + ext;
const dir = path.join(process.cwd(), 'uploads');
await mkdir(dir, { recursive: true });
const buffer = Buffer.from(await file.arrayBuffer());
await writeFile(path.join(dir, name), buffer);
return Response.json({ url: '/uploads/' + name });
} catch {
return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
}
}
+27
View File
@@ -0,0 +1,27 @@
// PUT /api/users/[id]/role (admin 改角色)
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export async function PUT(req, { params }) {
const { id } = params;
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
const { role } = await req.json();
if (!['user', 'admin'].includes(role)) {
return Response.json({ error: '无效的角色' }, { status: 400 });
}
if (id === user.id) {
return Response.json({ error: '不能修改自己的角色' }, { status: 400 });
}
try {
await pool.query('UPDATE users SET role = $1 WHERE id = $2', [role, id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+46
View File
@@ -0,0 +1,46 @@
// PUT /api/users/[id] (更新资料), PUT /api/users/[id]/role (改角色)
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
export async function PUT(req, { params }) {
const { id } = params;
const user = getUser(req);
if (!user) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const body = await req.json();
const { username, bio, role } = body;
// 改角色:仅管理员
if (role !== undefined) {
const forbidden = await requireAdmin(user);
if (forbidden) return forbidden;
if (!['user', 'admin'].includes(role)) {
return Response.json({ error: '无效的角色' }, { status: 400 });
}
if (id === user.id) {
return Response.json({ error: '不能修改自己的角色' }, { status: 400 });
}
try {
await pool.query('UPDATE users SET role = $1 WHERE id = $2', [role, id]);
return Response.json({ success: true });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
// 更新资料:仅本人
if (id !== user.id) {
return Response.json({ error: '无权限修改他人资料' }, { status: 403 });
}
try {
await pool.query('UPDATE users SET username = $1, bio = $2 WHERE id = $3', [username, bio || '', id]);
return Response.json({ success: true });
} catch (err) {
if (err.code === '23505') {
return Response.json({ error: '用户名已被占用' }, { status: 400 });
}
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+17
View File
@@ -0,0 +1,17 @@
// GET /api/users (admin)
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, username, avatar_url, bio, role, created_at FROM users ORDER BY created_at DESC'
);
return Response.json(r.rows);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+1140
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
// 全局布局
import './globals.css';
export const metadata = {
title: 'Forumlify',
description: 'Forumlify - 简洁优雅的现代社区系统',
};
export default function RootLayout({ children }) {
return (
<html lang="zh-CN" suppressHydrationWarning>
<body>{children}</body>
</html>
);
}
+59
View File
@@ -0,0 +1,59 @@
'use client';
// 主页:SPA 视图调度 (feed/post/new/admin/settings/messages)
import { useState } from 'react';
import AppProvider, { useApp } from '@/components/AppProvider';
import Navbar from '@/components/Navbar';
import Sidebar from '@/components/Sidebar';
import Feed from '@/components/Feed';
import PostDetail from '@/components/PostDetail';
import NewPost from '@/components/NewPost';
import AdminPage from '@/components/AdminPage';
import SettingsPage from '@/components/SettingsPage';
import Modals from '@/components/Modals';
function HomeInner() {
const { view, currentPostId } = useApp();
const [modal, setModal] = useState(null); // null | login | register | report
const [reportPostId, setReportPostId] = useState(null);
const openModal = (m) => setModal(m);
const openReport = (postId) => { setReportPostId(postId); setModal('report'); };
return (
<>
<Navbar onOpenModal={openModal} />
<div id="app" style={{ display: view === 'feed' ? 'flex' : 'none' }}>
<Sidebar />
<Feed onOpenModal={openModal} onReport={openReport} />
</div>
{/* 独立页面 */}
<div style={{ display: view !== 'feed' ? 'block' : 'none' }}>
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} />}
{view === 'new' && <NewPost />}
{view === 'admin' && <AdminPage />}
{view === 'settings' && <SettingsPage />}
{view === 'messages' && (
<div className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<h2>消息</h2>
</div>
<p style={{ color: '#94a3b8', padding: '20px 0', maxWidth: 700, margin: '0 auto', width: '100%' }}>暂无消息</p>
</div>
)}
</div>
<Modals modal={modal} onClose={() => setModal(null)} reportPostId={reportPostId} />
</>
);
}
export default function Home() {
return (
<AppProvider>
<HomeInner />
</AppProvider>
);
}