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:
1 parent
ef1318da66
commit
281460fb03
52 files changed
+2833
-3372
No files matched your search
+42
@@ -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 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user