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
@@ -1,4 +1,6 @@
|
||||
node_modules/
|
||||
.next/
|
||||
out/
|
||||
uploads/
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
## ✨ 特性
|
||||
|
||||
- 🎨 精致简约的界面设计,支持亮色/暗色模式
|
||||
- ⚡️ 轻量快速,无需复杂配置
|
||||
- ⚡️ 基于 Next.js 14 (App Router) + React 18,前后端一体化
|
||||
- 🔐 自带用户认证(JWT)
|
||||
- 📝 发帖、回复、举报、管理后台
|
||||
- 🐳 Docker 一键部署
|
||||
@@ -21,12 +21,7 @@ cd forumlify
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
应用默认运行在 `http://localhost:3003`。
|
||||
|
||||
---
|
||||
以下内容添加自NodeLoc @Lezi-fun的PR
|
||||
|
||||
---
|
||||
应用默认运行在 `http://localhost:3000`(监听 `0.0.0.0`,局域网可访问)。
|
||||
|
||||
### 从源码构建
|
||||
|
||||
@@ -34,7 +29,7 @@ docker-compose up -d
|
||||
|
||||
#### 环境要求
|
||||
|
||||
- Node.js 18+
|
||||
- Node.js 18.17+(Next.js 14 要求)
|
||||
- PostgreSQL 13+(`schema.sql` 使用了内置的 `gen_random_uuid()`)
|
||||
|
||||
#### 步骤
|
||||
@@ -62,7 +57,6 @@ psql -U forumlify -d forumlify -f schema.sql
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `DATABASE_URL` | `postgresql://forumlify:123456@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
||||
| `PORT` | `3000` | HTTP 监听端口 |
|
||||
| `JWT_SECRET` | `forumlify-secret-key-change-me-in-production` | JWT 签名密钥,**生产环境务必修改** |
|
||||
|
||||
```bash
|
||||
@@ -71,23 +65,25 @@ export DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
|
||||
export JWT_SECRET=your-own-secret-key
|
||||
```
|
||||
|
||||
4. **启动**
|
||||
4. **构建并启动**
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。
|
||||
|
||||
#### 前端配置
|
||||
开发模式(热更新):`npm run dev`。
|
||||
|
||||
前端页面为 `index.html`,相关行为可在 `config.js` 中调整:
|
||||
#### 服务端配置
|
||||
|
||||
监听端口与地址可在 `config.js` 中调整(服务端读取,浏览器端忽略):
|
||||
|
||||
| 配置项 | 默认值 | 说明 |
|
||||
|--------|--------|------|
|
||||
| `FORUM_NAME` | `Forumlify` | 论坛名称(左上角显示) |
|
||||
| `ENABLE_CAPTCHA` | `true` | 发帖/注册的人机验证(10 以内加减法) |
|
||||
| `SERVER_PORT` | `null` | 可选:服务端监听端口(仅服务端读取,浏览器端忽略)。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000`。设为 `null` 时使用环境变量或默认值 |
|
||||
| `SERVER_PORT` | `null` | 可选:监听端口。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000` |
|
||||
| `SERVER_HOST` | `null` | 可选:监听地址。优先级:环境变量 `HOST` > `SERVER_HOST` > 默认 `0.0.0.0`(所有网卡)。设为 `127.0.0.1` 仅本机访问 |
|
||||
|
||||
#### 上传目录
|
||||
|
||||
@@ -96,3 +92,34 @@ npm start
|
||||
```bash
|
||||
mkdir -p uploads && chmod 755 uploads
|
||||
```
|
||||
|
||||
## 🏗️ 项目结构
|
||||
|
||||
```
|
||||
app/
|
||||
page.js # 主页(SPA 视图调度)
|
||||
layout.js # 全局布局
|
||||
globals.css # 全局样式(含亮/暗主题)
|
||||
api/ # Route Handlers(API 后端)
|
||||
auth/ posts/ replies/ users/ reports/ links/
|
||||
stats/ event-logs/ settings/ upload/ uploads/
|
||||
components/
|
||||
AppProvider.js # 全局状态(用户/主题/路由)
|
||||
Navbar.js Feed.js PostDetail.js ReplyList.js
|
||||
NewPost.js AdminPage.js SettingsPage.js Modals.js
|
||||
lib/
|
||||
db.js # PostgreSQL 连接池
|
||||
auth.js # JWT 认证工具
|
||||
api.js # 前端 API 封装
|
||||
scripts/
|
||||
start.js # 启动入口(读取 config.js 监听配置)
|
||||
schema.sql # 数据库表结构
|
||||
config.js # 服务端配置(端口/地址)
|
||||
```
|
||||
|
||||
## 📚 技术栈
|
||||
|
||||
- Next.js 14 (App Router) + React 18
|
||||
- Express 风格 Route Handlers (Node.js Runtime)
|
||||
- PostgreSQL + pg
|
||||
- JWT 认证 + bcrypt 密码哈希
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -1104,11 +1104,7 @@ svg {
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.forum-name {
|
||||
font-size:
|
||||
|
||||
/* ===== 独立页面内容居中 ===== */
|
||||
/* ===== 独立页面内容居中 ===== */
|
||||
.page-slide .page-header,
|
||||
.page-slide > div,
|
||||
#postDetailContent,
|
||||
@@ -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
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "forumlify",
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"next": "^14.2.15",
|
||||
"pg": "^8.11.3",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@mapbox/node-pre-gyp": ["@mapbox/node-pre-gyp@1.0.11", "https://registry.npmmirror.com/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", { "dependencies": { "detect-libc": "^2.0.0", "https-proxy-agent": "^5.0.0", "make-dir": "^3.1.0", "node-fetch": "^2.6.7", "nopt": "^5.0.0", "npmlog": "^5.0.1", "rimraf": "^3.0.2", "semver": "^7.3.5", "tar": "^6.1.11" }, "bin": { "node-pre-gyp": "bin/node-pre-gyp" } }, "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ=="],
|
||||
|
||||
"@next/env": ["@next/env@14.2.35", "", {}, "sha512-DuhvCtj4t9Gwrx80dmz2F4t/zKQ4ktN8WrMwOuVzkJfBilwAwGr6v16M5eI8yCuZ63H9TTuEU09Iu2HqkzFPVQ=="],
|
||||
|
||||
"@next/swc-darwin-arm64": ["@next/swc-darwin-arm64@14.2.33", "", { "os": "darwin", "cpu": "arm64" }, "sha512-HqYnb6pxlsshoSTubdXKu15g3iivcbsMXg4bYpjL2iS/V6aQot+iyF4BUc2qA/J/n55YtvE4PHMKWBKGCF/+wA=="],
|
||||
|
||||
"@next/swc-darwin-x64": ["@next/swc-darwin-x64@14.2.33", "", { "os": "darwin", "cpu": "x64" }, "sha512-8HGBeAE5rX3jzKvF593XTTFg3gxeU4f+UWnswa6JPhzaR6+zblO5+fjltJWIZc4aUalqTclvN2QtTC37LxvZAA=="],
|
||||
|
||||
"@next/swc-linux-arm64-gnu": ["@next/swc-linux-arm64-gnu@14.2.33", "", { "os": "linux", "cpu": "arm64" }, "sha512-JXMBka6lNNmqbkvcTtaX8Gu5by9547bukHQvPoLe9VRBx1gHwzf5tdt4AaezW85HAB3pikcvyqBToRTDA4DeLw=="],
|
||||
|
||||
"@next/swc-linux-arm64-musl": ["@next/swc-linux-arm64-musl@14.2.33", "", { "os": "linux", "cpu": "arm64" }, "sha512-Bm+QulsAItD/x6Ih8wGIMfRJy4G73tu1HJsrccPW6AfqdZd0Sfm5Imhgkgq2+kly065rYMnCOxTBvmvFY1BKfg=="],
|
||||
|
||||
"@next/swc-linux-x64-gnu": ["@next/swc-linux-x64-gnu@14.2.33", "", { "os": "linux", "cpu": "x64" }, "sha512-FnFn+ZBgsVMbGDsTqo8zsnRzydvsGV8vfiWwUo1LD8FTmPTdV+otGSWKc4LJec0oSexFnCYVO4hX8P8qQKaSlg=="],
|
||||
|
||||
"@next/swc-linux-x64-musl": ["@next/swc-linux-x64-musl@14.2.33", "", { "os": "linux", "cpu": "x64" }, "sha512-345tsIWMzoXaQndUTDv1qypDRiebFxGYx9pYkhwY4hBRaOLt8UGfiWKr9FSSHs25dFIf8ZqIFaPdy5MljdoawA=="],
|
||||
|
||||
"@next/swc-win32-arm64-msvc": ["@next/swc-win32-arm64-msvc@14.2.33", "", { "os": "win32", "cpu": "arm64" }, "sha512-nscpt0G6UCTkrT2ppnJnFsYbPDQwmum4GNXYTeoTIdsmMydSKFz9Iny2jpaRupTb+Wl298+Rh82WKzt9LCcqSQ=="],
|
||||
|
||||
"@next/swc-win32-ia32-msvc": ["@next/swc-win32-ia32-msvc@14.2.33", "https://registry.npmmirror.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.33.tgz", { "os": "win32", "cpu": "ia32" }, "sha512-pc9LpGNKhJ0dXQhZ5QMmYxtARwwmWLpeocFmVG5Z0DzWq5Uf0izcI8tLc+qOpqxO1PWqZ5A7J1blrUIKrIFc7Q=="],
|
||||
|
||||
"@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@14.2.33", "", { "os": "win32", "cpu": "x64" }, "sha512-nOjfZMy8B94MdisuzZo9/57xuFVLHJaDj5e/xrduJp9CV2/HrfxTRH2fbyLe+K9QT41WBLUd4iXX3R7jBp0EUg=="],
|
||||
|
||||
"@swc/counter": ["@swc/counter@0.1.3", "https://registry.npmmirror.com/@swc/counter/-/counter-0.1.3.tgz", {}, "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ=="],
|
||||
|
||||
"@swc/helpers": ["@swc/helpers@0.5.5", "", { "dependencies": { "@swc/counter": "^0.1.3", "tslib": "^2.4.0" } }, "sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A=="],
|
||||
|
||||
"abbrev": ["abbrev@1.1.1", "https://registry.npmmirror.com/abbrev/-/abbrev-1.1.1.tgz", {}, "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q=="],
|
||||
|
||||
"agent-base": ["agent-base@6.0.2", "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="],
|
||||
|
||||
"ansi-regex": ["ansi-regex@5.0.1", "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
|
||||
|
||||
"aproba": ["aproba@2.1.0", "https://registry.npmmirror.com/aproba/-/aproba-2.1.0.tgz", {}, "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew=="],
|
||||
|
||||
"are-we-there-yet": ["are-we-there-yet@2.0.0", "https://registry.npmmirror.com/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", { "dependencies": { "delegates": "^1.0.0", "readable-stream": "^3.6.0" } }, "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw=="],
|
||||
|
||||
"balanced-match": ["balanced-match@1.0.2", "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
|
||||
"bcrypt": ["bcrypt@5.1.1", "https://registry.npmmirror.com/bcrypt/-/bcrypt-5.1.1.tgz", { "dependencies": { "@mapbox/node-pre-gyp": "^1.0.11", "node-addon-api": "^5.0.0" } }, "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww=="],
|
||||
|
||||
"brace-expansion": ["brace-expansion@1.1.18", "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-1.1.18.tgz", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
|
||||
|
||||
"buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "https://registry.npmmirror.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],
|
||||
|
||||
"busboy": ["busboy@1.6.0", "https://registry.npmmirror.com/busboy/-/busboy-1.6.0.tgz", { "dependencies": { "streamsearch": "^1.1.0" } }, "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA=="],
|
||||
|
||||
"caniuse-lite": ["caniuse-lite@1.0.30001809", "https://registry.npmmirror.com/caniuse-lite/-/caniuse-lite-1.0.30001809.tgz", {}, "sha512-xxWVywk6a6Arlk+hymeycyn/VgqEfLDxupvhH/xiY5SJ/18kmi9o6MiO320DCUzypORHLtvh0I4i04tUhCNHNQ=="],
|
||||
|
||||
"chownr": ["chownr@2.0.0", "https://registry.npmmirror.com/chownr/-/chownr-2.0.0.tgz", {}, "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ=="],
|
||||
|
||||
"client-only": ["client-only@0.0.1", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="],
|
||||
|
||||
"color-support": ["color-support@1.1.3", "https://registry.npmmirror.com/color-support/-/color-support-1.1.3.tgz", { "bin": { "color-support": "bin.js" } }, "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg=="],
|
||||
|
||||
"concat-map": ["concat-map@0.0.1", "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
|
||||
|
||||
"console-control-strings": ["console-control-strings@1.1.0", "https://registry.npmmirror.com/console-control-strings/-/console-control-strings-1.1.0.tgz", {}, "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"delegates": ["delegates@1.0.0", "https://registry.npmmirror.com/delegates/-/delegates-1.0.0.tgz", {}, "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ=="],
|
||||
|
||||
"detect-libc": ["detect-libc@2.1.2", "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
|
||||
|
||||
"ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "https://registry.npmmirror.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@8.0.0", "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
"fs-minipass": ["fs-minipass@2.1.0", "https://registry.npmmirror.com/fs-minipass/-/fs-minipass-2.1.0.tgz", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg=="],
|
||||
|
||||
"fs.realpath": ["fs.realpath@1.0.0", "https://registry.npmmirror.com/fs.realpath/-/fs.realpath-1.0.0.tgz", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="],
|
||||
|
||||
"gauge": ["gauge@3.0.2", "https://registry.npmmirror.com/gauge/-/gauge-3.0.2.tgz", { "dependencies": { "aproba": "^1.0.3 || ^2.0.0", "color-support": "^1.1.2", "console-control-strings": "^1.0.0", "has-unicode": "^2.0.1", "object-assign": "^4.1.1", "signal-exit": "^3.0.0", "string-width": "^4.2.3", "strip-ansi": "^6.0.1", "wide-align": "^1.1.2" } }, "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q=="],
|
||||
|
||||
"glob": ["glob@7.2.3", "https://registry.npmmirror.com/glob/-/glob-7.2.3.tgz", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
|
||||
|
||||
"graceful-fs": ["graceful-fs@4.2.11", "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
|
||||
|
||||
"has-unicode": ["has-unicode@2.0.1", "https://registry.npmmirror.com/has-unicode/-/has-unicode-2.0.1.tgz", {}, "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ=="],
|
||||
|
||||
"https-proxy-agent": ["https-proxy-agent@5.0.1", "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="],
|
||||
|
||||
"inflight": ["inflight@1.0.6", "https://registry.npmmirror.com/inflight/-/inflight-1.0.6.tgz", { "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA=="],
|
||||
|
||||
"inherits": ["inherits@2.0.4", "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
|
||||
|
||||
"js-tokens": ["js-tokens@4.0.0", "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
||||
|
||||
"jsonwebtoken": ["jsonwebtoken@9.0.3", "https://registry.npmmirror.com/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],
|
||||
|
||||
"jwa": ["jwa@2.0.1", "https://registry.npmmirror.com/jwa/-/jwa-2.0.1.tgz", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],
|
||||
|
||||
"jws": ["jws@4.0.1", "https://registry.npmmirror.com/jws/-/jws-4.0.1.tgz", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],
|
||||
|
||||
"lodash.includes": ["lodash.includes@4.3.0", "https://registry.npmmirror.com/lodash.includes/-/lodash.includes-4.3.0.tgz", {}, "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="],
|
||||
|
||||
"lodash.isboolean": ["lodash.isboolean@3.0.3", "https://registry.npmmirror.com/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", {}, "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="],
|
||||
|
||||
"lodash.isinteger": ["lodash.isinteger@4.0.4", "https://registry.npmmirror.com/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", {}, "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="],
|
||||
|
||||
"lodash.isnumber": ["lodash.isnumber@3.0.3", "https://registry.npmmirror.com/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", {}, "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="],
|
||||
|
||||
"lodash.isplainobject": ["lodash.isplainobject@4.0.6", "https://registry.npmmirror.com/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", {}, "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="],
|
||||
|
||||
"lodash.isstring": ["lodash.isstring@4.0.1", "https://registry.npmmirror.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz", {}, "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="],
|
||||
|
||||
"lodash.once": ["lodash.once@4.1.1", "https://registry.npmmirror.com/lodash.once/-/lodash.once-4.1.1.tgz", {}, "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="],
|
||||
|
||||
"loose-envify": ["loose-envify@1.4.0", "https://registry.npmmirror.com/loose-envify/-/loose-envify-1.4.0.tgz", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],
|
||||
|
||||
"make-dir": ["make-dir@3.1.0", "https://registry.npmmirror.com/make-dir/-/make-dir-3.1.0.tgz", { "dependencies": { "semver": "^6.0.0" } }, "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw=="],
|
||||
|
||||
"minimatch": ["minimatch@3.1.5", "https://registry.npmmirror.com/minimatch/-/minimatch-3.1.5.tgz", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
|
||||
|
||||
"minipass": ["minipass@5.0.0", "https://registry.npmmirror.com/minipass/-/minipass-5.0.0.tgz", {}, "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ=="],
|
||||
|
||||
"minizlib": ["minizlib@2.1.2", "https://registry.npmmirror.com/minizlib/-/minizlib-2.1.2.tgz", { "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" } }, "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg=="],
|
||||
|
||||
"mkdirp": ["mkdirp@1.0.4", "https://registry.npmmirror.com/mkdirp/-/mkdirp-1.0.4.tgz", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="],
|
||||
|
||||
"ms": ["ms@2.1.3", "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"nanoid": ["nanoid@3.3.18", "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.18.tgz", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],
|
||||
|
||||
"next": ["next@14.2.35", "https://registry.npmmirror.com/next/-/next-14.2.35.tgz", { "dependencies": { "@next/env": "14.2.35", "@swc/helpers": "0.5.5", "busboy": "1.6.0", "caniuse-lite": "^1.0.30001579", "graceful-fs": "^4.2.11", "postcss": "8.4.31", "styled-jsx": "5.1.1" }, "optionalDependencies": { "@next/swc-darwin-arm64": "14.2.33", "@next/swc-darwin-x64": "14.2.33", "@next/swc-linux-arm64-gnu": "14.2.33", "@next/swc-linux-arm64-musl": "14.2.33", "@next/swc-linux-x64-gnu": "14.2.33", "@next/swc-linux-x64-musl": "14.2.33", "@next/swc-win32-arm64-msvc": "14.2.33", "@next/swc-win32-ia32-msvc": "14.2.33", "@next/swc-win32-x64-msvc": "14.2.33" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.41.2", "react": "^18.2.0", "react-dom": "^18.2.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-KhYd2Hjt/O1/1aZVX3dCwGXM1QmOV4eNM2UTacK5gipDdPN/oHHK/4oVGy7X8GMfPMsUTUEmGlsy0EY1YGAkig=="],
|
||||
|
||||
"node-addon-api": ["node-addon-api@5.1.0", "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-5.1.0.tgz", {}, "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="],
|
||||
|
||||
"node-fetch": ["node-fetch@2.7.0", "https://registry.npmmirror.com/node-fetch/-/node-fetch-2.7.0.tgz", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
|
||||
|
||||
"nopt": ["nopt@5.0.0", "https://registry.npmmirror.com/nopt/-/nopt-5.0.0.tgz", { "dependencies": { "abbrev": "1" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ=="],
|
||||
|
||||
"npmlog": ["npmlog@5.0.1", "https://registry.npmmirror.com/npmlog/-/npmlog-5.0.1.tgz", { "dependencies": { "are-we-there-yet": "^2.0.0", "console-control-strings": "^1.1.0", "gauge": "^3.0.0", "set-blocking": "^2.0.0" } }, "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw=="],
|
||||
|
||||
"object-assign": ["object-assign@4.1.1", "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
|
||||
|
||||
"once": ["once@1.4.0", "https://registry.npmmirror.com/once/-/once-1.4.0.tgz", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||
|
||||
"path-is-absolute": ["path-is-absolute@1.0.1", "https://registry.npmmirror.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="],
|
||||
|
||||
"pg": ["pg@8.23.0", "https://registry.npmmirror.com/pg/-/pg-8.23.0.tgz", { "dependencies": { "pg-connection-string": "^2.14.0", "pg-pool": "^3.14.0", "pg-protocol": "^1.16.0", "pg-types": "2.2.0", "pgpass": "1.0.5" }, "optionalDependencies": { "pg-cloudflare": "^1.4.0" }, "peerDependencies": { "pg-native": ">=3.0.1" }, "optionalPeers": ["pg-native"] }, "sha512-Ip2EQCngowJLGOfCwkFhPXU7/ljlhn6Rxlmy4XYfL2Y+vyRM59+8uR2xqRWKdYmbXmxCFOAmKxBuSUCdF34qLg=="],
|
||||
|
||||
"pg-cloudflare": ["pg-cloudflare@1.4.0", "https://registry.npmmirror.com/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz", {}, "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A=="],
|
||||
|
||||
"pg-connection-string": ["pg-connection-string@2.14.0", "https://registry.npmmirror.com/pg-connection-string/-/pg-connection-string-2.14.0.tgz", {}, "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg=="],
|
||||
|
||||
"pg-int8": ["pg-int8@1.0.1", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="],
|
||||
|
||||
"pg-pool": ["pg-pool@3.14.0", "https://registry.npmmirror.com/pg-pool/-/pg-pool-3.14.0.tgz", { "peerDependencies": { "pg": ">=8.0" } }, "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw=="],
|
||||
|
||||
"pg-protocol": ["pg-protocol@1.16.0", "https://registry.npmmirror.com/pg-protocol/-/pg-protocol-1.16.0.tgz", {}, "sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg=="],
|
||||
|
||||
"pg-types": ["pg-types@2.2.0", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="],
|
||||
|
||||
"pgpass": ["pgpass@1.0.5", "", { "dependencies": { "split2": "^4.1.0" } }, "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug=="],
|
||||
|
||||
"picocolors": ["picocolors@1.1.1", "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
|
||||
"postcss": ["postcss@8.4.31", "https://registry.npmmirror.com/postcss/-/postcss-8.4.31.tgz", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],
|
||||
|
||||
"postgres-array": ["postgres-array@2.0.0", "https://registry.npmmirror.com/postgres-array/-/postgres-array-2.0.0.tgz", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
|
||||
|
||||
"postgres-bytea": ["postgres-bytea@1.0.1", "https://registry.npmmirror.com/postgres-bytea/-/postgres-bytea-1.0.1.tgz", {}, "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ=="],
|
||||
|
||||
"postgres-date": ["postgres-date@1.0.7", "https://registry.npmmirror.com/postgres-date/-/postgres-date-1.0.7.tgz", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="],
|
||||
|
||||
"postgres-interval": ["postgres-interval@1.2.0", "https://registry.npmmirror.com/postgres-interval/-/postgres-interval-1.2.0.tgz", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="],
|
||||
|
||||
"react": ["react@18.3.1", "https://registry.npmmirror.com/react/-/react-18.3.1.tgz", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ=="],
|
||||
|
||||
"react-dom": ["react-dom@18.3.1", "https://registry.npmmirror.com/react-dom/-/react-dom-18.3.1.tgz", { "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" }, "peerDependencies": { "react": "^18.3.1" } }, "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw=="],
|
||||
|
||||
"readable-stream": ["readable-stream@3.6.2", "https://registry.npmmirror.com/readable-stream/-/readable-stream-3.6.2.tgz", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
|
||||
|
||||
"rimraf": ["rimraf@3.0.2", "https://registry.npmmirror.com/rimraf/-/rimraf-3.0.2.tgz", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="],
|
||||
|
||||
"safe-buffer": ["safe-buffer@5.2.1", "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.2.1.tgz", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"scheduler": ["scheduler@0.23.2", "https://registry.npmmirror.com/scheduler/-/scheduler-0.23.2.tgz", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ=="],
|
||||
|
||||
"semver": ["semver@7.8.5", "https://registry.npmmirror.com/semver/-/semver-7.8.5.tgz", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
|
||||
|
||||
"set-blocking": ["set-blocking@2.0.0", "https://registry.npmmirror.com/set-blocking/-/set-blocking-2.0.0.tgz", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="],
|
||||
|
||||
"signal-exit": ["signal-exit@3.0.7", "https://registry.npmmirror.com/signal-exit/-/signal-exit-3.0.7.tgz", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
|
||||
|
||||
"source-map-js": ["source-map-js@1.2.1", "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
|
||||
"split2": ["split2@4.2.0", "https://registry.npmmirror.com/split2/-/split2-4.2.0.tgz", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],
|
||||
|
||||
"streamsearch": ["streamsearch@1.1.0", "https://registry.npmmirror.com/streamsearch/-/streamsearch-1.1.0.tgz", {}, "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg=="],
|
||||
|
||||
"string-width": ["string-width@4.2.3", "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"string_decoder": ["string_decoder@1.3.0", "https://registry.npmmirror.com/string_decoder/-/string_decoder-1.3.0.tgz", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
|
||||
|
||||
"strip-ansi": ["strip-ansi@6.0.1", "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"styled-jsx": ["styled-jsx@5.1.1", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0" } }, "sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw=="],
|
||||
|
||||
"tar": ["tar@6.2.1", "https://registry.npmmirror.com/tar/-/tar-6.2.1.tgz", { "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" } }, "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A=="],
|
||||
|
||||
"tr46": ["tr46@0.0.3", "https://registry.npmmirror.com/tr46/-/tr46-0.0.3.tgz", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],
|
||||
|
||||
"tslib": ["tslib@2.8.1", "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||
|
||||
"util-deprecate": ["util-deprecate@1.0.2", "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"webidl-conversions": ["webidl-conversions@3.0.1", "https://registry.npmmirror.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
|
||||
|
||||
"whatwg-url": ["whatwg-url@5.0.0", "https://registry.npmmirror.com/whatwg-url/-/whatwg-url-5.0.0.tgz", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
|
||||
|
||||
"wide-align": ["wide-align@1.1.5", "https://registry.npmmirror.com/wide-align/-/wide-align-1.1.5.tgz", { "dependencies": { "string-width": "^1.0.2 || 2 || 3 || 4" } }, "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg=="],
|
||||
|
||||
"wrappy": ["wrappy@1.0.2", "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
|
||||
|
||||
"xtend": ["xtend@4.0.2", "https://registry.npmmirror.com/xtend/-/xtend-4.0.2.tgz", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
|
||||
|
||||
"yallist": ["yallist@4.0.0", "https://registry.npmmirror.com/yallist/-/yallist-4.0.0.tgz", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
|
||||
|
||||
"fs-minipass/minipass": ["minipass@3.3.6", "https://registry.npmmirror.com/minipass/-/minipass-3.3.6.tgz", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"make-dir/semver": ["semver@6.3.1", "https://registry.npmmirror.com/semver/-/semver-6.3.1.tgz", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"minizlib/minipass": ["minipass@3.3.6", "https://registry.npmmirror.com/minipass/-/minipass-3.3.6.tgz", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台:5 个 tab
|
||||
import { useState } from 'react';
|
||||
import AdminReports from './admin/AdminReports';
|
||||
import AdminUsers from './admin/AdminUsers';
|
||||
import AdminLogs from './admin/AdminLogs';
|
||||
import AdminLinks from './admin/AdminLinks';
|
||||
import AdminForumSettings from './admin/AdminForumSettings';
|
||||
|
||||
const TABS = [
|
||||
{ key: 'reports', label: '举报' },
|
||||
{ key: 'users', label: '用户' },
|
||||
{ key: 'logs', label: '日志' },
|
||||
{ key: 'links', label: '友链' },
|
||||
{ key: 'settings', label: '论坛设置' },
|
||||
];
|
||||
|
||||
export default function AdminPage() {
|
||||
const [tab, setTab] = useState('reports');
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 900, margin: '0 auto', width: '100%' }}>
|
||||
<h2>管理后台</h2>
|
||||
</div>
|
||||
<div className="admin-tabs" style={{ maxWidth: 900, margin: '0 auto', width: '100%' }}>
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
className={'admin-tab' + (tab === t.key ? ' active' : '')}
|
||||
onClick={() => setTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div id="adminContent" style={{ maxWidth: 900, margin: '0 auto', width: '100%' }}>
|
||||
{tab === 'reports' && <AdminReports />}
|
||||
{tab === 'users' && <AdminUsers />}
|
||||
{tab === 'logs' && <AdminLogs />}
|
||||
{tab === 'links' && <AdminLinks />}
|
||||
{tab === 'settings' && <AdminForumSettings />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
'use client';
|
||||
|
||||
// 全局状态 Provider:用户、主题、论坛名、当前视图(feed/post/new/admin/...)
|
||||
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { API, getTheme, setToken, getToken } from '@/lib/api';
|
||||
|
||||
const AppContext = createContext(null);
|
||||
|
||||
export function useApp() {
|
||||
return useContext(AppContext);
|
||||
}
|
||||
|
||||
export default function AppProvider({ children }) {
|
||||
const [currentUser, setCurrentUser] = useState(null);
|
||||
const [forumName, setForumName] = useState('Forumlify');
|
||||
const [theme, setThemeState] = useState('light');
|
||||
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages
|
||||
const [currentPostId, setCurrentPostId] = useState(null);
|
||||
const [sort, setSort] = useState('latest');
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
const loadedRef = useRef(false);
|
||||
|
||||
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
|
||||
|
||||
// 主题
|
||||
useEffect(() => {
|
||||
const t = getTheme();
|
||||
setThemeState(t);
|
||||
document.documentElement.setAttribute('data-theme', t);
|
||||
}, []);
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
setThemeState((prev) => {
|
||||
const next = prev === 'light' ? 'dark' : 'light';
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
localStorage.setItem('forumlify-theme', next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 初始化:恢复登录、加载论坛名
|
||||
useEffect(() => {
|
||||
if (loadedRef.current) return;
|
||||
loadedRef.current = true;
|
||||
|
||||
async function init() {
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
try {
|
||||
const user = await API.getMe();
|
||||
setCurrentUser(user);
|
||||
API.logEvent('login').catch(() => {});
|
||||
} catch {
|
||||
setToken(null);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const s = await API.getSettings();
|
||||
if (s.forum_name) setForumName(s.forum_name);
|
||||
} catch { /* 用默认名 */ }
|
||||
}
|
||||
init();
|
||||
}, []);
|
||||
|
||||
// 按 URL 参数初始化视图
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const postParam = params.get('post');
|
||||
const pageParam = params.get('page');
|
||||
if (postParam) {
|
||||
setView('post');
|
||||
setCurrentPostId(postParam);
|
||||
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
|
||||
setView(pageParam);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 视图切换:同步 URL (pushState,模拟原 SPA 行为)
|
||||
const navigate = useCallback((page) => {
|
||||
const url = new URL(window.location);
|
||||
if (page === 'feed') {
|
||||
url.searchParams.delete('page');
|
||||
url.searchParams.delete('post');
|
||||
} else {
|
||||
url.searchParams.set('page', page);
|
||||
url.searchParams.delete('post');
|
||||
}
|
||||
window.history.pushState({ page }, '', url);
|
||||
setView(page);
|
||||
setCurrentPostId(null);
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const openPost = useCallback((postId) => {
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.set('post', postId);
|
||||
url.searchParams.delete('page');
|
||||
window.history.pushState({ page: 'post', postId }, '', url);
|
||||
setView('post');
|
||||
setCurrentPostId(postId);
|
||||
}, []);
|
||||
|
||||
// 浏览器前进后退
|
||||
useEffect(() => {
|
||||
const onPop = (e) => {
|
||||
const state = e.state || {};
|
||||
if (state.postId) {
|
||||
setView('post');
|
||||
setCurrentPostId(state.postId);
|
||||
} else {
|
||||
setView(state.page || 'feed');
|
||||
setCurrentPostId(null);
|
||||
}
|
||||
};
|
||||
window.addEventListener('popstate', onPop);
|
||||
return () => window.removeEventListener('popstate', onPop);
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email, password) => {
|
||||
const result = await API.login(email, password);
|
||||
if (result.user) {
|
||||
setCurrentUser(result.user);
|
||||
API.logEvent('login').catch(() => {});
|
||||
}
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (email, password, username) => {
|
||||
const result = await API.register(email, password, username);
|
||||
const loginResult = await API.login(email, password);
|
||||
if (loginResult.user) {
|
||||
setCurrentUser(loginResult.user);
|
||||
API.logEvent('register').catch(() => {});
|
||||
}
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
API.logout();
|
||||
setCurrentUser(null);
|
||||
navigate('feed');
|
||||
}, [navigate]);
|
||||
|
||||
const updateForumName = useCallback((name) => {
|
||||
setForumName(name);
|
||||
document.title = name;
|
||||
}, []);
|
||||
|
||||
const value = {
|
||||
currentUser, setCurrentUser,
|
||||
forumName, updateForumName,
|
||||
theme, toggleTheme,
|
||||
view, navigate,
|
||||
currentPostId, openPost,
|
||||
sort, setSort,
|
||||
refreshKey, refresh,
|
||||
login, register, logout,
|
||||
};
|
||||
|
||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
'use client';
|
||||
|
||||
// 信息流:帖子列表 + 排序 tab + 发布新帖按钮
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function Feed({ onOpenModal, onReport }) {
|
||||
const { currentUser, sort, setSort, openPost, navigate, refreshKey } = useApp();
|
||||
const [posts, setPosts] = useState(null); // null = loading
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setPosts(null);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await API.getPosts(sort);
|
||||
setPosts(data || []);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setPosts([]);
|
||||
}
|
||||
}, [sort, refreshKey]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleDelete = async (postId) => {
|
||||
if (!confirm('确定要删除这条帖子吗?')) return;
|
||||
try {
|
||||
await API.deletePost(postId);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main id="feed">
|
||||
<div className="feed-header">
|
||||
<div className="feed-header-left">
|
||||
<button className={'tab' + (sort === 'latest' ? ' active' : '')} onClick={() => setSort('latest')}>最新发布</button>
|
||||
<button className={'tab' + (sort === 'hot' ? ' active' : '')} onClick={() => setSort('hot')}>最新回复</button>
|
||||
</div>
|
||||
<button
|
||||
className="btn-primary fab-btn"
|
||||
onClick={() => {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
navigate('new');
|
||||
}}
|
||||
>
|
||||
发布新帖
|
||||
</button>
|
||||
</div>
|
||||
<div id="postList">
|
||||
{posts === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||
) : error ? (
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div>
|
||||
) : posts.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>✨ 还没有帖子,快来发布第一条吧!</div>
|
||||
) : (
|
||||
posts.map((p) => {
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }}
|
||||
onClick={() => openPost(p.id)}>
|
||||
<div className="post-header">
|
||||
<img src={avatar(p.username)} className="post-avatar" alt="" />
|
||||
<span className="post-username">{p.username || '匿名用户'}</span>
|
||||
<span className="post-time">{time}</span>
|
||||
</div>
|
||||
<div className="post-title">{p.title || '无标题'}</div>
|
||||
<div className="post-content">{(p.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}</div>
|
||||
{p.images && p.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{p.images.map((img, i) => <img key={i} src={img} className="post-image" alt="" />)}
|
||||
</div>
|
||||
)}
|
||||
<div className="post-actions">
|
||||
<span>💬 {p.reply_count || 0}</span>
|
||||
<button className="action-report" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
onReport(p.id);
|
||||
}}>举报</button>
|
||||
{currentUser && currentUser.id === p.user_id && (
|
||||
<button className="action-delete" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDelete(p.id);
|
||||
}}>删除</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
'use client';
|
||||
|
||||
// 登录/注册/举报 模态框
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function Modals({ modal, onClose, reportPostId }) {
|
||||
const { login, register, currentUser, refresh } = useApp();
|
||||
|
||||
// 登录表单
|
||||
const [loginEmail, setLoginEmail] = useState('');
|
||||
const [loginPassword, setLoginPassword] = useState('');
|
||||
|
||||
// 注册表单
|
||||
const [regUsername, setRegUsername] = useState('');
|
||||
const [regEmail, setRegEmail] = useState('');
|
||||
const [regPassword, setRegPassword] = useState('');
|
||||
const [regCaptcha, setRegCaptcha] = useState(null);
|
||||
const [regCaptchaInput, setRegCaptchaInput] = useState('');
|
||||
|
||||
// 举报表单
|
||||
const [reportReason, setReportReason] = useState('spam');
|
||||
|
||||
useEffect(() => {
|
||||
if (modal === 'register') setRegCaptcha(generateCaptcha());
|
||||
}, [modal]);
|
||||
|
||||
if (!modal) return null;
|
||||
|
||||
const close = (e) => {
|
||||
if (e && e.target !== e.currentTarget) return;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!loginEmail.trim() || !loginPassword) { alert('请填写完整信息'); return; }
|
||||
try {
|
||||
const result = await login(loginEmail.trim(), loginPassword);
|
||||
if (result.user) {
|
||||
onClose();
|
||||
setLoginEmail('');
|
||||
setLoginPassword('');
|
||||
refresh();
|
||||
}
|
||||
} catch (err) {
|
||||
alert('登录失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRegister = async () => {
|
||||
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { alert('请填写完整信息'); return; }
|
||||
if (regPassword.length < 6) { alert('密码至少6位'); return; }
|
||||
if (!regCaptcha || parseInt(regCaptchaInput) !== regCaptcha.answer) {
|
||||
alert('验证码错误,请重新计算');
|
||||
setRegCaptcha(generateCaptcha());
|
||||
setRegCaptchaInput('');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await register(regEmail.trim(), regPassword, regUsername.trim());
|
||||
onClose();
|
||||
setRegUsername('');
|
||||
setRegEmail('');
|
||||
setRegPassword('');
|
||||
setRegCaptchaInput('');
|
||||
alert('注册成功!');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
alert('注册失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReport = async () => {
|
||||
if (!reportPostId) return;
|
||||
try {
|
||||
await API.createReport(reportPostId, reportReason);
|
||||
onClose();
|
||||
alert('举报已提交,管理员将尽快处理');
|
||||
} catch (err) {
|
||||
alert('举报失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{modal === 'login' && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}>✕</span>
|
||||
<h2 style={{ marginBottom: 16 }}>登录</h2>
|
||||
<input type="email" placeholder="邮箱" value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
|
||||
<input type="password" placeholder="密码" value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>登录</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modal === 'register' && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}>✕</span>
|
||||
<h2 style={{ marginBottom: 16 }}>注册</h2>
|
||||
<input type="text" placeholder="用户名" value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
|
||||
<input type="email" placeholder="邮箱" value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
|
||||
<input type="password" placeholder="密码(至少6位)" value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
|
||||
<div className="captcha-row">
|
||||
<span onClick={() => setRegCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{regCaptcha ? regCaptcha.question : ''}
|
||||
</span>
|
||||
<input type="text" placeholder="答案" style={{ width: 80 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>注册</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modal === 'report' && currentUser && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}>✕</span>
|
||||
<h2 style={{ marginBottom: 16 }}>举报帖子</h2>
|
||||
<p style={{ fontSize: 14, color: '#64748b', marginBottom: 12 }}>请选择举报原因:</p>
|
||||
<select
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, marginBottom: 16 }}
|
||||
value={reportReason}
|
||||
onChange={(e) => setReportReason(e.target.value)}
|
||||
>
|
||||
<option value="spam">垃圾广告</option>
|
||||
<option value="abuse">人身攻击</option>
|
||||
<option value="illegal">违法内容</option>
|
||||
<option value="nsfw">不适当内容</option>
|
||||
<option value="other">其他</option>
|
||||
</select>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleReport}>提交举报</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client';
|
||||
|
||||
// 导航栏:论坛名、登录/注册按钮、用户下拉菜单、主题切换
|
||||
import { useState } from 'react';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function Navbar({ onOpenModal }) {
|
||||
const { currentUser, forumName, theme, toggleTheme, navigate, logout, setCurrentUser } = useApp();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
const avatarSrc = currentUser?.avatar_url ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
|
||||
'&background=6366f1&color=fff';
|
||||
|
||||
const goPage = (page) => {
|
||||
if (page === 'admin' && currentUser?.role !== 'admin') {
|
||||
alert('无权限访问');
|
||||
return;
|
||||
}
|
||||
setMenuOpen(false);
|
||||
navigate(page);
|
||||
};
|
||||
|
||||
return (
|
||||
<nav id="navbar">
|
||||
<div className="nav-left">
|
||||
<span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}>
|
||||
{forumName}
|
||||
</span>
|
||||
</div>
|
||||
<div className="nav-right">
|
||||
<div id="userMenu">
|
||||
{!currentUser ? (
|
||||
<div id="authButtons">
|
||||
<button className="btn-ghost" onClick={() => onOpenModal('login')}>登录</button>
|
||||
<button className="btn-primary" onClick={() => onOpenModal('register')}>注册</button>
|
||||
</div>
|
||||
) : (
|
||||
<div id="userDropdown" style={{ display: 'block' }}>
|
||||
<img
|
||||
className="avatar"
|
||||
src={avatarSrc}
|
||||
alt="avatar"
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }}
|
||||
/>
|
||||
{menuOpen && (
|
||||
<div className="dropdown-menu show" onClick={(e) => e.stopPropagation()}>
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('messages'); }}>消息</a>
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}>设置</a>
|
||||
{currentUser.role === 'admin' && (
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('admin'); }}>管理后台</a>
|
||||
)}
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
toggleTheme();
|
||||
setMenuOpen(false);
|
||||
}}
|
||||
>
|
||||
{theme === 'dark' ? '☀️ 亮色模式' : '🌙 暗色模式'}
|
||||
</a>
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (confirm('确定要退出吗?')) {
|
||||
setMenuOpen(false);
|
||||
logout();
|
||||
}
|
||||
}}
|
||||
>
|
||||
退出
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
'use client';
|
||||
|
||||
// 发布新帖页
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API, generateCaptcha, uploadImage } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function NewPost() {
|
||||
const { currentUser, navigate, refresh } = useApp();
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [images, setImages] = useState([]); // 上传后的 URL 列表
|
||||
const [previews, setPreviews] = useState([]); // 本地预览 dataURL
|
||||
const [captcha, setCaptcha] = useState(null);
|
||||
const [captchaInput, setCaptchaInput] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
useEffect(() => { setCaptcha(generateCaptcha()); }, []);
|
||||
|
||||
const handleFiles = async (files) => {
|
||||
setUploading(true);
|
||||
try {
|
||||
const newPreviews = [];
|
||||
for (const file of files) {
|
||||
const dataUrl = await new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => resolve(e.target.result);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
newPreviews.push(dataUrl);
|
||||
// 直接上传拿 URL
|
||||
const url = await uploadImage(file);
|
||||
setImages((prev) => [...prev, url]);
|
||||
}
|
||||
setPreviews((prev) => [...prev, ...newPreviews]);
|
||||
} catch (err) {
|
||||
alert('上传失败:' + err.message);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentUser || !currentUser.id) {
|
||||
alert('请先登录');
|
||||
navigate('feed');
|
||||
return;
|
||||
}
|
||||
if (!content.trim()) { alert('请填写内容'); return; }
|
||||
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
|
||||
alert('验证码错误,请重新计算');
|
||||
setCaptcha(generateCaptcha());
|
||||
setCaptchaInput('');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await API.createPost(title.trim() || '无标题', content.trim(), images);
|
||||
API.logEvent('create_post').catch(() => {});
|
||||
alert('发布成功!');
|
||||
navigate('feed');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
alert('发布失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
|
||||
<h2>发布新帖</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="标题"
|
||||
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid #e2e8f0', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, fontFamily: 'inherit' }}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<textarea
|
||||
rows={6}
|
||||
placeholder="说点什么..."
|
||||
style={{ width: '100%', padding: 12, border: '1.5px solid #e2e8f0', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
<div id="imagePreview" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, margin: '8px 0' }}>
|
||||
{previews.map((src, i) => (
|
||||
<img key={i} src={src} alt="" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 4, border: '1px solid #e2e8f0' }} />
|
||||
))}
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
disabled={uploading}
|
||||
onChange={(e) => { if (e.target.files) handleFiles(Array.from(e.target.files)); }}
|
||||
style={{ margin: '8px 0 12px' }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '12px 0' }}>
|
||||
<span onClick={() => setCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{captcha ? captcha.question : ''}
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="答案"
|
||||
style={{ width: 80, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={captchaInput}
|
||||
onChange={(e) => setCaptchaInput(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15 }} onClick={handleSubmit}>
|
||||
{uploading ? '上传中...' : '发布帖子'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
'use client';
|
||||
|
||||
// 帖子详情页
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import ReplyList from './ReplyList';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function PostDetail({ postId }) {
|
||||
const { currentUser, navigate, refreshKey } = useApp();
|
||||
const [post, setPost] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const data = await API.getPost(postId);
|
||||
setPost(data);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}, [postId, refreshKey]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="page-slide active" style={{ padding: '40px 0', textAlign: 'center', color: '#ef4444' }}>
|
||||
加载失败:{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!post) {
|
||||
return <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>;
|
||||
}
|
||||
|
||||
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
|
||||
const canDelete = currentUser && currentUser.id === post.user_id;
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!confirm('确定要删除这条帖子吗?')) return;
|
||||
try {
|
||||
await API.deletePost(postId);
|
||||
alert('删除成功');
|
||||
navigate('feed');
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<h2>{post.title || '帖子详情'}</h2>
|
||||
</div>
|
||||
<div id="postDetailContent" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<div className="post-detail-card">
|
||||
<div className="post-header">
|
||||
<img src={avatar(post.username)} className="post-avatar" alt="" />
|
||||
<span className="post-username">{post.username || '匿名用户'}</span>
|
||||
<span className="post-time">{time}</span>
|
||||
{canDelete && (
|
||||
<button className="btn-sm btn-danger" onClick={handleDelete}>删除</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="post-title" style={{ fontSize: 20, fontWeight: 700, margin: '8px 0 12px' }}>
|
||||
{post.title || '无标题'}
|
||||
</div>
|
||||
<div className="post-content" style={{ fontSize: 16, lineHeight: 1.8 }}>
|
||||
{(post.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}
|
||||
</div>
|
||||
{post.images && post.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{post.images.map((img, i) => <img key={i} src={img} className="post-image" alt="" />)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<ReplyList postId={postId} onRefresh={load} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
'use client';
|
||||
|
||||
// 回复列表 + 发表回复表单
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function ReplyList({ postId, onRefresh }) {
|
||||
const { currentUser } = useApp();
|
||||
const [replies, setReplies] = useState([]);
|
||||
const [content, setContent] = useState('');
|
||||
const [captcha, setCaptcha] = useState(null);
|
||||
const [captchaInput, setCaptchaInput] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const data = await API.getReplies(postId);
|
||||
setReplies(data || []);
|
||||
} catch { setReplies([]); }
|
||||
}, [postId]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
useEffect(() => { setCaptcha(generateCaptcha()); }, [postId]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
if (!content.trim()) { alert('请填写回复内容'); return; }
|
||||
if (!captcha || parseInt(captchaInput) !== captcha.answer) {
|
||||
alert('验证码错误,请重新计算');
|
||||
setCaptcha(generateCaptcha());
|
||||
setCaptchaInput('');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await API.createReply(postId, content.trim());
|
||||
API.logEvent('create_reply').catch(() => {});
|
||||
setContent('');
|
||||
setCaptchaInput('');
|
||||
setCaptcha(generateCaptcha());
|
||||
load();
|
||||
onRefresh();
|
||||
} catch (err) {
|
||||
alert('回复失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (replyId) => {
|
||||
if (!confirm('确定要删除这条回复吗?')) return;
|
||||
try {
|
||||
await API.deleteReply(replyId);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginTop: 20, fontSize: 14, color: '#64748b' }}>💬 {replies.length} 条回复</div>
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{replies.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有回复,快来抢沙发吧 🛋️</div>
|
||||
) : (
|
||||
replies.map((r) => {
|
||||
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={r.id} className="reply-item">
|
||||
<div className="reply-header">
|
||||
<img src={avatar(r.username)} className="reply-avatar" alt="" />
|
||||
<span className="reply-username">{r.username || '匿名用户'}</span>
|
||||
<span className="reply-time">{rTime}</span>
|
||||
{currentUser && currentUser.id === r.user_id && (
|
||||
<button className="btn-sm btn-danger reply-delete-btn" onClick={() => handleDelete(r.id)}>删除</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="reply-content">
|
||||
{(r.content || '').split('\n').map((l, i) => <span key={i}>{l}<br /></span>)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div id="replyArea" style={{ marginTop: 24, borderTop: '1px solid #e2e8f0', paddingTop: 20 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 12 }}>发表回复</h3>
|
||||
<textarea
|
||||
rows={3}
|
||||
placeholder="写下你的回复..."
|
||||
style={{ width: '100%', padding: '10px 12px', border: '1px solid #e2e8f0', borderRadius: 4, fontSize: 14, fontFamily: 'inherit', resize: 'vertical' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleSubmit(); }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '10px 0' }}>
|
||||
<span onClick={() => setCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
|
||||
{captcha ? captcha.question : ''}
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="答案"
|
||||
style={{ width: 80, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={captchaInput}
|
||||
onChange={(e) => setCaptchaInput(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={handleSubmit}>提交回复</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
'use client';
|
||||
|
||||
// 个人设置页
|
||||
import { useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { currentUser, setCurrentUser } = useApp();
|
||||
const [username, setUsername] = useState(currentUser?.username || '');
|
||||
const [bio, setBio] = useState(currentUser?.bio || '');
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
if (!username.trim()) { alert('用户名不能为空'); return; }
|
||||
try {
|
||||
const data = await API.updateProfile(currentUser.id, username.trim(), bio.trim());
|
||||
if (data.error) throw new Error(data.error);
|
||||
setCurrentUser({ ...currentUser, username: username.trim(), bio: bio.trim() });
|
||||
alert('保存成功!');
|
||||
} catch (err) {
|
||||
alert('保存失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 400, margin: '0 auto', width: '100%' }}>
|
||||
<h2>设置</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 400, margin: '0 auto', width: '100%' }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14 }}>用户名</label>
|
||||
<input
|
||||
type="text"
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, margin: '6px 0 12px' }}
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
<label style={{ fontWeight: 600, fontSize: 14 }}>个人简介</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4, margin: '6px 0 12px' }}
|
||||
value={bio}
|
||||
onChange={(e) => setBio(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" onClick={handleSave}>保存设置</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
'use client';
|
||||
|
||||
// 侧边栏:社区统计 + 友情链接
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function Sidebar() {
|
||||
const [stats, setStats] = useState({ posts: 0, users: 0, topics: 0, online: 0 });
|
||||
const [links, setLinks] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
API.getStats().then(setStats).catch(() => {});
|
||||
API.getLinks().then(setLinks).catch(() => {});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<aside id="sidebar">
|
||||
<div className="stats-box">
|
||||
<h4>社区统计</h4>
|
||||
<div className="stat-item"><span>主题</span><span>{stats.topics || 0}</span></div>
|
||||
<div className="stat-item"><span>帖子</span><span>{stats.posts || 0}</span></div>
|
||||
<div className="stat-item"><span>用户</span><span>{stats.users || 0}</span></div>
|
||||
<div className="stat-item"><span>在线</span><span>{stats.online || 0}</span></div>
|
||||
</div>
|
||||
<div className="links-box">
|
||||
<h4>友情链接</h4>
|
||||
<ul id="friendlyLinks">
|
||||
{links.length === 0 ? (
|
||||
<li style={{ color: '#94a3b8', fontSize: 13 }}>暂无链接</li>
|
||||
) : (
|
||||
links.map((l) => (
|
||||
<li key={l.id}><a href={l.url} target="_blank" rel="noreferrer">{l.title}</a></li>
|
||||
))
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 论坛设置
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
|
||||
export default function AdminForumSettings() {
|
||||
const { updateForumName } = useApp();
|
||||
const [name, setName] = useState('Forumlify');
|
||||
const [result, setResult] = useState(null); // {ok, msg}
|
||||
|
||||
useEffect(() => {
|
||||
API.getSettings()
|
||||
.then((data) => { if (data.forum_name) setName(data.forum_name); })
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!name.trim()) { alert('请输入论坛名称'); return; }
|
||||
try {
|
||||
await API.updateSettings(name.trim());
|
||||
updateForumName(name.trim());
|
||||
setResult({ ok: true, msg: '✅ 保存成功!' });
|
||||
} catch {
|
||||
setResult({ ok: false, msg: '❌ 保存失败' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3 style={{ marginBottom: 16 }}>⚙️ 论坛设置</h3>
|
||||
<div style={{ maxWidth: 400 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>论坛名称</label>
|
||||
<input
|
||||
type="text"
|
||||
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid #e2e8f0', borderRadius: 6, fontSize: 15, marginBottom: 12, fontFamily: 'inherit' }}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}>保存</button>
|
||||
{result && (
|
||||
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}>{result.msg}</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 友情链接管理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function AdminLinks() {
|
||||
const [links, setLinks] = useState([]);
|
||||
const [title, setTitle] = useState('');
|
||||
const [url, setUrl] = useState('');
|
||||
|
||||
const load = () => { API.getLinks().then(setLinks).catch(() => {}); };
|
||||
useEffect(load, []);
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!title.trim() || !url.trim()) { alert('请填写完整信息'); return; }
|
||||
try {
|
||||
await API.addLink(title.trim(), url.trim());
|
||||
setTitle('');
|
||||
setUrl('');
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('添加失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('确定删除该链接吗?')) return;
|
||||
try {
|
||||
await API.deleteLink(id);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<input
|
||||
type="text" placeholder="链接名称"
|
||||
style={{ flex: 1, minWidth: 120, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={title} onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type="url" placeholder="链接地址"
|
||||
style={{ flex: 2, minWidth: 160, padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 4 }}
|
||||
value={url} onChange={(e) => setUrl(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>添加</button>
|
||||
</div>
|
||||
<div id="linkList">
|
||||
{links.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', fontSize: 13 }}>暂无友情链接</div>
|
||||
) : (
|
||||
links.map((l) => (
|
||||
<div key={l.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
|
||||
<span><a href={l.url} target="_blank" rel="noreferrer" style={{ color: '#6366f1', textDecoration: 'none' }}>{l.title}</a></span>
|
||||
<button className="btn-sm btn-danger" onClick={() => handleDelete(l.id)}>删除</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 事件日志
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function AdminLogs() {
|
||||
const [logs, setLogs] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getEventLogs()
|
||||
.then((data) => { setLogs(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setLogs([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
|
||||
if (!logs) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>;
|
||||
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>暂无日志</div>;
|
||||
|
||||
return (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '1px solid #e2e8f0' }}>
|
||||
<th>时间</th><th>用户</th><th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{logs.map((l) => (
|
||||
<tr key={l.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
|
||||
<td style={{ padding: '6px 0' }}>{new Date(l.created_at).toLocaleString('zh-CN')}</td>
|
||||
<td style={{ padding: '6px 0' }}>{l.username || '系统'}</td>
|
||||
<td style={{ padding: '6px 0' }}>{l.action}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 举报处理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
const STATUS = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
|
||||
|
||||
export default function AdminReports() {
|
||||
const [reports, setReports] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getReports()
|
||||
.then((data) => { setReports(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setReports([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleAction = async (r, action) => {
|
||||
const status = action === 'approve' ? 'approved' : 'rejected';
|
||||
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
|
||||
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
|
||||
try {
|
||||
await API.updateReport(r.id, status, note);
|
||||
if (action === 'approve' && r.post_id) {
|
||||
API.deletePost(r.post_id).catch(() => {});
|
||||
}
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('操作失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
|
||||
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>;
|
||||
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>✅ 暂无举报</div>;
|
||||
|
||||
return reports.map((r) => (
|
||||
<div key={r.id} className="report-item">
|
||||
<div><strong>{r.reporter_name || '匿名'}</strong> 举报了帖子</div>
|
||||
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>原因:{r.reason}</div>
|
||||
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>
|
||||
帖子:{r.post_title || '无标题'} — {(r.post_content || '').substring(0, 30)}
|
||||
{(r.post_content || '').length > 30 ? '...' : ''}
|
||||
</div>
|
||||
<div style={{ fontSize: 13, fontWeight: 600 }}>状态:{STATUS[r.status] || r.status}</div>
|
||||
{r.handler_name && (
|
||||
<div style={{ fontSize: 12, color: '#94a3b8' }}>
|
||||
处理人:{r.handler_name}{r.handler_note ? ' (' + r.handler_note + ')' : ''}
|
||||
</div>
|
||||
)}
|
||||
{r.status === 'pending' && (
|
||||
<div className="report-actions">
|
||||
<button className="btn-sm btn-danger" onClick={() => handleAction(r, 'approve')}>删除帖子</button>
|
||||
<button className="btn-sm btn-secondary" onClick={() => handleAction(r, 'reject')}>驳回举报</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 用户管理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
|
||||
export default function AdminUsers() {
|
||||
const { currentUser } = useApp();
|
||||
const [users, setUsers] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getUsers()
|
||||
.then((data) => { setUsers(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setUsers([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleRole = async (u, role) => {
|
||||
const roleName = role === 'admin' ? '管理员' : '普通用户';
|
||||
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
|
||||
try {
|
||||
await API.updateUserRole(u.id, role);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('操作失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
|
||||
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>共 <strong>{users.length}</strong> 位用户</div>
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '2px solid #e2e8f0' }}>
|
||||
<th style={{ padding: '10px 12px' }}>用户</th>
|
||||
<th style={{ padding: '10px 12px' }}>角色</th>
|
||||
<th style={{ padding: '10px 12px' }}>注册时间</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'center' }}>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => {
|
||||
const isAdmin = u.role === 'admin';
|
||||
const isCurrent = currentUser && currentUser.id === u.id;
|
||||
return (
|
||||
<tr key={u.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
|
||||
<td style={{ padding: '10px 12px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<img
|
||||
src={u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}
|
||||
style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }}
|
||||
alt=""
|
||||
/>
|
||||
<span style={{ fontWeight: 500 }}>{u.username}</span>
|
||||
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>你</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px' }}>
|
||||
<span style={{
|
||||
display: 'inline-block', padding: '2px 10px', borderRadius: 4, fontSize: 12, fontWeight: 500,
|
||||
...(isAdmin ? { background: '#6366f1', color: '#fff' } : { background: '#e2e8f0', color: '#64748b' }),
|
||||
}}>
|
||||
{isAdmin ? '管理员' : '普通用户'}
|
||||
</span>
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', color: '#94a3b8', fontSize: 13 }}>
|
||||
{u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'}
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', textAlign: 'center' }}>
|
||||
{isCurrent ? (
|
||||
<span style={{ fontSize: 12, color: '#94a3b8' }}>不可操作自己</span>
|
||||
) : isAdmin ? (
|
||||
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>设为普通用户</button>
|
||||
) : (
|
||||
<button className="btn-sm btn-primary" style={{ padding: '4px 12px', background: '#6366f1', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer' }} onClick={() => handleRole(u, 'admin')}>设为管理员</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,11 @@ const CONFIG = {
|
||||
// 优先顺序:环境变量 PORT > 此处配置 > 默认 3000
|
||||
// 设为 null 则使用环境变量或默认值
|
||||
SERVER_PORT: null,
|
||||
|
||||
// 可选:服务端监听地址(仅服务端读取,浏览器端忽略)
|
||||
// 优先顺序:环境变量 HOST > 此处配置 > 默认 0.0.0.0(所有网卡)
|
||||
// 设为 '127.0.0.1' 可仅本机访问;设为 '0.0.0.0' 或 null 则允许局域网访问
|
||||
SERVER_HOST: null,
|
||||
};
|
||||
|
||||
// ===== 不要修改下面 =====
|
||||
|
||||
+3
-1
@@ -15,11 +15,13 @@ services:
|
||||
app:
|
||||
build: .
|
||||
ports:
|
||||
- "3003:3000"
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
- db
|
||||
environment:
|
||||
DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify
|
||||
HOSTNAME: 0.0.0.0
|
||||
PORT: 3000
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
|
||||
|
||||
+27
-3
@@ -1,7 +1,31 @@
|
||||
FROM node:18-alpine
|
||||
# ============================================================
|
||||
# Forumlify (Next.js) 生产镜像 — standalone 模式
|
||||
# ============================================================
|
||||
|
||||
# ---- 构建阶段 ----
|
||||
FROM node:18-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
|
||||
# 先装依赖(利用缓存)
|
||||
COPY package.json package-lock.json* bun.lock* ./
|
||||
RUN npm install
|
||||
|
||||
# 复制源码并构建
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# ---- 运行阶段 ----
|
||||
FROM node:18-alpine AS runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# standalone 输出(含 server.js 与最小 node_modules)
|
||||
COPY --from=builder /app/.next/standalone ./
|
||||
# 静态资源
|
||||
COPY --from=builder /app/.next/static ./.next/static
|
||||
|
||||
# 上传目录
|
||||
RUN mkdir -p /app/uploads
|
||||
|
||||
EXPOSE 3000
|
||||
CMD ["npm", "start"]
|
||||
CMD ["node", "server.js"]
|
||||
-1488
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
+127
@@ -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
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -0,0 +1,12 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
output: 'standalone',
|
||||
// /uploads/* 由 API 路由提供(上传文件运行时新增,不进 public 构建快照)
|
||||
async rewrites() {
|
||||
return [
|
||||
{ source: '/uploads/:name', destination: '/api/uploads/:name' },
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
Generated
+303
-1210
File diff suppressed because it is too large.
Load diff
+13
-11
@@ -1,18 +1,20 @@
|
||||
{
|
||||
"name": "forumlify",
|
||||
"version": "1.0.0",
|
||||
"description": "Forumlify - 简洁优雅的现代社区系统",
|
||||
"main": "server.js",
|
||||
"version": "2.0.0",
|
||||
"description": "Forumlify - 简洁优雅的现代社区系统 (Next.js)",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "node server.js"
|
||||
"dev": "next dev -H 0.0.0.0",
|
||||
"build": "next build",
|
||||
"start": "node scripts/start.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.18.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"pg": "^8.11.3"
|
||||
}
|
||||
}
|
||||
"next": "^14.2.15",
|
||||
"pg": "^8.11.3",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env node
|
||||
// Forumlify 启动入口
|
||||
// 从 config.js 读取 SERVER_HOST / SERVER_PORT(可选),未配置时用默认值:
|
||||
// host = 环境变量 HOST > config.SERVER_HOST > '0.0.0.0'
|
||||
// port = 环境变量 PORT > config.SERVER_PORT > 3000
|
||||
const { spawn } = require('child_process');
|
||||
const CONFIG = require('../config');
|
||||
|
||||
const host = process.env.HOST || CONFIG.SERVER_HOST || '0.0.0.0';
|
||||
const port = process.env.PORT || CONFIG.SERVER_PORT || 3000;
|
||||
|
||||
const args = ['start', '-H', host, '-p', String(port)];
|
||||
const child = spawn(require.resolve('next/dist/bin/next'), args, {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, HOSTNAME: host, PORT: String(port) },
|
||||
});
|
||||
|
||||
child.on('exit', (code, signal) => {
|
||||
if (signal) process.kill(process.pid, signal);
|
||||
else process.exit(code ?? 0);
|
||||
});
|
||||
@@ -1,639 +0,0 @@
|
||||
// ============================================================
|
||||
// Forumlify 后端服务
|
||||
// 一个文件搞定所有 API + 文件服务
|
||||
// ============================================================
|
||||
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { Pool } = require('pg');
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const app = express();
|
||||
|
||||
// 服务端配置(config.js,浏览器端加载同名文件但不影响服务端)
|
||||
const CONFIG = require('./config');
|
||||
|
||||
// 监听端口:环境变量 PORT 优先,其次 config.js 的 SERVER_PORT,最后默认 3000
|
||||
const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000;
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'forumlify-secret-key-change-me-in-production';
|
||||
|
||||
// ============================================================
|
||||
// 数据库
|
||||
// ============================================================
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL || 'postgresql://forumlify:123456@localhost:5432/forumlify',
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 中间件
|
||||
// ============================================================
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// 确保上传目录存在
|
||||
if (!fs.existsSync('uploads')) fs.mkdirSync('uploads');
|
||||
app.use('/uploads', express.static('uploads'));
|
||||
|
||||
// ============================================================
|
||||
// 认证中间件
|
||||
// ============================================================
|
||||
const auth = (req, res, next) => {
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: '请先登录' });
|
||||
}
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
req.user = decoded;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: '登录已过期,请重新登录' });
|
||||
}
|
||||
};
|
||||
|
||||
const admin = async (req, res, next) => {
|
||||
try {
|
||||
const r = await pool.query('SELECT role FROM users WHERE id = $1', [req.user.id]);
|
||||
if (r.rows[0]?.role !== 'admin') {
|
||||
return res.status(403).json({ error: '需要管理员权限' });
|
||||
}
|
||||
next();
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================
|
||||
// 论坛设置接口(新增)
|
||||
// ============================================================
|
||||
|
||||
// 获取论坛设置(公开)
|
||||
app.get('/api/settings', async (req, res) => {
|
||||
try {
|
||||
const r = await pool.query('SELECT key, value FROM settings');
|
||||
const settings = {};
|
||||
r.rows.forEach(row => { settings[row.key] = row.value; });
|
||||
res.json(settings);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 更新论坛设置(管理员)
|
||||
app.put('/api/settings', auth, admin, async (req, res) => {
|
||||
const { forum_name } = req.body;
|
||||
if (!forum_name || forum_name.trim().length === 0) {
|
||||
return res.status(400).json({ error: '论坛名称不能为空' });
|
||||
}
|
||||
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()]
|
||||
);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '更新失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 认证接口
|
||||
// ============================================================
|
||||
|
||||
// 注册 - 第一个用户自动成为管理员
|
||||
app.post('/api/auth/register', async (req, res) => {
|
||||
const { email, password, username } = req.body;
|
||||
|
||||
if (!email || !password || !username) {
|
||||
return res.status(400).json({ error: '请填写完整信息' });
|
||||
}
|
||||
if (password.length < 6) {
|
||||
return res.status(400).json({ error: '密码至少6位' });
|
||||
}
|
||||
|
||||
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]
|
||||
);
|
||||
|
||||
res.json({
|
||||
user: r.rows[0],
|
||||
message: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功'
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
res.status(400).json({ error: '邮箱或用户名已被注册' });
|
||||
} else {
|
||||
res.status(500).json({ error: '注册失败,请稍后重试' });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 登录
|
||||
app.post('/api/auth/login', async (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
if (!email || !password) {
|
||||
return res.status(400).json({ error: '请填写邮箱和密码' });
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
|
||||
const user = r.rows[0];
|
||||
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: '邮箱或密码错误' });
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(password, user.password_hash);
|
||||
if (!valid) {
|
||||
return res.status(401).json({ error: '邮箱或密码错误' });
|
||||
}
|
||||
|
||||
const token = jwt.sign(
|
||||
{ id: user.id, email: user.email, role: user.role },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '7d' }
|
||||
);
|
||||
|
||||
res.json({
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
role: user.role,
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '登录失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取当前用户信息
|
||||
app.get('/api/auth/me', auth, async (req, res) => {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, username, avatar_url, bio, role, created_at FROM users WHERE id = $1',
|
||||
[req.user.id]
|
||||
);
|
||||
if (!r.rows[0]) {
|
||||
return res.status(404).json({ error: '用户不存在' });
|
||||
}
|
||||
res.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 用户管理
|
||||
// ============================================================
|
||||
|
||||
// 获取所有用户(管理员)
|
||||
app.get('/api/users', auth, admin, async (req, res) => {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, username, avatar_url, bio, role, created_at FROM users ORDER BY created_at DESC'
|
||||
);
|
||||
res.json(r.rows);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 修改用户角色(管理员)
|
||||
app.put('/api/users/:id/role', auth, admin, async (req, res) => {
|
||||
const { role } = req.body;
|
||||
const userId = req.params.id;
|
||||
|
||||
if (!['user', 'admin'].includes(role)) {
|
||||
return res.status(400).json({ error: '无效的角色' });
|
||||
}
|
||||
|
||||
try {
|
||||
if (userId === req.user.id) {
|
||||
return res.status(400).json({ error: '不能修改自己的角色' });
|
||||
}
|
||||
|
||||
await pool.query('UPDATE users SET role = $1 WHERE id = $2', [role, userId]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 更新用户资料
|
||||
app.put('/api/users/:id', auth, async (req, res) => {
|
||||
const { username, bio } = req.body;
|
||||
const userId = req.params.id;
|
||||
|
||||
if (userId !== req.user.id) {
|
||||
return res.status(403).json({ error: '无权限修改他人资料' });
|
||||
}
|
||||
|
||||
try {
|
||||
await pool.query('UPDATE users SET username = $1, bio = $2 WHERE id = $3', [username, bio || '', userId]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
res.status(400).json({ error: '用户名已被占用' });
|
||||
} else {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 帖子接口
|
||||
// ============================================================
|
||||
|
||||
// 获取帖子列表
|
||||
app.get('/api/posts', async (req, res) => {
|
||||
const sort = req.query.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
|
||||
`);
|
||||
res.json(r.rows);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 获取单个帖子
|
||||
app.get('/api/posts/:id', async (req, res) => {
|
||||
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`,
|
||||
[req.params.id]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return res.status(404).json({ error: '帖子不存在' });
|
||||
}
|
||||
res.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 创建帖子
|
||||
app.post('/api/posts', auth, async (req, res) => {
|
||||
const { title, content, images } = req.body;
|
||||
|
||||
if (!content || content.trim().length === 0) {
|
||||
return res.status(400).json({ error: '请填写内容' });
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`INSERT INTO posts (user_id, title, content, images)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING *`,
|
||||
[req.user.id, title || '无标题', content, images || []]
|
||||
);
|
||||
res.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '发布失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 删除帖子
|
||||
app.delete('/api/posts/:id', auth, async (req, res) => {
|
||||
try {
|
||||
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [req.params.id]);
|
||||
if (post.rows.length === 0) {
|
||||
return res.status(404).json({ error: '帖子不存在' });
|
||||
}
|
||||
|
||||
const user = await pool.query('SELECT role FROM users WHERE id = $1', [req.user.id]);
|
||||
if (post.rows[0].user_id !== req.user.id && user.rows[0]?.role !== 'admin') {
|
||||
return res.status(403).json({ error: '无权限删除此帖子' });
|
||||
}
|
||||
|
||||
await pool.query('DELETE FROM posts WHERE id = $1', [req.params.id]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '删除失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 回复接口
|
||||
// ============================================================
|
||||
|
||||
// 获取帖子回复列表
|
||||
app.get('/api/posts/:id/replies', async (req, res) => {
|
||||
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`,
|
||||
[req.params.id]
|
||||
);
|
||||
res.json(r.rows);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 创建回复
|
||||
app.post('/api/posts/:id/replies', auth, async (req, res) => {
|
||||
const { content } = req.body;
|
||||
|
||||
if (!content || content.trim().length === 0) {
|
||||
return res.status(400).json({ error: '请填写回复内容' });
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *`,
|
||||
[req.params.id, req.user.id, content]
|
||||
);
|
||||
await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [req.params.id]);
|
||||
res.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '回复失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 删除回复
|
||||
app.delete('/api/replies/:id', auth, async (req, res) => {
|
||||
try {
|
||||
const reply = await pool.query('SELECT user_id FROM replies WHERE id = $1', [req.params.id]);
|
||||
if (reply.rows.length === 0) {
|
||||
return res.status(404).json({ error: '回复不存在' });
|
||||
}
|
||||
|
||||
const user = await pool.query('SELECT role FROM users WHERE id = $1', [req.user.id]);
|
||||
if (reply.rows[0].user_id !== req.user.id && user.rows[0]?.role !== 'admin') {
|
||||
return res.status(403).json({ error: '无权限删除此回复' });
|
||||
}
|
||||
|
||||
await pool.query('DELETE FROM replies WHERE id = $1', [req.params.id]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '删除失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 举报接口
|
||||
// ============================================================
|
||||
|
||||
// 获取举报列表(管理员)
|
||||
app.get('/api/reports', auth, admin, async (req, res) => {
|
||||
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
|
||||
`);
|
||||
res.json(r.rows);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 提交举报
|
||||
app.post('/api/reports', auth, async (req, res) => {
|
||||
const { post_id, reason } = req.body;
|
||||
|
||||
if (!post_id || !reason) {
|
||||
return res.status(400).json({ error: '请填写完整信息' });
|
||||
}
|
||||
|
||||
try {
|
||||
const existing = await pool.query(
|
||||
'SELECT id FROM reports WHERE post_id = $1 AND reporter_id = $2 AND status = $3',
|
||||
[post_id, req.user.id, 'pending']
|
||||
);
|
||||
if (existing.rows.length > 0) {
|
||||
return res.status(400).json({ error: '你已经举报过此帖子,请等待处理' });
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO reports (post_id, reporter_id, reason)
|
||||
VALUES ($1, $2, $3)`,
|
||||
[post_id, req.user.id, reason]
|
||||
);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '举报失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 处理举报(管理员)
|
||||
app.put('/api/reports/:id', auth, admin, async (req, res) => {
|
||||
const { status, note } = req.body;
|
||||
|
||||
if (!['pending', 'approved', 'rejected'].includes(status)) {
|
||||
return res.status(400).json({ error: '无效的状态' });
|
||||
}
|
||||
|
||||
try {
|
||||
await pool.query(
|
||||
`UPDATE reports
|
||||
SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3
|
||||
WHERE id = $4`,
|
||||
[status, req.user.id, note || '', req.params.id]
|
||||
);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '操作失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 友情链接
|
||||
// ============================================================
|
||||
|
||||
// 获取友情链接
|
||||
app.get('/api/links', async (req, res) => {
|
||||
try {
|
||||
const r = await pool.query('SELECT * FROM friendly_links ORDER BY sort_order');
|
||||
res.json(r.rows);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 添加友情链接(管理员)
|
||||
app.post('/api/links', auth, admin, async (req, res) => {
|
||||
const { title, url } = req.body;
|
||||
|
||||
if (!title || !url) {
|
||||
return res.status(400).json({ error: '请填写完整信息' });
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`INSERT INTO friendly_links (title, url)
|
||||
VALUES ($1, $2)
|
||||
RETURNING *`,
|
||||
[title, url]
|
||||
);
|
||||
res.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '添加失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 删除友情链接(管理员)
|
||||
app.delete('/api/links/:id', auth, admin, async (req, res) => {
|
||||
try {
|
||||
await pool.query('DELETE FROM friendly_links WHERE id = $1', [req.params.id]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '删除失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 统计数据
|
||||
// ============================================================
|
||||
|
||||
app.get('/api/stats', async (req, res) => {
|
||||
try {
|
||||
const [postsRes, usersRes] = await Promise.all([
|
||||
pool.query('SELECT COUNT(*) FROM posts'),
|
||||
pool.query('SELECT COUNT(*) FROM users'),
|
||||
]);
|
||||
res.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 (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 事件日志
|
||||
// ============================================================
|
||||
|
||||
// 获取事件日志(管理员)
|
||||
app.get('/api/event-logs', auth, admin, async (req, res) => {
|
||||
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`
|
||||
);
|
||||
res.json(r.rows);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 记录事件
|
||||
app.post('/api/event-logs', auth, async (req, res) => {
|
||||
const { action } = req.body;
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO event_logs (user_id, action, ip)
|
||||
VALUES ($1, $2, $3)`,
|
||||
[req.user.id, action, req.ip || '0.0.0.0']
|
||||
);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.json({ success: true });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 图片上传
|
||||
// ============================================================
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => cb(null, 'uploads/'),
|
||||
filename: (req, file, cb) => {
|
||||
const ext = path.extname(file.originalname);
|
||||
const name = Date.now() + '-' + Math.round(Math.random() * 10000) + ext;
|
||||
cb(null, name);
|
||||
}
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: { fileSize: 5 * 1024 * 1024 },
|
||||
fileFilter: (req, file, cb) => {
|
||||
const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
|
||||
cb(null, allowed.includes(file.mimetype));
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/upload', auth, upload.single('file'), (req, res) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: '请选择图片' });
|
||||
}
|
||||
res.json({ url: '/uploads/' + req.file.filename });
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 托管前端文件
|
||||
// ============================================================
|
||||
|
||||
app.use(express.static('.'));
|
||||
|
||||
app.get('*', (req, res) => {
|
||||
if (!req.path.startsWith('/api')) {
|
||||
res.sendFile(path.join(__dirname, 'index.html'));
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 启动服务器
|
||||
// ============================================================
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log('========================================');
|
||||
console.log(' 🌊 Forumlify 已启动');
|
||||
console.log(' 📡 http://localhost:' + PORT);
|
||||
console.log(' 📡 API: http://localhost:' + PORT + '/api');
|
||||
console.log('========================================');
|
||||
});
|
||||
Reference in new issue
Block a user