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

+127
View File
@@ -0,0 +1,127 @@
// 前端 API 封装 (替代原 index.html 的 apiFetch + API 对象)
// 所有调用返回 JSON;HTTP 错误时抛出带 error 消息的 Error
const API_BASE_URL = '/api';
let token = null;
if (typeof window !== 'undefined') {
token = localStorage.getItem('forumlify-token') || null;
}
export function getToken() {
return token;
}
export function setToken(t) {
token = t;
if (t) localStorage.setItem('forumlify-token', t);
else localStorage.removeItem('forumlify-token');
}
async function apiFetch(path, options = {}) {
const headers = { ...(options.headers || {}) };
if (options.body && typeof options.body === 'string') {
headers['Content-Type'] = 'application/json';
}
if (token) headers['Authorization'] = 'Bearer ' + token;
const res = await fetch(API_BASE_URL + path, { ...options, headers });
const data = await res.json().catch(() => ({}));
if (!res.ok || data.error) {
const err = new Error(data.error || '请求失败');
err.status = res.status;
throw err;
}
return data;
}
export const API = {
// 认证
async login(email, password) {
const data = await apiFetch('/auth/login', { method: 'POST', body: JSON.stringify({ email, password }) });
if (data.token) setToken(data.token);
return data;
},
register(email, password, username) {
return apiFetch('/auth/register', { method: 'POST', body: JSON.stringify({ email, password, username }) });
},
logout() { setToken(null); },
getMe() { return apiFetch('/auth/me'); },
// 帖子
getPosts(sort) { return apiFetch('/posts?sort=' + (sort || 'latest')); },
getPost(postId) { return apiFetch('/posts/' + postId); },
createPost(title, content, images) {
return apiFetch('/posts', { method: 'POST', body: JSON.stringify({ title, content, images: images || [] }) });
},
deletePost(postId) { return apiFetch('/posts/' + postId, { method: 'DELETE' }); },
// 回复
getReplies(postId) { return apiFetch('/posts/' + postId + '/replies'); },
createReply(postId, content) {
return apiFetch('/posts/' + postId + '/replies', { method: 'POST', body: JSON.stringify({ content }) });
},
deleteReply(replyId) { return apiFetch('/replies/' + replyId, { method: 'DELETE' }); },
// 用户管理
getUsers() { return apiFetch('/users'); },
updateUserRole(userId, role) {
return apiFetch('/users/' + userId + '/role', { method: 'PUT', body: JSON.stringify({ role }) });
},
updateProfile(userId, username, bio) {
return apiFetch('/users/' + userId, { method: 'PUT', body: JSON.stringify({ username, bio }) });
},
// 举报
getReports() { return apiFetch('/reports'); },
createReport(postId, reason) {
return apiFetch('/reports', { method: 'POST', body: JSON.stringify({ post_id: postId, reason }) });
},
updateReport(reportId, status, note) {
return apiFetch('/reports/' + reportId, { method: 'PUT', body: JSON.stringify({ status, note }) });
},
// 统计 + 设置 + 友链
getStats() { return apiFetch('/stats'); },
getSettings() { return apiFetch('/settings'); },
updateSettings(forum_name) {
return apiFetch('/settings', { method: 'PUT', body: JSON.stringify({ forum_name }) });
},
getLinks() { return apiFetch('/links'); },
addLink(title, url) {
return apiFetch('/links', { method: 'POST', body: JSON.stringify({ title, url }) });
},
deleteLink(id) { return apiFetch('/links/' + id, { method: 'DELETE' }); },
// 事件日志
getEventLogs() { return apiFetch('/event-logs'); },
logEvent(action) {
return apiFetch('/event-logs', { method: 'POST', body: JSON.stringify({ action }) }).catch(() => {});
},
};
// 图片上传 (multipart)
export async function uploadImage(file) {
const fd = new FormData();
fd.append('file', file);
const headers = {};
if (token) headers['Authorization'] = 'Bearer ' + token;
const res = await fetch('/api/upload', { method: 'POST', body: fd, headers });
const data = await res.json().catch(() => ({}));
if (!res.ok || data.error) throw new Error(data.error || '上传失败');
return data.url;
}
// 验证码 (10以内加减法,与原实现一致)
export function generateCaptcha() {
let a = Math.floor(Math.random() * 9) + 1;
let b = Math.floor(Math.random() * 9) + 1;
let op = ['+', '-'][Math.floor(Math.random() * 2)];
if (op === '-' && a < b) { const t = a; a = b; b = t; }
return { question: a + ' ' + op + ' ' + b + ' = ?', answer: op === '+' ? a + b : a - b };
}
// 主题
export function getTheme() {
if (typeof window === 'undefined') return 'light';
return localStorage.getItem('forumlify-theme') || 'light';
}
+42
View File
@@ -0,0 +1,42 @@
// JWT 认证工具 (Route Handlers 共享)
import jwt from 'jsonwebtoken';
import pool from './db';
const JWT_SECRET = process.env.JWT_SECRET || 'forumlify-secret-key-change-me-in-production';
export { JWT_SECRET };
// 从 Next.js Request 提取 Bearer token,解析并返回用户 payload
export function getUser(req) {
const auth = req.headers.get('authorization') || '';
const token = auth.split(' ')[1];
if (!token) return null;
try {
return jwt.verify(token, JWT_SECRET);
} catch {
return null;
}
}
// 认证中间件:未登录返回 401
export async function requireAuth(req) {
const user = getUser(req);
if (!user) {
return { user: null, error: Response.json({ error: '请先登录' }, { status: 401 }) };
}
return { user, error: null };
}
// 管理员校验:非管理员返回 403
export async function requireAdmin(user) {
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
try {
const r = await pool.query('SELECT role FROM users WHERE id = $1', [user.id]);
if (r.rows[0]?.role !== 'admin') {
return Response.json({ error: '需要管理员权限' }, { status: 403 });
}
return null;
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}
+12
View File
@@ -0,0 +1,12 @@
// PostgreSQL 连接池单例 (Route Handlers 共享)
import { Pool } from 'pg';
const globalPool = globalThis.__forumlifyPool || new Pool({
connectionString: process.env.DATABASE_URL || 'postgresql://forumlify:123456@localhost:5432/forumlify',
});
if (process.env.NODE_ENV !== 'production') {
globalThis.__forumlifyPool = globalPool;
}
export default globalPool;