huh
feat: migrate to Next.js 14 (App Router + Route Handlers)
This commit is contained in:
96 files changed
+5170
-5573
No files matched your search
@@ -0,0 +1,12 @@
|
||||
# Forumlify 环境变量示例
|
||||
# 复制为 .env 并按需修改
|
||||
|
||||
# PostgreSQL 连接串(默认与 docker-compose.yml 一致)
|
||||
DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
|
||||
|
||||
# JWT 签名密钥(生产环境务必修改为随机长字符串)
|
||||
JWT_SECRET=forumlify-secret-key-change-me-in-production
|
||||
|
||||
# 可选:监听端口/地址(也可在 config.js 中设置 SERVER_PORT / SERVER_HOST)
|
||||
# PORT=3000
|
||||
# HOST=0.0.0.0
|
||||
+7
-1
@@ -1,5 +1,11 @@
|
||||
node_modules/
|
||||
.next/
|
||||
out/
|
||||
uploads/
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
|
||||
# .env 允许提交到仓库(项目约定)
|
||||
# 仅忽略本地覆盖文件
|
||||
.env.local
|
||||
.env.*.local
|
||||
@@ -5,7 +5,7 @@
|
||||
## ✨ 特性
|
||||
|
||||
- 🎨 精致简约的界面设计,支持亮色/暗色模式
|
||||
- ⚡️ 轻量快速,无需复杂配置
|
||||
- ⚡️ 基于 Next.js 14 (App Router) + React 18,前后端一体化
|
||||
- 🔐 自带用户认证(JWT)
|
||||
- 📝 发帖、回复、举报、管理后台
|
||||
- 🐳 Docker 一键部署
|
||||
@@ -21,10 +21,11 @@ cd forumlify
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
应用默认运行在 `http://localhost:3003`。
|
||||
应用默认运行在 `http://localhost:3000`(监听 `0.0.0.0`,局域网可访问)。
|
||||
|
||||
---
|
||||
以下内容添加自NodeLoc @Lezi-fun的PR
|
||||
|
||||
> 以下内容添加自 NodeLoc @Lezi-fun 的 PR(从源码构建与配置说明)
|
||||
|
||||
---
|
||||
|
||||
@@ -34,7 +35,7 @@ docker-compose up -d
|
||||
|
||||
#### 环境要求
|
||||
|
||||
- Node.js 18+
|
||||
- Node.js 18.17+(Next.js 14 要求)
|
||||
- PostgreSQL 13+(`schema.sql` 使用了内置的 `gen_random_uuid()`)
|
||||
|
||||
#### 步骤
|
||||
@@ -62,7 +63,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 +71,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 +98,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,48 @@
|
||||
// PUT /api/admin/custom-pages/[id], DELETE /api/admin/custom-pages/[id]
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
if (!UUID_RE.test(params.id)) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
const { title, content, enabled } = await req.json();
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`UPDATE custom_pages
|
||||
SET title = $1, content = $2, enabled = $3, updated_at = NOW()
|
||||
WHERE id = $4
|
||||
RETURNING *`,
|
||||
[title, content, enabled, params.id]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
if (!UUID_RE.test(params.id)) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
try {
|
||||
await pool.query('DELETE FROM custom_pages WHERE id = $1', [params.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// GET /api/admin/custom-pages, POST /api/admin/custom-pages — 管理 CRUD
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, name, title, content, enabled, created_at, updated_at FROM custom_pages ORDER BY created_at'
|
||||
);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const { name, title, content } = await req.json();
|
||||
if (!name || !title || !content) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
|
||||
return Response.json({ error: '页面名称只允许字母、数字、短横线和下划线' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`INSERT INTO custom_pages (name, title, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *`,
|
||||
[name, title, content]
|
||||
);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return Response.json({ error: '页面名称已存在' }, { status: 400 });
|
||||
}
|
||||
return Response.json({ error: '创建失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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,17 @@
|
||||
// GET /api/auth/recovery-codes/count — 剩余恢复码数量
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT COUNT(*) FROM recovery_codes WHERE user_id = $1 AND is_used = false',
|
||||
[user.id]
|
||||
);
|
||||
return Response.json({ count: parseInt(r.rows[0].count) || 0 });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// POST /api/auth/recovery-codes/generate — 生成 10 个恢复码
|
||||
import bcrypt from 'bcrypt';
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
function generateRecoveryCode() {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
let code = '';
|
||||
for (let i = 0; i < 20; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)];
|
||||
if (i === 4 || i === 9 || i === 14) code += '-';
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
await pool.query('DELETE FROM recovery_codes WHERE user_id = $1', [user.id]);
|
||||
const codes = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const code = generateRecoveryCode();
|
||||
codes.push(code);
|
||||
const hash = await bcrypt.hash(code, 10);
|
||||
await pool.query(
|
||||
'INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2)',
|
||||
[user.id, hash]
|
||||
);
|
||||
}
|
||||
return Response.json({ success: true, codes });
|
||||
} catch {
|
||||
return Response.json({ error: '生成失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -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,38 @@
|
||||
// POST /api/auth/reset-password — 用恢复码重置密码(公开)
|
||||
import bcrypt from 'bcrypt';
|
||||
import pool from '@/lib/db';
|
||||
|
||||
export async function POST(req) {
|
||||
const { email, recoveryCode, newPassword } = await req.json();
|
||||
if (!email || !recoveryCode || !newPassword) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (newPassword.length < 6) {
|
||||
return Response.json({ error: '密码至少6位' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const user = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
|
||||
if (user.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const codes = await pool.query(
|
||||
'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false',
|
||||
[user.rows[0].id]
|
||||
);
|
||||
let matched = false;
|
||||
let matchedId = null;
|
||||
for (const row of codes.rows) {
|
||||
const valid = await bcrypt.compare(recoveryCode, row.code_hash);
|
||||
if (valid) { matched = true; matchedId = row.id; break; }
|
||||
}
|
||||
if (!matched) {
|
||||
return Response.json({ error: '恢复码无效或已使用' }, { status: 400 });
|
||||
}
|
||||
await pool.query('UPDATE recovery_codes SET is_used = true WHERE id = $1', [matchedId]);
|
||||
const hash = await bcrypt.hash(newPassword, 10);
|
||||
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, user.rows[0].id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '重置失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
|
||||
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 GET(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
if (!UUID_RE.test(params.id)) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
try {
|
||||
const check = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||
`, [params.id, user.id]);
|
||||
if (check.rows.length === 0) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const r = await pool.query(`
|
||||
SELECT
|
||||
m.*,
|
||||
u.username as sender_username,
|
||||
u.avatar_url as sender_avatar_url
|
||||
FROM messages m
|
||||
JOIN users u ON m.sender_id = u.id
|
||||
WHERE m.conversation_id = $1
|
||||
ORDER BY m.created_at ASC
|
||||
`, [params.id]);
|
||||
await pool.query(`
|
||||
UPDATE messages SET is_read = true
|
||||
WHERE conversation_id = $1 AND sender_id != $2 AND is_read = false
|
||||
`, [params.id, user.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 });
|
||||
}
|
||||
if (!UUID_RE.test(params.id)) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const { content } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写消息内容' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const check = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||
`, [params.id, user.id]);
|
||||
if (check.rows.length === 0) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const r = await pool.query(`
|
||||
INSERT INTO messages (conversation_id, sender_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *
|
||||
`, [params.id, user.id, content]);
|
||||
await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [params.id]);
|
||||
const userInfo = await pool.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||
return Response.json({
|
||||
...r.rows[0],
|
||||
sender_username: userInfo.rows[0].username,
|
||||
sender_avatar_url: userInfo.rows[0].avatar_url,
|
||||
});
|
||||
} catch {
|
||||
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// GET /api/conversations, POST /api/conversations
|
||||
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
|
||||
c.id,
|
||||
c.user1_id,
|
||||
c.user2_id,
|
||||
c.last_message_at,
|
||||
c.created_at,
|
||||
u.id as other_user_id,
|
||||
u.username as other_username,
|
||||
u.avatar_url as other_avatar_url,
|
||||
(SELECT COUNT(*) FROM messages WHERE conversation_id = c.id AND sender_id != $1 AND is_read = false) as unread_count,
|
||||
(SELECT content FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message,
|
||||
(SELECT created_at FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message_time
|
||||
FROM conversations c
|
||||
JOIN users u ON (u.id = c.user1_id OR u.id = c.user2_id) AND u.id != $1
|
||||
WHERE c.user1_id = $1 OR c.user2_id = $1
|
||||
ORDER BY c.last_message_at DESC
|
||||
`, [user.id]);
|
||||
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 { other_user_id } = await req.json();
|
||||
if (!other_user_id) {
|
||||
return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
|
||||
}
|
||||
if (other_user_id === user.id) {
|
||||
return Response.json({ error: '不能与自己私信' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
|
||||
if (userCheck.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const existing = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
|
||||
`, [user.id, other_user_id]);
|
||||
if (existing.rows.length > 0) {
|
||||
return Response.json({ id: existing.rows[0].id });
|
||||
}
|
||||
const r = await pool.query(`
|
||||
INSERT INTO conversations (user1_id, user2_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id
|
||||
`, [user.id, other_user_id]);
|
||||
return Response.json({ id: r.rows[0].id });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// GET /api/custom-pages/[name] — 公开单个页面
|
||||
import pool from '@/lib/db';
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, name, title, content FROM custom_pages WHERE name = $1 AND enabled = true',
|
||||
[params.name]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// GET /api/custom-pages — 公开页面列表
|
||||
import pool from '@/lib/db';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, name, title FROM custom_pages WHERE enabled = true ORDER BY created_at'
|
||||
);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -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,24 @@
|
||||
// PUT /api/messages/[id]/read — 标记消息已读
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
if (!UUID_RE.test(params.id)) {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
try {
|
||||
await pool.query(`
|
||||
UPDATE messages SET is_read = true
|
||||
WHERE id = $1 AND sender_id != $2
|
||||
`, [params.id, user.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// PUT /api/notifications/[id]/read — 标记单条已读
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if (!UUID_RE.test(params.id)) {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
'UPDATE notifications SET is_read = true WHERE id = $1 AND user_id = $2',
|
||||
[params.id, user.id]
|
||||
);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// PUT /api/notifications/read-all — 全部标记已读
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
await pool.query('UPDATE notifications SET is_read = true WHERE user_id = $1', [user.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// GET /api/notifications — 我的通知列表
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, type, title, content, link, is_read, created_at FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50',
|
||||
[user.id]
|
||||
);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -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,76 @@
|
||||
// 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 PUT(req, { params }) {
|
||||
if (!UUID_RE.test(params.id)) return invalidId();
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { title, content } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写内容' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [params.id]);
|
||||
if (post.rows.length === 0) return invalidId();
|
||||
if (post.rows[0].user_id !== user.id) {
|
||||
return Response.json({ error: '无权限编辑此帖子' }, { status: 403 });
|
||||
}
|
||||
const r = await pool.query(
|
||||
`UPDATE posts SET title = $1, content = $2, edited_at = NOW() WHERE id = $3 RETURNING *`,
|
||||
[title || '无标题', content, params.id]
|
||||
);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '编辑失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req, { params }) {
|
||||
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,66 @@
|
||||
// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= & 分页
|
||||
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';
|
||||
const userId = url.searchParams.get('user_id');
|
||||
const page = parseInt(url.searchParams.get('page')) || 1;
|
||||
const limit = parseInt(url.searchParams.get('limit')) || 20;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
try {
|
||||
const params = [];
|
||||
let where = '';
|
||||
if (userId) {
|
||||
where = ' WHERE p.user_id = $1';
|
||||
params.push(userId);
|
||||
}
|
||||
|
||||
const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
|
||||
const total = parseInt(countResult.rows[0]?.total || 0);
|
||||
|
||||
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
|
||||
${where}
|
||||
ORDER BY ${sort} DESC
|
||||
LIMIT $${params.length + 1} OFFSET $${params.length + 2}
|
||||
`, [...params, limit, offset]);
|
||||
|
||||
return Response.json({
|
||||
data: r.rows,
|
||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
||||
});
|
||||
} 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,21 @@
|
||||
// PUT /api/users/[id]/avatar — 修改头像
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if (params.id !== user.id) {
|
||||
return Response.json({ error: '无权限修改他人头像' }, { status: 403 });
|
||||
}
|
||||
const { avatar_url } = await req.json();
|
||||
if (!avatar_url) {
|
||||
return Response.json({ error: '请提供头像地址' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await pool.query('UPDATE users SET avatar_url = $1 WHERE id = $2', [avatar_url, params.id]);
|
||||
return Response.json({ success: true, avatar_url });
|
||||
} catch {
|
||||
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// PUT /api/users/[id]/email — 修改邮箱(需密码验证)
|
||||
import bcrypt from 'bcrypt';
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if (params.id !== user.id) {
|
||||
return Response.json({ error: '无权限' }, { status: 403 });
|
||||
}
|
||||
const { password, newEmail } = await req.json();
|
||||
if (!password || !newEmail) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [params.id]);
|
||||
if (u.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const valid = await bcrypt.compare(password, u.rows[0].password_hash);
|
||||
if (!valid) {
|
||||
return Response.json({ error: '密码错误' }, { status: 400 });
|
||||
}
|
||||
const existing = await pool.query('SELECT id FROM users WHERE email = $1 AND id != $2', [newEmail, params.id]);
|
||||
if (existing.rows.length > 0) {
|
||||
return Response.json({ error: '邮箱已被占用' }, { status: 400 });
|
||||
}
|
||||
await pool.query('UPDATE users SET email = $1 WHERE id = $2', [newEmail, params.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// PUT /api/users/[id]/password — 修改密码
|
||||
import bcrypt from 'bcrypt';
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if (params.id !== user.id) {
|
||||
return Response.json({ error: '无权限' }, { status: 403 });
|
||||
}
|
||||
const { oldPassword, newPassword } = await req.json();
|
||||
if (!oldPassword || !newPassword) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (newPassword.length < 6) {
|
||||
return Response.json({ error: '新密码至少6位' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [params.id]);
|
||||
if (u.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const valid = await bcrypt.compare(oldPassword, u.rows[0].password_hash);
|
||||
if (!valid) {
|
||||
return Response.json({ error: '当前密码错误' }, { status: 400 });
|
||||
}
|
||||
const hash = await bcrypt.hash(newPassword, 10);
|
||||
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, params.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -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,26 @@
|
||||
// GET /api/users (admin) — 支持 ?username= 按用户名查询
|
||||
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;
|
||||
|
||||
const url = new URL(req.url);
|
||||
const username = url.searchParams.get('username');
|
||||
|
||||
try {
|
||||
let query = 'SELECT id, username, avatar_url, bio, role, created_at FROM users';
|
||||
const params = [];
|
||||
if (username) {
|
||||
query += ' WHERE username = $1';
|
||||
params.push(username);
|
||||
}
|
||||
query += ' ORDER BY created_at DESC';
|
||||
const r = await pool.query(query, params);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -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>
|
||||
);
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
'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 UserProfile from '@/components/UserProfile';
|
||||
import CustomPage from '@/components/CustomPage';
|
||||
import MessagesPage from '@/components/MessagesPage';
|
||||
import ChatManager from '@/components/chat/ChatManager';
|
||||
import Modals from '@/components/Modals';
|
||||
|
||||
function HomeInner() {
|
||||
const { view, currentPostId, currentUsername, currentPageName } = 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 (
|
||||
<>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<Navbar onOpenModal={openModal} style={{ flex: 1 }} />
|
||||
<div style={{ paddingRight: 16 }}>
|
||||
<ChatManager />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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 === 'user' && currentUsername && <UserProfile username={currentUsername} />}
|
||||
{view === 'custom' && currentPageName && <CustomPage pageName={currentPageName} />}
|
||||
{view === 'new' && <NewPost />}
|
||||
{view === 'admin' && <AdminPage />}
|
||||
{view === 'settings' && <SettingsPage />}
|
||||
{view === 'messages' && <MessagesPage />}
|
||||
</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,71 @@
|
||||
'use client';
|
||||
|
||||
// 账户安全:修改密码 + 修改邮箱
|
||||
import { useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
|
||||
export default function AccountSecurity() {
|
||||
const { currentUser } = useApp();
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [pwStatus, setPwStatus] = useState(null);
|
||||
const [emailPassword, setEmailPassword] = useState('');
|
||||
const [newEmail, setNewEmail] = useState('');
|
||||
const [emailStatus, setEmailStatus] = useState(null);
|
||||
|
||||
const changePassword = async () => {
|
||||
if (!oldPassword || !newPassword) { alert('请填写完整信息'); return; }
|
||||
if (newPassword.length < 6) { alert('新密码至少6位'); return; }
|
||||
try {
|
||||
await API.updatePassword(currentUser.id, oldPassword, newPassword);
|
||||
setPwStatus({ ok: true, msg: '✅ 密码修改成功' });
|
||||
setOldPassword('');
|
||||
setNewPassword('');
|
||||
} catch (err) {
|
||||
setPwStatus({ ok: false, msg: '❌ ' + err.message });
|
||||
}
|
||||
};
|
||||
|
||||
const changeEmail = async () => {
|
||||
if (!emailPassword || !newEmail) { alert('请填写完整信息'); return; }
|
||||
try {
|
||||
await API.updateEmail(currentUser.id, emailPassword, newEmail);
|
||||
setEmailStatus({ ok: true, msg: '✅ 邮箱修改成功' });
|
||||
setEmailPassword('');
|
||||
setNewEmail('');
|
||||
} catch (err) {
|
||||
setEmailStatus({ ok: false, msg: '❌ ' + err.message });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 12 }}>🔒 账户安全</h3>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>当前密码</label>
|
||||
<input type="password" value={oldPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setOldPassword(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>新密码</label>
|
||||
<input type="password" value={newPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewPassword(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changePassword}>修改密码</button>
|
||||
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444' }}>{pwStatus.msg}</div>}
|
||||
|
||||
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }}></div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>当前密码(验证身份)</label>
|
||||
<input type="password" value={emailPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setEmailPassword(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>新邮箱</label>
|
||||
<input type="email" value={newEmail} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewEmail(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changeEmail}>修改邮箱</button>
|
||||
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444' }}>{emailStatus.msg}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台:5 个 tab
|
||||
import { useState } from 'react';
|
||||
import { Icon } from './Icons';
|
||||
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';
|
||||
import AdminCustomPages from './admin/AdminCustomPages';
|
||||
|
||||
const TABS = [
|
||||
{ key: 'reports', label: '举报', icon: 'shieldAlert' },
|
||||
{ key: 'users', label: '用户', icon: 'users' },
|
||||
{ key: 'logs', label: '日志', icon: 'file' },
|
||||
{ key: 'links', label: '友链', icon: 'link' },
|
||||
{ key: 'custom', label: '自定义页面', icon: 'file' },
|
||||
{ key: 'settings', label: '论坛设置', icon: 'settings' },
|
||||
];
|
||||
|
||||
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><Icon name="shieldAlert" size={20} /> 管理后台</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)}
|
||||
>
|
||||
<Icon name={t.icon} size={14} /> {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 === 'custom' && <AdminCustomPages />}
|
||||
{tab === 'settings' && <AdminForumSettings />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
'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 | user | custom
|
||||
const [currentPostId, setCurrentPostId] = useState(null);
|
||||
const [currentUsername, setCurrentUsername] = useState(null);
|
||||
const [currentPageName, setCurrentPageName] = 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');
|
||||
const userParam = params.get('user');
|
||||
if (postParam) {
|
||||
setView('post');
|
||||
setCurrentPostId(postParam);
|
||||
} else if (userParam) {
|
||||
setView('user');
|
||||
setCurrentUsername(userParam);
|
||||
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
|
||||
setView(pageParam);
|
||||
} else if (pageParam) {
|
||||
// 未知 page 参数视为自定义页面
|
||||
setView('custom');
|
||||
setCurrentPageName(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');
|
||||
url.searchParams.delete('user');
|
||||
window.history.pushState({ page: 'post', postId }, '', url);
|
||||
setView('post');
|
||||
setCurrentPostId(postId);
|
||||
}, []);
|
||||
|
||||
const openUser = useCallback((username) => {
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.set('user', username);
|
||||
url.searchParams.delete('page');
|
||||
url.searchParams.delete('post');
|
||||
window.history.pushState({ page: 'user', username }, '', url);
|
||||
setView('user');
|
||||
setCurrentUsername(username);
|
||||
}, []);
|
||||
|
||||
const openCustomPage = useCallback((pageName) => {
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.set('page', pageName);
|
||||
url.searchParams.delete('post');
|
||||
url.searchParams.delete('user');
|
||||
window.history.pushState({ page: 'custom', pageName }, '', url);
|
||||
setView('custom');
|
||||
setCurrentPageName(pageName);
|
||||
}, []);
|
||||
|
||||
// 浏览器前进后退
|
||||
useEffect(() => {
|
||||
const onPop = (e) => {
|
||||
const state = e.state || {};
|
||||
if (state.postId) {
|
||||
setView('post');
|
||||
setCurrentPostId(state.postId);
|
||||
} else if (state.username) {
|
||||
setView('user');
|
||||
setCurrentUsername(state.username);
|
||||
} else if (state.pageName) {
|
||||
setView('custom');
|
||||
setCurrentPageName(state.pageName);
|
||||
} else {
|
||||
setView(state.page || 'feed');
|
||||
setCurrentPostId(null);
|
||||
setCurrentUsername(null);
|
||||
setCurrentPageName(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,
|
||||
currentUsername, openUser,
|
||||
currentPageName, openCustomPage,
|
||||
sort, setSort,
|
||||
refreshKey, refresh,
|
||||
login, register, logout,
|
||||
};
|
||||
|
||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
'use client';
|
||||
|
||||
// 自定义页面:以 iframe srcdoc 渲染 HTML 内容(与原版一致)
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function CustomPage({ pageName }) {
|
||||
const [html, setHtml] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
setHtml(null);
|
||||
setError(null);
|
||||
API.getCustomPage(pageName)
|
||||
.then((page) => setHtml(page.content))
|
||||
.catch((err) => setError(err.message));
|
||||
}, [pageName]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div style={{ padding: '84px 32px', textAlign: 'center', color: '#ef4444' }}>
|
||||
页面加载失败:{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (html === null) {
|
||||
return <div style={{ padding: '84px 32px', textAlign: 'center', color: '#94a3b8' }}>加载中...</div>;
|
||||
}
|
||||
|
||||
const srcdoc = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
padding: 24px;
|
||||
background: var(--bg, #f6f8fc);
|
||||
color: var(--text, #0a0e1a);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { background: #0f1117; color: #e8edf5; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>${html}</body>
|
||||
</html>`;
|
||||
|
||||
return (
|
||||
<div style={{ padding: '84px 32px 40px', background: 'var(--bg)', minHeight: '100vh' }}>
|
||||
<iframe
|
||||
style={{ width: '100%', minHeight: '70vh', border: 'none', borderRadius: 8, background: 'var(--surface)' }}
|
||||
sandbox="allow-scripts allow-modals allow-same-origin"
|
||||
srcDoc={srcdoc}
|
||||
title={pageName}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
'use client';
|
||||
|
||||
// 信息流:帖子列表 + 排序 tab + 发布新帖按钮
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
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, openUser, navigate, refreshKey } = useApp();
|
||||
const [posts, setPosts] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
const load = useCallback(async (targetPage) => {
|
||||
setPosts(null);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
|
||||
setPosts(result.data || []);
|
||||
setTotalPages(result.pagination?.totalPages || 1);
|
||||
setPage(result.pagination?.page || 1);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setPosts([]);
|
||||
}
|
||||
}, [sort, refreshKey]);
|
||||
|
||||
useEffect(() => { load(page); }, [load]);
|
||||
|
||||
// 排序切换时回第一页
|
||||
useEffect(() => { setPage(1); }, [sort]);
|
||||
|
||||
const handleDelete = async (postId) => {
|
||||
if (!confirm('确定要删除这条帖子吗?')) return;
|
||||
try {
|
||||
await API.deletePost(postId);
|
||||
load(page);
|
||||
} 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');
|
||||
}}
|
||||
>
|
||||
<Icon name="plus" /> 发布新帖
|
||||
</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"
|
||||
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||
onClick={(e) => { e.stopPropagation(); openUser(p.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>
|
||||
<Icon name="message" size={14} /> {p.reply_count || 0}
|
||||
</span>
|
||||
<button className="action-report" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
onReport(p.id);
|
||||
}}>
|
||||
<Icon name="flag" size={14} /> 举报
|
||||
</button>
|
||||
{currentUser && currentUser.id === p.user_id && (
|
||||
<button className="action-delete" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDelete(p.id);
|
||||
}}>
|
||||
<Icon name="trash" size={14} /> 删除
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
{totalPages > 1 && posts && posts.length > 0 && (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 6, padding: '16px 0', marginTop: 8, borderTop: '1px solid var(--border)', flexWrap: 'wrap' }}>
|
||||
<button
|
||||
className="page-btn"
|
||||
disabled={page <= 1}
|
||||
onClick={() => load(page - 1)}
|
||||
style={{ padding: '6px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', color: 'var(--text)', cursor: page <= 1 ? 'not-allowed' : 'pointer', fontSize: 13, opacity: page <= 1 ? 0.4 : 1 }}
|
||||
>
|
||||
«
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((i) => (
|
||||
<button
|
||||
key={i}
|
||||
className="page-btn"
|
||||
disabled={i === page}
|
||||
onClick={() => load(i)}
|
||||
style={{
|
||||
padding: '6px 10px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, minWidth: 32, textAlign: 'center',
|
||||
background: i === page ? 'var(--primary)' : 'var(--surface)',
|
||||
color: i === page ? '#fff' : 'var(--text)',
|
||||
cursor: i === page ? 'default' : 'pointer',
|
||||
borderColor: i === page ? 'var(--primary)' : 'var(--border)',
|
||||
}}
|
||||
>
|
||||
{i}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className="page-btn"
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => load(page + 1)}
|
||||
style={{ padding: '6px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', color: 'var(--text)', cursor: page >= totalPages ? 'not-allowed' : 'pointer', fontSize: 13, opacity: page >= totalPages ? 0.4 : 1 }}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client';
|
||||
|
||||
// 图标库 — SVG 内容逐字符提取自旧版 index.html (Feather Icons),与原版一致
|
||||
const S = {
|
||||
xmlns: 'http://www.w3.org/2000/svg', width: 16, height: 16, viewBox: '0 0 24 24',
|
||||
fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
|
||||
style: { display: 'inline', verticalAlign: 'middle' },
|
||||
};
|
||||
|
||||
export function Icon({ name, size = 16, ...rest }) {
|
||||
return <svg {...S} width={size} height={size} {...rest}>{PATHS[name] || null}</svg>;
|
||||
}
|
||||
|
||||
const PATHS = {
|
||||
message: (
|
||||
<>
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
||||
</>
|
||||
),
|
||||
settings: (
|
||||
<>
|
||||
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>
|
||||
</>
|
||||
),
|
||||
shieldAlert: (
|
||||
<>
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/>
|
||||
</>
|
||||
),
|
||||
moon: (
|
||||
<>
|
||||
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
|
||||
</>
|
||||
),
|
||||
logout: (
|
||||
<>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
|
||||
</>
|
||||
),
|
||||
book: (
|
||||
<>
|
||||
<path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><line x1="18" y1="12" x2="18" y2="12"/>
|
||||
</>
|
||||
),
|
||||
link: (
|
||||
<>
|
||||
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
|
||||
</>
|
||||
),
|
||||
plus: (
|
||||
<>
|
||||
<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
|
||||
</>
|
||||
),
|
||||
shield: (
|
||||
<>
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
||||
</>
|
||||
),
|
||||
users: (
|
||||
<>
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||
</>
|
||||
),
|
||||
file: (
|
||||
<>
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/>
|
||||
</>
|
||||
),
|
||||
plus2: (
|
||||
<>
|
||||
<path d="M12 5v14"/><path d="M5 12h14"/>
|
||||
</>
|
||||
),
|
||||
close: (
|
||||
<>
|
||||
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</>
|
||||
),
|
||||
trash: (
|
||||
<>
|
||||
<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
|
||||
</>
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
'use client';
|
||||
|
||||
// 消息页:通知列表(回复/删除/举报处理/系统)
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
const TYPE_MAP = { reply: '💬', post_deleted: '🗑️', report_handled: '🛡️', system: '📢' };
|
||||
|
||||
export default function MessagesPage() {
|
||||
const { currentUser } = useApp();
|
||||
const [notifications, setNotifications] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentUser) return;
|
||||
API.getNotifications()
|
||||
.then((data) => {
|
||||
setNotifications(data || []);
|
||||
setError(null);
|
||||
API.markAllNotificationsRead().catch(() => {});
|
||||
})
|
||||
.catch((e) => { setError(e.message); setNotifications([]); });
|
||||
}, [currentUser]);
|
||||
|
||||
if (!currentUser) {
|
||||
return <div className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>请先登录</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<h2><Icon name="message" size={20} /> 消息</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
{error ? (
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>
|
||||
) : notifications === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||
) : notifications.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>
|
||||
<Icon name="message" size={48} />
|
||||
<p style={{ fontSize: 16 }}>暂无消息</p>
|
||||
<p style={{ fontSize: 13 }}>当有人回复你的帖子或处理你的举报时,会在这里通知你</p>
|
||||
</div>
|
||||
) : (
|
||||
notifications.map((n) => {
|
||||
const icon = TYPE_MAP[n.type] || '📌';
|
||||
const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={n.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', borderBottom: '1px solid var(--border-light)', background: 'var(--surface)', borderRadius: 6, marginBottom: 6 }}>
|
||||
<span style={{ fontSize: 20 }}>{icon}</span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 14 }}>{n.title}</div>
|
||||
<div style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 2 }}>{n.content}</div>
|
||||
{n.link && <a href={n.link} style={{ color: 'var(--primary)', fontSize: 13, textDecoration: 'none', marginTop: 4, display: 'inline-block' }}>查看详情 →</a>}
|
||||
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 4 }}>{time}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
'use client';
|
||||
|
||||
// 登录/注册/举报 模态框
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
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}><Icon name="close" size={20} /></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}><Icon name="close" size={20} /></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}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}><Icon name="shieldAlert" size={20} /> 举报帖子</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,121 @@
|
||||
'use client';
|
||||
|
||||
// 导航栏:论坛名、自定义页面链接、登录/注册、用户菜单、主题切换
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function Navbar({ onOpenModal }) {
|
||||
const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [customPages, setCustomPages] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
API.getCustomPages().then(setCustomPages).catch(() => {});
|
||||
}, []);
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
const openMessages = (e) => {
|
||||
e.preventDefault();
|
||||
setMenuOpen(false);
|
||||
// 打开私信列表(ChatManager 监听)
|
||||
window.dispatchEvent(new CustomEvent('forumlify-open-messages'));
|
||||
};
|
||||
|
||||
return (
|
||||
<nav id="navbar">
|
||||
<div className="nav-left">
|
||||
<span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}>
|
||||
{forumName}
|
||||
</span>
|
||||
<span id="customNavLinks" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 16 }}>
|
||||
{customPages.map((p) => (
|
||||
<a
|
||||
key={p.id}
|
||||
href="#"
|
||||
className="custom-page-nav-link"
|
||||
data-custom={p.name}
|
||||
onClick={(e) => { e.preventDefault(); openCustomPage(p.name); }}
|
||||
style={{ color: 'var(--text-secondary)', textDecoration: 'none', fontSize: 14, padding: '4px 10px', borderRadius: 4, transition: 'color 0.15s' }}
|
||||
onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--text)'; }}
|
||||
onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-secondary)'; }}
|
||||
>
|
||||
{p.title}
|
||||
</a>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
<div 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={openMessages}>
|
||||
<Icon name="message" /> 消息
|
||||
</a>
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}>
|
||||
<Icon name="settings" /> 设置
|
||||
</a>
|
||||
{currentUser.role === 'admin' && (
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('admin'); }}>
|
||||
<Icon name="shieldAlert" /> 管理后台
|
||||
</a>
|
||||
)}
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
toggleTheme();
|
||||
setMenuOpen(false);
|
||||
}}
|
||||
>
|
||||
<Icon name={theme === 'dark' ? 'sun' : 'moon'} /> {theme === 'dark' ? '亮色模式' : '暗色模式'}
|
||||
</a>
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (confirm('确定要退出吗?')) {
|
||||
setMenuOpen(false);
|
||||
logout();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon name="logout" /> 退出
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
'use client';
|
||||
|
||||
// 发布新帖页
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { API, generateCaptcha, uploadImage } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
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) {
|
||||
if (!file.type.startsWith('image/')) continue;
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
|
||||
continue;
|
||||
}
|
||||
const dataUrl = await new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => resolve(e.target.result);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
newPreviews.push(dataUrl);
|
||||
const url = await uploadImage(file);
|
||||
setImages((prev) => [...prev, url]);
|
||||
}
|
||||
setPreviews((prev) => [...prev, ...newPreviews]);
|
||||
} catch (err) {
|
||||
alert('上传失败:' + err.message);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 拖拽上传
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const fileInputRef = useRef(null);
|
||||
const dropZoneStyle = {
|
||||
border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'),
|
||||
borderRadius: 8, padding: 24, textAlign: 'center', cursor: 'pointer',
|
||||
transition: 'all 0.3s', margin: '8px 0 12px',
|
||||
background: dragOver ? 'var(--primary-bg)' : 'var(--bg)',
|
||||
};
|
||||
|
||||
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><Icon name="plus" size={20} /> 发布新帖</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 var(--border)' }} />
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
id="dropZone"
|
||||
style={dropZoneStyle}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
|
||||
onDragLeave={(e) => { e.preventDefault(); setDragOver(false); }}
|
||||
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files) handleFiles(Array.from(e.dataTransfer.files)); }}
|
||||
>
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
|
||||
{uploading ? '上传中...' : (dragOver ? '松开上传' : '📷 点击或拖拽上传图片')}
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
id="fileInput"
|
||||
accept="image/*"
|
||||
multiple
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={(e) => { if (e.target.files) handleFiles(Array.from(e.target.files)); }}
|
||||
/>
|
||||
<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,96 @@
|
||||
'use client';
|
||||
|
||||
// 帖子详情页
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import ReplyList from './ReplyList';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
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, openUser, 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"
|
||||
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||
onClick={() => openUser(post.username)}
|
||||
>
|
||||
{post.username || '匿名用户'}
|
||||
</span>
|
||||
<span className="post-time">{time}</span>
|
||||
{canDelete && (
|
||||
<button className="btn-sm btn-danger" onClick={handleDelete}>
|
||||
<Icon name="trash" size={14} /> 删除
|
||||
</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,65 @@
|
||||
'use client';
|
||||
|
||||
// 恢复码管理:查看 + 重新生成
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function RecoveryCodes() {
|
||||
const [count, setCount] = useState(0);
|
||||
const [modal, setModal] = useState(null); // null | {codes, isNew}
|
||||
|
||||
const loadCount = () => {
|
||||
API.getRecoveryCodeCount().then((d) => setCount(d.count || 0)).catch(() => {});
|
||||
};
|
||||
useEffect(loadCount, []);
|
||||
|
||||
const regenerate = async () => {
|
||||
if (!confirm('重新生成将使所有旧恢复码失效,确定继续吗?')) return;
|
||||
try {
|
||||
const d = await API.generateRecoveryCodes();
|
||||
setModal({ codes: d.codes || [], isNew: true });
|
||||
loadCount();
|
||||
} catch (err) {
|
||||
alert('生成失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const view = async () => {
|
||||
try {
|
||||
// 生成后直接展示;若已有恢复码则重新生成展示(与原版一致:查看即生成新码)
|
||||
const d = await API.generateRecoveryCodes();
|
||||
setModal({ codes: d.codes || [], isNew: false });
|
||||
loadCount();
|
||||
} catch (err) {
|
||||
alert('获取失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 8 }}>🔑 恢复码</h3>
|
||||
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>用于忘记密码时重置账户。每个恢复码只能使用一次。</p>
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={view}>📋 查看恢复码</button>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={regenerate}>🔄 重新生成</button>
|
||||
</div>
|
||||
<div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>剩余 {count} 个可用恢复码</div>
|
||||
|
||||
{modal && (
|
||||
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setModal(null); }}>
|
||||
<div className="modal-content" style={{ maxWidth: 480, position: 'relative' }}>
|
||||
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setModal(null)}>×</span>
|
||||
<h2 style={{ marginBottom: 12 }}>{modal.isNew ? '🆕 新恢复码' : '🔑 恢复码'}</h2>
|
||||
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12 }}>⚠️ 请妥善保存这些恢复码,关闭窗口后无法再次查看。</p>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
|
||||
{modal.codes.map((c, i) => (
|
||||
<code key={i} style={{ background: 'var(--bg)', padding: '8px 12px', borderRadius: 6, fontSize: 13, textAlign: 'center', userSelect: 'all' }}>{c}</code>
|
||||
))}
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={() => setModal(null)}>我已保存</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
'use client';
|
||||
|
||||
// 回复列表 + 发表回复表单
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API, generateCaptcha } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
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, openUser } = 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' }}>
|
||||
<Icon name="message" size={14} /> {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"
|
||||
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||
onClick={() => openUser(r.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)}>
|
||||
<Icon name="trash" size={12} /> 删除
|
||||
</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 }}><Icon name="message" size={16} /> 发表回复</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,93 @@
|
||||
'use client';
|
||||
|
||||
// 个人设置页:头像 + 基本资料 + 账户安全 + 恢复码
|
||||
import { useState, useRef } from 'react';
|
||||
import { API, uploadImage } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import AccountSecurity from './AccountSecurity';
|
||||
import RecoveryCodes from './RecoveryCodes';
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { currentUser, setCurrentUser } = useApp();
|
||||
const [username, setUsername] = useState(currentUser?.username || '');
|
||||
const [bio, setBio] = useState(currentUser?.bio || '');
|
||||
const [avatarUrl, setAvatarUrl] = useState(currentUser?.avatar_url || '');
|
||||
const [avatarStatus, setAvatarStatus] = useState(null);
|
||||
const avatarInputRef = useRef(null);
|
||||
|
||||
const handleAvatar = async (file) => {
|
||||
if (!file) return;
|
||||
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: '❌ 请选择图片文件' }); return; }
|
||||
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: '❌ 图片不能超过 5MB' }); return; }
|
||||
try {
|
||||
const url = await uploadImage(file);
|
||||
await API.updateAvatar(currentUser.id, url);
|
||||
setAvatarUrl(url);
|
||||
setCurrentUser({ ...currentUser, avatar_url: url });
|
||||
setAvatarStatus({ ok: true, msg: '✅ 头像已更新' });
|
||||
} catch (err) {
|
||||
setAvatarStatus({ ok: false, msg: '❌ ' + err.message });
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
const avatarSrc = avatarUrl ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') + '&background=6366f1&color=fff&size=128';
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 500, margin: '0 auto', width: '100%' }}>
|
||||
<h2><Icon name="settings" size={20} /> 设置</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 500, margin: '0 auto', width: '100%', padding: '20px 0' }}>
|
||||
{/* 头像 */}
|
||||
<div style={{ textAlign: 'center', marginBottom: 24 }}>
|
||||
<div style={{ position: 'relative', display: 'inline-block' }}>
|
||||
<img src={avatarSrc} style={{ width: 100, height: 100, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
|
||||
<button
|
||||
style={{ position: 'absolute', bottom: 0, right: 0, background: 'var(--primary)', color: '#fff', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(99,102,241,0.4)' }}
|
||||
onClick={() => avatarInputRef.current?.click()}
|
||||
>
|
||||
📷
|
||||
</button>
|
||||
</div>
|
||||
<input type="file" ref={avatarInputRef} accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files?.[0]) handleAvatar(e.target.files[0]); }} />
|
||||
<h2 style={{ margin: '12px 0 4px' }}>{currentUser?.username}</h2>
|
||||
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || '这个人很懒,什么都没写'}</p>
|
||||
{avatarStatus && (
|
||||
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444' }}>{avatarStatus.msg}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 基本资料 */}
|
||||
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>用户名</label>
|
||||
<input type="text" value={username} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setUsername(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>个人简介</label>
|
||||
<textarea rows={3} value={bio} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }} onChange={(e) => setBio(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>保存设置</button>
|
||||
</div>
|
||||
|
||||
<AccountSecurity />
|
||||
<RecoveryCodes />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
'use client';
|
||||
|
||||
// 侧边栏:社区统计 + 友情链接
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
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>
|
||||
<Icon name="book" size={14} /> 社区统计
|
||||
</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>
|
||||
<Icon name="link" size={14} /> 友情链接
|
||||
</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,97 @@
|
||||
'use client';
|
||||
|
||||
// 用户主页:资料卡 + 该用户的帖子列表
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { useOpenPrivateChat } from './chat/ChatManager';
|
||||
|
||||
function avatar(username, size = 128) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
'&background=6366f1&color=fff&size=' + size;
|
||||
}
|
||||
|
||||
export default function UserProfile({ username }) {
|
||||
const { currentUser, openPost } = useApp();
|
||||
const openPrivateChat = useOpenPrivateChat();
|
||||
const [user, setUser] = useState(null);
|
||||
const [posts, setPosts] = useState([]);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const users = await API.getUsersByUsername(username);
|
||||
const u = users && users.length > 0 ? users[0] : null;
|
||||
if (!u) {
|
||||
setError('用户不存在');
|
||||
return;
|
||||
}
|
||||
setUser(u);
|
||||
const result = await API.getPosts('latest', u.id);
|
||||
setPosts(result.data || []);
|
||||
} catch (err) {
|
||||
setError(err.message || '加载失败');
|
||||
}
|
||||
}, [username]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!user) {
|
||||
return <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<h2><Icon name="users" size={20} /> 用户主页</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 32, textAlign: 'center' }}>
|
||||
<img src={avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
|
||||
<h2 style={{ margin: '16px 0 4px', fontSize: 24 }}>{user.username}</h2>
|
||||
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
||||
{currentUser && currentUser.id !== user.id && (
|
||||
<button
|
||||
className="btn-primary"
|
||||
style={{ marginTop: 12, padding: '8px 20px' }}
|
||||
onClick={() => openPrivateChat(user.id, user.username)}
|
||||
>
|
||||
<Icon name="message" size={14} /> 发私信
|
||||
</button>
|
||||
)}
|
||||
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
||||
<span>📅 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
||||
<span>📝 发了 {posts.length} 个帖子</span>
|
||||
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}>🛡️ 管理员</span>}
|
||||
</div>
|
||||
</div>
|
||||
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}>📝 发布的帖子</h3>
|
||||
{posts.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</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-title" style={{ fontSize: 16, fontWeight: 600 }}>{p.title || '无标题'}</div>
|
||||
<div className="post-content" style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
|
||||
{(p.content || '').substring(0, 100)}{(p.content || '').length > 100 ? '...' : ''}
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 8 }}>{time}</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 自定义页面管理(列表)
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import CustomPageEditor from './CustomPageEditor';
|
||||
|
||||
export default function AdminCustomPages() {
|
||||
const [pages, setPages] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
const [editing, setEditing] = useState(null); // null | 'new' | page对象
|
||||
|
||||
const load = () => {
|
||||
API.adminGetCustomPages()
|
||||
.then((data) => { setPages(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setPages([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleDelete = async (p) => {
|
||||
if (!confirm('确定要删除这个页面吗?')) return;
|
||||
try {
|
||||
await API.adminDeleteCustomPage(p.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('删除失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
|
||||
<h3 style={{ margin: 0 }}>📄 自定义页面</h3>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}>➕ 添加页面</button>
|
||||
</div>
|
||||
<div id="customPageList">
|
||||
{pages === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>加载中...</div>
|
||||
) : pages.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>暂无自定义页面</div>
|
||||
) : (
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
|
||||
<th style={{ padding: '8px 12px' }}>名称</th>
|
||||
<th style={{ padding: '8px 12px' }}>标题</th>
|
||||
<th style={{ padding: '8px 12px' }}>URL</th>
|
||||
<th style={{ padding: '8px 12px' }}>状态</th>
|
||||
<th style={{ padding: '8px 12px', textAlign: 'center' }}>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{pages.map((p) => (
|
||||
<tr key={p.id} style={{ borderBottom: '1px solid var(--border-light)' }}>
|
||||
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>{p.name}</code></td>
|
||||
<td style={{ padding: '8px 12px' }}>{p.title}</td>
|
||||
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>?custom={p.name}</code></td>
|
||||
<td style={{ padding: '8px 12px' }}>
|
||||
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444' }}>{p.enabled ? '✅ 启用' : '❌ 禁用'}</span>
|
||||
</td>
|
||||
<td style={{ padding: '8px 12px', textAlign: 'center', display: 'flex', gap: 6, justifyContent: 'center' }}>
|
||||
<button className="btn-sm btn-secondary" onClick={() => setEditing(p)}>✏️</button>
|
||||
<button className="btn-sm btn-danger" onClick={() => handleDelete(p)}>🗑️</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<CustomPageEditor
|
||||
page={editing === 'new' ? null : editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => { setEditing(null); load(); }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 论坛设置
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
import { Icon } from '../Icons';
|
||||
|
||||
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 }}><Icon name="settings" size={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,69 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 友情链接管理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
|
||||
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)}>
|
||||
<Icon name="trash" size={12} /> 删除
|
||||
</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,67 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 举报处理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
|
||||
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')}>
|
||||
<Icon name="trash" size={12} /> 删除帖子
|
||||
</button>
|
||||
<button className="btn-sm btn-secondary" onClick={() => handleAction(r, 'reject')}>
|
||||
<Icon name="close" size={12} /> 驳回举报
|
||||
</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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 自定义页面编辑器(modal)
|
||||
import { useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function CustomPageEditor({ page, onClose, onSaved }) {
|
||||
const isEdit = !!page;
|
||||
const [name, setName] = useState(page?.name || '');
|
||||
const [title, setTitle] = useState(page?.title || '');
|
||||
const [content, setContent] = useState(page?.content || '');
|
||||
const [enabled, setEnabled] = useState(page?.enabled !== false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!name.trim()) { alert('请输入页面名称'); return; }
|
||||
if (!title.trim()) { alert('请输入导航栏显示名称'); return; }
|
||||
if (!content.trim()) { alert('请输入页面内容'); return; }
|
||||
if (!/^[a-zA-Z0-9\-_]+$/.test(name.trim())) {
|
||||
alert('页面名称只允许字母、数字、短横线和下划线');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (isEdit) {
|
||||
await API.adminUpdateCustomPage(page.id, title.trim(), content.trim(), enabled);
|
||||
} else {
|
||||
await API.adminCreateCustomPage(name.trim(), title.trim(), content.trim());
|
||||
}
|
||||
onSaved();
|
||||
} catch (err) {
|
||||
alert('保存失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="modal-content" style={{ maxWidth: 600, maxHeight: '90vh', overflowY: 'auto', position: 'relative' }}>
|
||||
<span className="close" style={{ position: 'absolute', top: 12, right: 16, fontSize: 24, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}>×</span>
|
||||
<h2 style={{ marginBottom: 16 }}>{isEdit ? '✏️ 编辑页面' : '📄 添加页面'}</h2>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面名称</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
readOnly={isEdit}
|
||||
placeholder="about (用于 URL: ?custom=about)"
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: isEdit ? 'var(--border-light)' : 'var(--bg)', color: 'var(--text)' }}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
{isEdit
|
||||
? <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>⚠️ 名称不可修改</div>
|
||||
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>只允许字母、数字、短横线和下划线</div>}
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>导航栏显示名称</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
placeholder="关于我们"
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>状态</label>
|
||||
<select
|
||||
value={String(enabled)}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
onChange={(e) => setEnabled(e.target.value === 'true')}
|
||||
>
|
||||
<option value="true">启用</option>
|
||||
<option value="false">禁用</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>页面内容(HTML + CSS + JS)</label>
|
||||
<textarea
|
||||
rows={12}
|
||||
value={content}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, fontFamily: 'monospace', background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染</div>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>保存</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
'use client';
|
||||
|
||||
// 私信管理器:会话列表 modal + 聊天窗口 modal + 未读 badge + openPrivateChat
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
import ConversationList from './ConversationList';
|
||||
import ChatWindow from './ChatWindow';
|
||||
|
||||
export default function ChatManager() {
|
||||
const { currentUser } = useApp();
|
||||
const [listOpen, setListOpen] = useState(false);
|
||||
const [chat, setChat] = useState(null); // {conversationId, otherUserId, otherUsername}
|
||||
const [unread, setUnread] = useState(0);
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
|
||||
const refreshList = useCallback(() => setRefreshKey((k) => k + 1), []);
|
||||
|
||||
// 未读 badge 轮询(30 秒 + 每次刷新)
|
||||
useEffect(() => {
|
||||
if (!currentUser) return;
|
||||
const update = () => {
|
||||
API.getConversations()
|
||||
.then((cs) => {
|
||||
const total = (cs || []).reduce((s, c) => s + (c.unread_count || 0), 0);
|
||||
setUnread(total);
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
update();
|
||||
const t = setInterval(update, 30000);
|
||||
return () => clearInterval(t);
|
||||
}, [currentUser, refreshKey]);
|
||||
|
||||
// 监听其他组件发起的打开私信事件
|
||||
useEffect(() => {
|
||||
const handler = (e) => {
|
||||
setChat(e.detail);
|
||||
setListOpen(false);
|
||||
};
|
||||
const openList = () => setListOpen(true);
|
||||
window.addEventListener('forumlify-open-chat', handler);
|
||||
window.addEventListener('forumlify-open-messages', openList);
|
||||
return () => {
|
||||
window.removeEventListener('forumlify-open-chat', handler);
|
||||
window.removeEventListener('forumlify-open-messages', openList);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const openChat = (conversationId, otherUserId, otherUsername) => {
|
||||
setChat({ conversationId, otherUserId, otherUsername });
|
||||
setListOpen(false);
|
||||
};
|
||||
|
||||
const closeChat = () => {
|
||||
setChat(null);
|
||||
refreshList();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 导航栏私信按钮 + 未读 badge */}
|
||||
<button
|
||||
className="nav-icon-btn"
|
||||
title="私信"
|
||||
style={{ position: 'relative', padding: '6px 8px', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-secondary)', borderRadius: 4, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
onClick={() => setListOpen(true)}
|
||||
>
|
||||
✉️
|
||||
{unread > 0 && (
|
||||
<span style={{ position: 'absolute', top: -2, right: -2, background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 6px', fontSize: 10, fontWeight: 600, minWidth: 18, textAlign: 'center', lineHeight: 1.4 }}>
|
||||
{unread > 99 ? '99+' : unread}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{listOpen && (
|
||||
<ConversationList
|
||||
onOpenChat={openChat}
|
||||
onClose={() => setListOpen(false)}
|
||||
/>
|
||||
)}
|
||||
{chat && (
|
||||
<ChatWindow
|
||||
conversationId={chat.conversationId}
|
||||
otherUserId={chat.otherUserId}
|
||||
otherUsername={chat.otherUsername}
|
||||
onClose={closeChat}
|
||||
onRefreshList={refreshList}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// 供其他组件调用的打开私信(通过自定义事件桥接)
|
||||
export function useOpenPrivateChat() {
|
||||
const { currentUser } = useApp();
|
||||
const open = async (otherUserId, otherUsername) => {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
try {
|
||||
const result = await API.getOrCreateConversation(otherUserId);
|
||||
window.dispatchEvent(new CustomEvent('forumlify-open-chat', {
|
||||
detail: { conversationId: result.id, otherUserId, otherUsername },
|
||||
}));
|
||||
} catch (err) {
|
||||
alert('打开私信失败:' + err.message);
|
||||
}
|
||||
};
|
||||
return open;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
'use client';
|
||||
|
||||
// 私信 - 聊天窗口(3 秒轮询新消息)
|
||||
import { useEffect, useState, useRef, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
|
||||
const { currentUser } = useApp();
|
||||
const [messages, setMessages] = useState(null);
|
||||
const [content, setContent] = useState('');
|
||||
const containerRef = useRef(null);
|
||||
|
||||
const load = useCallback(async (silent = false) => {
|
||||
if (!silent) setMessages(null);
|
||||
try {
|
||||
const data = await API.getMessages(conversationId);
|
||||
setMessages(data || []);
|
||||
} catch {
|
||||
if (!silent) setMessages([]);
|
||||
}
|
||||
}, [conversationId]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// 3 秒轮询
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => load(true), 3000);
|
||||
return () => clearInterval(t);
|
||||
}, [load]);
|
||||
|
||||
// 自动滚动到底部
|
||||
useEffect(() => {
|
||||
if (containerRef.current) containerRef.current.scrollTop = containerRef.current.scrollHeight;
|
||||
}, [messages]);
|
||||
|
||||
const send = async () => {
|
||||
if (!content.trim()) return;
|
||||
try {
|
||||
await API.sendMessage(conversationId, content.trim());
|
||||
setContent('');
|
||||
load();
|
||||
onRefreshList();
|
||||
} catch (err) {
|
||||
alert('发送失败:' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
||||
<span id="chatTitle" style={{ fontWeight: 600, fontSize: 16 }}>{otherUsername}</span>
|
||||
<span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>×</span>
|
||||
</div>
|
||||
<div id="chatMessages" ref={containerRef} style={{ flex: 1, overflowY: 'auto', padding: 16, minHeight: 300, maxHeight: 400 }}>
|
||||
{messages === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||
) : messages.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>还没有消息,打个招呼吧 👋</div>
|
||||
) : (
|
||||
messages.map((m) => {
|
||||
const isMine = m.sender_id === currentUser?.id;
|
||||
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
|
||||
{!isMine && (
|
||||
<img src={m.sender_avatar_url || avatar(m.sender_username)} style={{ width: 32, height: 32, borderRadius: '50%', objectFit: 'cover', marginRight: 8, flexShrink: 0 }} alt="" />
|
||||
)}
|
||||
<div style={{ maxWidth: '70%' }}>
|
||||
<div style={{
|
||||
background: isMine ? 'var(--primary)' : 'var(--surface)',
|
||||
color: isMine ? '#fff' : 'var(--text)',
|
||||
padding: '10px 14px', borderRadius: 12,
|
||||
border: isMine ? 'none' : '1px solid var(--border)',
|
||||
wordBreak: 'break-word',
|
||||
}}>
|
||||
{m.content}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--text-light)', marginTop: 4, textAlign: isMine ? 'right' : 'left' }}>
|
||||
{time} {isMine ? (m.is_read ? '✓✓' : '✓') : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, padding: '12px 16px', borderTop: '1px solid var(--border)' }}>
|
||||
<input
|
||||
type="text"
|
||||
id="chatInput"
|
||||
placeholder="输入消息..."
|
||||
style={{ flex: 1, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={send}>发送</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
'use client';
|
||||
|
||||
// 私信 - 会话列表
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function ConversationList({ onOpenChat, onClose }) {
|
||||
const [conversations, setConversations] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getConversations()
|
||||
.then((data) => setConversations(data || []))
|
||||
.catch(() => setConversations([]));
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
return (
|
||||
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
||||
<h2 style={{ fontSize: 18, margin: 0 }}>✉️ 私信</h2>
|
||||
<span className="close" onClick={onClose} style={{ fontSize: 24, cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}>×</span>
|
||||
</div>
|
||||
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
|
||||
{conversations === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||
) : conversations.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>暂无私信</div>
|
||||
) : (
|
||||
conversations.map((c) => {
|
||||
const unread = c.unread_count || 0;
|
||||
const lastMsg = c.last_message || '暂无消息';
|
||||
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div
|
||||
key={c.id}
|
||||
className="message-list-item"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderBottom: '1px solid var(--border)', cursor: 'pointer', transition: 'background 0.15s' }}
|
||||
onClick={() => onOpenChat(c.id, c.other_user_id, c.other_username)}
|
||||
>
|
||||
<img src={c.other_avatar_url || avatar(c.other_username)} style={{ width: 40, height: 40, borderRadius: '50%', objectFit: 'cover' }} alt="" />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontWeight: 600 }}>{c.other_username}</span>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-light)' }}>{time}</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 200 }}>{lastMsg}</span>
|
||||
{unread > 0 && (
|
||||
<span style={{ background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 8px', fontSize: 11, fontWeight: 600 }}>{unread}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,11 @@ const CONFIG = {
|
||||
// 服务端监听端口(仅服务端读取,浏览器端忽略)
|
||||
// 优先级:环境变量 PORT > SERVER_PORT > 默认 3000
|
||||
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"]
|
||||
-352
@@ -1,352 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title id="pageTitle">Forumlify</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- ===== 导航栏 ===== -->
|
||||
<nav id="navbar">
|
||||
<div class="nav-left">
|
||||
<span id="forumName" class="forum-name">Forumlify</span>
|
||||
<span id="customNavLinks" style="display:inline-flex;align-items:center;gap:6px;margin-left:16px;"></span>
|
||||
</div>
|
||||
<div class="nav-right">
|
||||
<div id="userMenu">
|
||||
<div id="authButtons">
|
||||
<button id="loginBtn" class="btn-ghost">登录</button>
|
||||
<button id="registerBtn" class="btn-primary">注册</button>
|
||||
</div>
|
||||
<div id="userDropdown" style="display:none">
|
||||
<button id="messageBtn" class="nav-icon-btn" title="私信" style="position:relative;padding:6px 8px;background:none;border:none;cursor:pointer;color:var(--text-secondary);border-radius:4px;display:inline-flex;align-items:center;justify-content:center;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
<span id="messageBadge" style="display:none;position:absolute;top:-2px;right:-2px;background:#ef4444;color:#fff;border-radius:50%;padding:2px 6px;font-size:10px;font-weight:600;min-width:18px;text-align:center;line-height:1.4;"></span>
|
||||
</button>
|
||||
<img id="avatarImg" class="avatar" src="" alt="avatar" />
|
||||
<div class="dropdown-menu" id="dropdownMenu">
|
||||
<a href="#" data-page="messages">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
消息
|
||||
</a>
|
||||
<a href="#" data-page="settings">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||
设置
|
||||
</a>
|
||||
<a href="#" data-page="admin" id="adminEntry" style="display:none">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
||||
管理后台
|
||||
</a>
|
||||
<hr />
|
||||
<a href="#" id="themeToggle" style="display:flex;align-items:center;gap:8px;">
|
||||
<svg id="themeIcon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
|
||||
</svg>
|
||||
<span id="themeLabel">暗色模式</span>
|
||||
</a>
|
||||
<hr />
|
||||
<a href="#" id="logoutBtn">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
|
||||
退出
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- ===== 主内容区 ===== -->
|
||||
<div id="app">
|
||||
<aside id="sidebar">
|
||||
<div class="stats-box">
|
||||
<h4>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><line x1="18" y1="12" x2="18" y2="12"/></svg>
|
||||
社区统计
|
||||
</h4>
|
||||
<div class="stat-item"><span>主题</span><span id="statTopics">0</span></div>
|
||||
<div class="stat-item"><span>帖子</span><span id="statPosts">0</span></div>
|
||||
<div class="stat-item"><span>用户</span><span id="statUsers">0</span></div>
|
||||
<div class="stat-item"><span>在线</span><span id="statOnline">0</span></div>
|
||||
</div>
|
||||
<div class="links-box">
|
||||
<h4>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
|
||||
友情链接
|
||||
</h4>
|
||||
<ul id="friendlyLinks">
|
||||
<li style="color:#94a3b8;font-size:13px;">暂无链接</li>
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main id="feed">
|
||||
<div class="feed-header">
|
||||
<div class="feed-header-left">
|
||||
<button class="tab active" data-sort="latest">最新发布</button>
|
||||
<button class="tab" data-sort="hot">最新回复</button>
|
||||
</div>
|
||||
<button id="fab" class="btn-primary fab-btn">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||
发布新帖
|
||||
</button>
|
||||
</div>
|
||||
<div id="postList">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- ===== 独立页面 ===== -->
|
||||
<!-- 消息页面 -->
|
||||
<div id="pageMessages" class="page-slide">
|
||||
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;">
|
||||
<h2>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
消息
|
||||
</h2>
|
||||
</div>
|
||||
<div id="messagesContent" style="max-width:700px;margin:0 auto;width:100%;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 设置页面 -->
|
||||
<div id="pageSettings" class="page-slide">
|
||||
<div class="page-header" style="max-width:500px;margin:0 auto;width:100%;">
|
||||
<h2>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||
设置
|
||||
</h2>
|
||||
</div>
|
||||
<div id="settingsContent" style="max-width:500px;margin:0 auto;width:100%;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 管理后台 -->
|
||||
<div id="pageAdmin" class="page-slide">
|
||||
<div class="page-header" style="max-width:900px;margin:0 auto;width:100%;">
|
||||
<h2>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
||||
管理后台
|
||||
</h2>
|
||||
</div>
|
||||
<div class="admin-tabs" style="max-width:900px;margin:0 auto;width:100%;">
|
||||
<button class="admin-tab active" data-tab="reports">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
|
||||
举报
|
||||
</button>
|
||||
<button class="admin-tab" data-tab="users">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
|
||||
用户
|
||||
</button>
|
||||
<button class="admin-tab" data-tab="logs">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||
日志
|
||||
</button>
|
||||
<button class="admin-tab" data-tab="links">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
|
||||
友链
|
||||
</button>
|
||||
<button class="admin-tab" data-tab="settings">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||
论坛设置
|
||||
</button>
|
||||
<button class="admin-tab" data-tab="custom">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||
自定义页面
|
||||
</button>
|
||||
</div>
|
||||
<div id="adminContent" style="max-width:900px;margin:0 auto;width:100%;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 发布新帖 -->
|
||||
<div id="pageNew" class="page-slide">
|
||||
<div class="page-header" style="max-width:600px;margin:0 auto;width:100%;">
|
||||
<h2>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
|
||||
发布新帖
|
||||
</h2>
|
||||
</div>
|
||||
<div style="max-width:600px;margin:0 auto;width:100%;">
|
||||
<input type="text" id="postTitle" placeholder="标题" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:15px;font-weight:600;margin-bottom:12px;font-family:inherit;" />
|
||||
<textarea id="postContent" rows="6" placeholder="说点什么..." style="width:100%;padding:12px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:15px;font-family:inherit;resize:vertical;"></textarea>
|
||||
<div id="dropZone" style="border:2px dashed var(--border);border-radius:8px;padding:24px;text-align:center;cursor:pointer;transition:all 0.3s;margin:8px 0 12px;background:var(--bg);">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block;margin:0 auto 8px;color:var(--text-secondary);"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
|
||||
<p style="color:var(--text-secondary);font-size:14px;margin:0;">
|
||||
<span id="dropZoneText">点击或拖拽上传图片</span>
|
||||
</p>
|
||||
<p style="color:var(--text-light);font-size:12px;margin:4px 0 0;">支持 JPG、PNG、GIF、WebP,单张最大 5MB</p>
|
||||
<input type="file" id="fileInput" accept="image/*" multiple style="display:none;" />
|
||||
</div>
|
||||
<div id="imagePreview" style="display:flex;flex-wrap:wrap;gap:8px;margin:8px 0;"></div>
|
||||
<div class="captcha-row" style="margin:12px 0;">
|
||||
<span id="postCaptchaQuestion">3 + 5 = ?</span>
|
||||
<input type="text" id="postCaptchaInput" placeholder="答案" style="width:80px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
|
||||
</div>
|
||||
<button id="postSubmit" class="btn-primary" style="padding:10px 32px;font-size:15px;">发布帖子</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 帖子详情页 -->
|
||||
<div id="pagePost" class="page-slide">
|
||||
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;">
|
||||
<h2 id="postDetailTitle">帖子详情</h2>
|
||||
</div>
|
||||
<div id="postDetailContent" style="max-width:700px;margin:0 auto;width:100%;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
<div id="replyArea" style="max-width:700px;margin:0 auto;width:100%;margin-top:24px;border-top:1px solid #e2e8f0;padding-top:20px;display:none;">
|
||||
<h3 style="font-size:16px;margin-bottom:12px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
发表回复
|
||||
</h3>
|
||||
<textarea id="replyContent" rows="3" placeholder="写下你的回复..." style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:4px;font-size:14px;font-family:inherit;resize:vertical;"></textarea>
|
||||
<div class="captcha-row" style="margin:10px 0;">
|
||||
<span id="replyCaptchaQuestion">3 + 5 = ?</span>
|
||||
<input type="text" id="replyCaptchaInput" placeholder="答案" style="width:80px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
|
||||
</div>
|
||||
<button id="replySubmit" class="btn-primary" style="padding:8px 24px;">提交回复</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 用户主页 -->
|
||||
<div id="pageUser" class="page-slide">
|
||||
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;">
|
||||
<button class="back-btn" onclick="switchPage('feed')">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||
返回
|
||||
</button>
|
||||
<h2 id="userPageTitle">用户主页</h2>
|
||||
</div>
|
||||
<div id="userProfileContent" style="max-width:700px;margin:0 auto;width:100%;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 模态框 ===== -->
|
||||
<!-- 登录 -->
|
||||
<div id="loginModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" data-modal="loginModal">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</span>
|
||||
<h2 style="margin-bottom:16px;">登录</h2>
|
||||
<input type="email" id="loginEmail" placeholder="邮箱" />
|
||||
<input type="password" id="loginPassword" placeholder="密码" />
|
||||
<div style="text-align:center;margin-top:8px;">
|
||||
<a href="#" id="forgotPasswordLink" style="color:var(--primary);font-size:13px;text-decoration:none;">忘记密码?</a>
|
||||
</div>
|
||||
<button id="loginSubmit" class="btn-primary" style="width:100%;margin-top:8px;">登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 注册 -->
|
||||
<div id="registerModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" data-modal="registerModal">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</span>
|
||||
<h2 style="margin-bottom:16px;">注册</h2>
|
||||
<input type="text" id="regUsername" placeholder="用户名" />
|
||||
<input type="email" id="regEmail" placeholder="邮箱" />
|
||||
<input type="password" id="regPassword" placeholder="密码(至少6位)" />
|
||||
<div class="captcha-row">
|
||||
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
||||
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
||||
</div>
|
||||
<button id="registerSubmit" class="btn-primary" style="width:100%;">注册</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 举报 -->
|
||||
<div id="reportModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" data-modal="reportModal">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</span>
|
||||
<h2 style="margin-bottom:16px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
||||
举报帖子
|
||||
</h2>
|
||||
<p style="font-size:14px;color:#64748b;margin-bottom:12px;">请选择举报原因:</p>
|
||||
<select id="reportReason" style="width:100%;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;margin-bottom:16px;">
|
||||
<option value="spam">垃圾广告</option>
|
||||
<option value="abuse">人身攻击</option>
|
||||
<option value="illegal">违法内容</option>
|
||||
<option value="nsfw">不适当内容</option>
|
||||
<option value="other">其他</option>
|
||||
</select>
|
||||
<button id="reportSubmit" class="btn-primary" style="width:100%;">提交举报</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 忘记密码 -->
|
||||
<div id="forgotPasswordModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" data-modal="forgotPasswordModal">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</span>
|
||||
<h2 style="margin-bottom:16px;">🔑 重置密码</h2>
|
||||
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">输入你的邮箱和一个未使用的恢复码</p>
|
||||
<input type="email" id="resetEmail" placeholder="邮箱" />
|
||||
<input type="text" id="resetRecoveryCode" placeholder="恢复码(格式:ABCD-1234-EFGH-5678)" style="font-family:monospace;letter-spacing:0.5px;" />
|
||||
<input type="password" id="resetNewPassword" placeholder="新密码(至少6位)" />
|
||||
<button id="resetPasswordSubmit" class="btn-primary" style="width:100%;">重置密码</button>
|
||||
<div id="resetStatus" style="font-size:14px;margin-top:8px;text-align:center;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 私信列表模态框 ===== -->
|
||||
<div id="messageListModal" class="modal">
|
||||
<div class="modal-content" style="max-width:480px;max-height:80vh;padding:0;overflow:hidden;display:flex;flex-direction:column;border-radius:8px;">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid var(--border);flex-shrink:0;">
|
||||
<h2 style="font-size:18px;margin:0;">✉️ 私信</h2>
|
||||
<span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">×</span>
|
||||
</div>
|
||||
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 聊天模态框 ===== -->
|
||||
<div id="chatModal" class="modal">
|
||||
<div class="modal-content" style="max-width:480px;max-height:80vh;padding:0;overflow:hidden;display:flex;flex-direction:column;border-radius:8px;">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid var(--border);flex-shrink:0;">
|
||||
<div style="display:flex;align-items:center;gap:10px;">
|
||||
<button onclick="closeChat()" style="background:none;border:none;cursor:pointer;color:var(--text-secondary);font-size:18px;">←</button>
|
||||
<span id="chatTitle" style="font-weight:600;font-size:16px;">用户</span>
|
||||
</div>
|
||||
<span class="close" data-modal="chatModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">×</span>
|
||||
</div>
|
||||
<div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;">
|
||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;">
|
||||
<input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" />
|
||||
<button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ========================================================== -->
|
||||
<!-- ⚙️ 引用 JS -->
|
||||
<!-- ========================================================== -->
|
||||
<script src="config.js"></script>
|
||||
<script src="js/api.js"></script>
|
||||
<script src="js/theme.js"></script>
|
||||
<script src="js/captcha.js"></script>
|
||||
<script src="js/auth.js"></script>
|
||||
<script src="js/feed.js"></script>
|
||||
<script src="js/post.js"></script>
|
||||
<script src="js/admin.js"></script>
|
||||
<script src="js/user.js"></script>
|
||||
<script src="js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
-425
@@ -1,425 +0,0 @@
|
||||
// ============================================================
|
||||
// 🛡️ 管理后台
|
||||
// ============================================================
|
||||
|
||||
function renderAdminReports() {
|
||||
const container = document.getElementById('adminContent');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
|
||||
API.getReports().then(reports => {
|
||||
if (!reports || reports.length === 0) {
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">✅ 暂无举报</div>';
|
||||
return;
|
||||
}
|
||||
let html = '';
|
||||
const statusMap = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
|
||||
reports.forEach(r => {
|
||||
const postTitle = r.post_title || '无标题';
|
||||
html += `
|
||||
<div class="report-item">
|
||||
<div><strong>${r.reporter_name || '匿名'}</strong> 举报了帖子</div>
|
||||
<div style="font-size:13px;color:#64748b;margin:4px 0;">原因:${r.reason}</div>
|
||||
<div style="font-size:13px;color:#64748b;margin:4px 0;">帖子:${postTitle} — ${(r.post_content || '').substring(0, 30)}${(r.post_content || '').length > 30 ? '...' : ''}</div>
|
||||
<div style="font-size:13px;font-weight:600;">状态:${statusMap[r.status] || r.status}</div>
|
||||
${r.handler_name ? `<div style="font-size:12px;color:#94a3b8;">处理人:${r.handler_name}${r.handler_note ? ' (' + r.handler_note + ')' : ''}</div>` : ''}
|
||||
${r.status === 'pending' ? `
|
||||
<div class="report-actions">
|
||||
<button class="btn-sm btn-danger" data-reportid="${r.id}" data-action="approve">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除帖子
|
||||
</button>
|
||||
<button class="btn-sm btn-secondary" data-reportid="${r.id}" data-action="reject">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
驳回举报
|
||||
</button>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
container.innerHTML = html;
|
||||
container.querySelectorAll('[data-action]').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const id = this.dataset.reportid;
|
||||
const action = this.dataset.action;
|
||||
const status = action === 'approve' ? 'approved' : 'rejected';
|
||||
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
|
||||
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
|
||||
API.updateReport(id, status, note).then(() => {
|
||||
if (action === 'approve') {
|
||||
const report = reports.find(r => r.id === id);
|
||||
if (report && report.post_id) {
|
||||
API.deletePost(report.post_id).catch(() => {});
|
||||
}
|
||||
}
|
||||
renderAdminReports();
|
||||
}).catch(err => alert('操作失败:' + err.message));
|
||||
});
|
||||
});
|
||||
}).catch(() => {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function renderAdminUsers() {
|
||||
const container = document.getElementById('adminContent');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
|
||||
API.getUsers().then(users => {
|
||||
let html = `
|
||||
<div style="margin-bottom:12px;font-size:13px;color:#94a3b8;">
|
||||
共 <strong>${users.length}</strong> 位用户
|
||||
</div>
|
||||
<div style="overflow-x:auto;">
|
||||
<table style="width:100%;border-collapse:collapse;font-size:14px;">
|
||||
<thead>
|
||||
<tr style="text-align:left;border-bottom: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;text-align:center;">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
`;
|
||||
users.forEach(u => {
|
||||
const isAdmin = u.role === 'admin';
|
||||
const isCurrentUser = currentUser && currentUser.id === u.id;
|
||||
html += `
|
||||
<tr style="border-bottom:1px solid #f1f5f9;${isCurrentUser ? 'background:var(--primary-bg);' : ''}">
|
||||
<td style="padding:10px 12px;">
|
||||
<div style="display:flex;align-items:center;gap:8px;">
|
||||
<img src="${u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}"
|
||||
style="width:28px;height:28px;border-radius:50%;object-fit:cover;" />
|
||||
<span style="font-weight:500;">${u.username}</span>
|
||||
${isCurrentUser ? '<span style="font-size:11px;color:#94a3b8;background:#eef2ff;padding:1px 8px;border-radius:4px;">你</span>' : ''}
|
||||
</div>
|
||||
</td>
|
||||
<td style="padding:10px 12px;">
|
||||
<span style="display:inline-block;padding:2px 10px;border-radius:4px;font-size:12px;font-weight:500;${isAdmin ? 'background:#6366f1;color:#fff;' : 'background:#e2e8f0;color:#64748b;'}">
|
||||
${isAdmin ? '管理员' : '普通用户'}
|
||||
</span>
|
||||
</td>
|
||||
<td style="padding:10px 12px;color:#94a3b8;font-size:13px;">${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'}</td>
|
||||
<td style="padding:10px 12px;text-align:center;">
|
||||
${isCurrentUser ?
|
||||
'<span style="font-size:12px;color:#94a3b8;">不可操作自己</span>' :
|
||||
(isAdmin ?
|
||||
`<button class="btn-sm btn-secondary" data-userid="${u.id}" data-role="user" style="padding:4px 12px;">设为普通用户</button>` :
|
||||
`<button class="btn-sm btn-primary" data-userid="${u.id}" data-role="admin" style="padding:4px 12px;background:#6366f1;color:#fff;border:none;border-radius:4px;cursor:pointer;">设为管理员</button>`
|
||||
)
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
});
|
||||
html += '</tbody></table></div>';
|
||||
container.innerHTML = html;
|
||||
|
||||
container.querySelectorAll('[data-role]').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const userId = this.dataset.userid;
|
||||
const role = this.dataset.role;
|
||||
const roleName = role === 'admin' ? '管理员' : '普通用户';
|
||||
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
|
||||
API.updateUserRole(userId, role).then(() => {
|
||||
renderAdminUsers();
|
||||
}).catch(err => alert('操作失败:' + err.message));
|
||||
});
|
||||
});
|
||||
}).catch(() => {
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function renderAdminLogs() {
|
||||
const container = document.getElementById('adminContent');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
|
||||
API.getEventLogs().then(logs => {
|
||||
if (!logs || logs.length === 0) {
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">暂无日志</div>';
|
||||
return;
|
||||
}
|
||||
let html =
|
||||
'<table style="width:100%;border-collapse:collapse;font-size:13px;"><thead><tr style="text-align:left;border-bottom:1px solid #e2e8f0;"><th>时间</th><th>用户</th><th>操作</th></tr></thead><tbody>';
|
||||
logs.forEach(l => {
|
||||
html += `
|
||||
<tr style="border-bottom: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>
|
||||
`;
|
||||
});
|
||||
html += '</tbody></table>';
|
||||
container.innerHTML = html;
|
||||
}).catch(() => {
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function renderAdminLinks() {
|
||||
const container = document.getElementById('adminContent');
|
||||
container.innerHTML = `
|
||||
<div style="margin-bottom:16px;display:flex;gap:8px;flex-wrap:wrap;">
|
||||
<input type="text" id="newLinkTitle" placeholder="链接名称" style="flex:1;min-width:120px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
|
||||
<input type="url" id="newLinkUrl" placeholder="链接地址" style="flex:2;min-width:160px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" />
|
||||
<button id="addLinkBtn" class="btn-primary" style="padding:8px 16px;">添加</button>
|
||||
</div>
|
||||
<div id="linkList"></div>
|
||||
`;
|
||||
|
||||
function loadLinks() {
|
||||
API.getLinks().then(links => {
|
||||
const ul = document.getElementById('linkList');
|
||||
if (!links || links.length === 0) {
|
||||
ul.innerHTML = '<div style="color:#94a3b8;font-size:13px;">暂无友情链接</div>';
|
||||
return;
|
||||
}
|
||||
let html = '';
|
||||
links.forEach(l => {
|
||||
html += `
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
|
||||
<span><a href="${l.url}" target="_blank" style="color:#6366f1;text-decoration:none;">${l.title}</a></span>
|
||||
<button class="btn-sm btn-danger" data-linkid="${l.id}">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
ul.innerHTML = html;
|
||||
ul.querySelectorAll('[data-linkid]').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
if (!confirm('确定删除该链接吗?')) return;
|
||||
API.deleteLink(this.dataset.linkid).then(() => {
|
||||
loadLinks();
|
||||
}).catch(err => alert('删除失败:' + err.message));
|
||||
});
|
||||
});
|
||||
}).catch(() => {});
|
||||
}
|
||||
loadLinks();
|
||||
document.getElementById('addLinkBtn').addEventListener('click', function() {
|
||||
const title = document.getElementById('newLinkTitle').value.trim();
|
||||
const url = document.getElementById('newLinkUrl').value.trim();
|
||||
if (!title || !url) { alert('请填写完整信息'); return; }
|
||||
API.addLink(title, url).then(() => {
|
||||
document.getElementById('newLinkTitle').value = '';
|
||||
document.getElementById('newLinkUrl').value = '';
|
||||
loadLinks();
|
||||
}).catch(err => alert('添加失败:' + err.message));
|
||||
});
|
||||
}
|
||||
|
||||
function renderAdminSettings() {
|
||||
const container = document.getElementById('adminContent');
|
||||
container.innerHTML = `
|
||||
<h3 style="margin-bottom:16px;">⚙️ 论坛设置</h3>
|
||||
<div style="max-width:400px;margin:0 auto;width:100%;">
|
||||
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;">论坛名称</label>
|
||||
<input type="text" id="settingsForumName" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:15px;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" />
|
||||
<button id="settingsForumSave" class="btn-primary" style="padding:10px 24px;">保存</button>
|
||||
<span id="settingsResult" style="margin-left:12px;font-size:14px;"></span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
API.getSettings().then(data => {
|
||||
document.getElementById('settingsForumName').value = data.forum_name || 'Forumlify';
|
||||
}).catch(() => {});
|
||||
|
||||
document.getElementById('settingsForumSave').addEventListener('click', async () => {
|
||||
const name = document.getElementById('settingsForumName').value.trim();
|
||||
if (!name) { alert('请输入论坛名称'); return; }
|
||||
try {
|
||||
await API.updateSettings(name);
|
||||
document.getElementById('settingsResult').textContent = '✅ 保存成功!';
|
||||
document.getElementById('settingsResult').style.color = '#22c55e';
|
||||
document.getElementById('forumName').textContent = name;
|
||||
document.title = name;
|
||||
const titleEl = document.getElementById('pageTitle');
|
||||
if (titleEl) titleEl.textContent = name;
|
||||
} catch (err) {
|
||||
document.getElementById('settingsResult').textContent = '❌ 保存失败';
|
||||
document.getElementById('settingsResult').style.color = '#ef4444';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 📄 自定义页面管理
|
||||
// ============================================================
|
||||
|
||||
let editingPageId = null;
|
||||
|
||||
function renderAdminCustomPages() {
|
||||
const container = document.getElementById('adminContent');
|
||||
container.innerHTML = `
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
|
||||
<h3 style="margin:0;">📄 自定义页面</h3>
|
||||
<button id="addCustomPageBtn" class="btn-primary" style="padding:8px 16px;">➕ 添加页面</button>
|
||||
</div>
|
||||
<div id="customPageList"></div>
|
||||
`;
|
||||
|
||||
loadCustomPageList();
|
||||
|
||||
document.getElementById('addCustomPageBtn').addEventListener('click', function() {
|
||||
editingPageId = null;
|
||||
openCustomPageEditor();
|
||||
});
|
||||
}
|
||||
|
||||
function loadCustomPageList() {
|
||||
const container = document.getElementById('customPageList');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
|
||||
API.getAdminCustomPages().then(pages => {
|
||||
if (pages.length === 0) {
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">暂无自定义页面</div>';
|
||||
return;
|
||||
}
|
||||
let html = `<div style="overflow-x:auto;">
|
||||
<table style="width:100%;border-collapse:collapse;font-size:14px;">
|
||||
<thead>
|
||||
<tr style="text-align:left;border-bottom:2px solid var(--border);">
|
||||
<th style="padding:8px 12px;">名称</th>
|
||||
<th style="padding:8px 12px;">标题</th>
|
||||
<th style="padding:8px 12px;">URL</th>
|
||||
<th style="padding:8px 12px;">状态</th>
|
||||
<th style="padding:8px 12px;text-align:center;">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
`;
|
||||
pages.forEach(p => {
|
||||
html += `
|
||||
<tr style="border-bottom:1px solid var(--border-light);">
|
||||
<td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">${p.name}</code></td>
|
||||
<td style="padding:8px 12px;">${p.title}</td>
|
||||
<td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">?custom=${p.name}</code></td>
|
||||
<td style="padding:8px 12px;"><span style="color:${p.enabled ? '#22c55e' : '#ef4444'};">${p.enabled ? '✅ 启用' : '❌ 禁用'}</span></td>
|
||||
<td style="padding:8px 12px;text-align:center;display:flex;gap:6px;justify-content:center;">
|
||||
<button class="btn-sm btn-secondary" data-id="${p.id}" data-action="edit">✏️</button>
|
||||
<button class="btn-sm btn-danger" data-id="${p.id}" data-action="delete">🗑️</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
});
|
||||
html += '</tbody></table></div>';
|
||||
container.innerHTML = html;
|
||||
|
||||
container.querySelectorAll('[data-action="edit"]').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const page = pages.find(p => p.id === this.dataset.id);
|
||||
if (page) {
|
||||
editingPageId = page.id;
|
||||
openCustomPageEditor(page);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
container.querySelectorAll('[data-action="delete"]').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
if (!confirm('确定要删除这个页面吗?')) return;
|
||||
API.deleteCustomPage(this.dataset.id).then(() => {
|
||||
loadCustomPageList();
|
||||
loadCustomPagesNav();
|
||||
}).catch(err => alert('删除失败:' + err.message));
|
||||
});
|
||||
});
|
||||
}).catch(err => {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function openCustomPageEditor(page) {
|
||||
const isEdit = !!page;
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'modal active';
|
||||
modal.style.display = 'flex';
|
||||
modal.innerHTML = `
|
||||
<div class="modal-content" style="max-width:600px;max-height:90vh;overflow-y:auto;">
|
||||
<span class="close" style="position:absolute;top:12px;right:16px;font-size:24px;cursor:pointer;color:var(--text-light);">×</span>
|
||||
<h2 style="margin-bottom:16px;">${isEdit ? '✏️ 编辑页面' : '📄 添加页面'}</h2>
|
||||
<div style="margin-bottom:12px;">
|
||||
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面名称</label>
|
||||
<input type="text" id="editorPageName" value="${isEdit ? page.name : ''}" ${isEdit ? 'readonly style="background:var(--border-light);color:var(--text-light);"' : ''}
|
||||
placeholder="about (用于 URL: ?custom=about)" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
|
||||
${isEdit ? '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">⚠️ 名称不可修改</div>' : '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">只允许字母、数字、短横线和下划线</div>'}
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">导航栏显示名称</label>
|
||||
<input type="text" id="editorPageTitle" value="${isEdit ? page.title : ''}"
|
||||
placeholder="关于我们" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">状态</label>
|
||||
<select id="editorEnabled" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);">
|
||||
<option value="true" ${isEdit && page.enabled ? 'selected' : ''}>启用</option>
|
||||
<option value="false" ${isEdit && !page.enabled ? 'selected' : ''}>禁用</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面内容(HTML + CSS + JS)</label>
|
||||
<textarea id="editorContent" rows="12" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;font-family:monospace;background:var(--bg);color:var(--text);resize:vertical;">${isEdit ? page.content : ''}</textarea>
|
||||
<div style="font-size:12px;color:var(--text-light);margin-top:2px;">支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染</div>
|
||||
</div>
|
||||
<button id="editorSaveBtn" class="btn-primary" style="padding:10px 24px;width:100%;">保存</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(modal);
|
||||
|
||||
modal.querySelector('.close').addEventListener('click', function() {
|
||||
modal.remove();
|
||||
});
|
||||
modal.addEventListener('click', function(e) {
|
||||
if (e.target === this) modal.remove();
|
||||
});
|
||||
|
||||
modal.querySelector('#editorSaveBtn').addEventListener('click', async function() {
|
||||
const name = document.getElementById('editorPageName').value.trim();
|
||||
const title = document.getElementById('editorPageTitle').value.trim();
|
||||
const content = document.getElementById('editorContent').value.trim();
|
||||
const enabled = document.getElementById('editorEnabled').value === 'true';
|
||||
|
||||
if (!name) { alert('请输入页面名称'); return; }
|
||||
if (!title) { alert('请输入导航栏显示名称'); return; }
|
||||
if (!content) { alert('请输入页面内容'); return; }
|
||||
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
|
||||
alert('页面名称只允许字母、数字、短横线和下划线');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (isEdit) {
|
||||
await API.updateCustomPage(page.id, title, content, enabled);
|
||||
} else {
|
||||
await API.createCustomPage(name, title, content);
|
||||
}
|
||||
modal.remove();
|
||||
loadCustomPageList();
|
||||
loadCustomPagesNav();
|
||||
} catch (err) {
|
||||
alert('保存失败:' + err.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 管理后台Tab切换
|
||||
// ============================================================
|
||||
|
||||
document.querySelectorAll('.admin-tab').forEach(tab => {
|
||||
tab.addEventListener('click', function() {
|
||||
document.querySelectorAll('.admin-tab').forEach(t => t.classList.remove('active'));
|
||||
this.classList.add('active');
|
||||
const tabMap = {
|
||||
reports: renderAdminReports,
|
||||
users: renderAdminUsers,
|
||||
logs: renderAdminLogs,
|
||||
links: renderAdminLinks,
|
||||
settings: renderAdminSettings,
|
||||
custom: renderAdminCustomPages
|
||||
};
|
||||
if (tabMap[this.dataset.tab]) tabMap[this.dataset.tab]();
|
||||
});
|
||||
});
|
||||
@@ -1,380 +0,0 @@
|
||||
// ============================================================
|
||||
// API 请求封装
|
||||
// ============================================================
|
||||
let token = localStorage.getItem('forumlify-token') || null;
|
||||
|
||||
function apiFetch(path, options = {}) {
|
||||
const url = CONFIG.API_BASE_URL + path;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers || {})
|
||||
};
|
||||
if (token) {
|
||||
headers['Authorization'] = 'Bearer ' + token;
|
||||
}
|
||||
return fetch(url, {
|
||||
...options,
|
||||
headers
|
||||
}).then(res => res.json());
|
||||
}
|
||||
|
||||
const API = {
|
||||
// ============================================================
|
||||
// 认证
|
||||
// ============================================================
|
||||
async login(email, password) {
|
||||
const data = await apiFetch('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
if (data.token) {
|
||||
token = data.token;
|
||||
localStorage.setItem('forumlify-token', token);
|
||||
}
|
||||
return data;
|
||||
},
|
||||
|
||||
async register(email, password, username) {
|
||||
const data = await apiFetch('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password, username })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async logout() {
|
||||
token = null;
|
||||
localStorage.removeItem('forumlify-token');
|
||||
currentUser = null;
|
||||
},
|
||||
|
||||
async getMe() {
|
||||
const data = await apiFetch('/auth/me');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 帖子(含分页)
|
||||
// ============================================================
|
||||
async getPosts(sort, page = 1, limit = 20) {
|
||||
const data = await apiFetch('/posts?sort=' + (sort || 'latest') + '&page=' + page + '&limit=' + limit);
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async getPost(postId) {
|
||||
const data = await apiFetch('/posts/' + postId);
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async createPost(title, content, images) {
|
||||
const data = await apiFetch('/posts', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title, content, images: images || [] })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async updatePost(postId, title, content) {
|
||||
const data = await apiFetch('/posts/' + postId, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ title, content })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async deletePost(postId) {
|
||||
const data = await apiFetch('/posts/' + postId, { method: 'DELETE' });
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 回复
|
||||
// ============================================================
|
||||
async getReplies(postId) {
|
||||
const data = await apiFetch('/posts/' + postId + '/replies');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async createReply(postId, content) {
|
||||
const data = await apiFetch('/posts/' + postId + '/replies', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ content })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async deleteReply(replyId) {
|
||||
const data = await apiFetch('/replies/' + replyId, { method: 'DELETE' });
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 用户管理
|
||||
// ============================================================
|
||||
async getUsers() {
|
||||
const data = await apiFetch('/users');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async updateUserRole(userId, role) {
|
||||
const data = await apiFetch('/users/' + userId + '/role', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ role })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 举报
|
||||
// ============================================================
|
||||
async getReports() {
|
||||
const data = await apiFetch('/reports');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async createReport(postId, reason) {
|
||||
const data = await apiFetch('/reports', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ post_id: postId, reason })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async updateReport(reportId, status, note) {
|
||||
const data = await apiFetch('/reports/' + reportId, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ status, note })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 统计
|
||||
// ============================================================
|
||||
async getStats() {
|
||||
const data = await apiFetch('/stats');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 友情链接
|
||||
// ============================================================
|
||||
async getLinks() {
|
||||
const data = await apiFetch('/links');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async addLink(title, url) {
|
||||
const data = await apiFetch('/links', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title, url })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async deleteLink(id) {
|
||||
const data = await apiFetch('/links/' + id, { method: 'DELETE' });
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 事件日志
|
||||
// ============================================================
|
||||
async getEventLogs() {
|
||||
const data = await apiFetch('/event-logs');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async logEvent(action) {
|
||||
try {
|
||||
await apiFetch('/event-logs', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ action })
|
||||
});
|
||||
} catch (e) { /* 静默失败 */ }
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 论坛设置
|
||||
// ============================================================
|
||||
async getSettings() {
|
||||
const data = await apiFetch('/settings');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async updateSettings(forum_name) {
|
||||
const data = await apiFetch('/settings', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ forum_name })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 私信
|
||||
// ============================================================
|
||||
async getConversations() {
|
||||
const data = await apiFetch('/conversations');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async getOrCreateConversation(other_user_id) {
|
||||
const data = await apiFetch('/conversations', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ other_user_id })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async getMessages(conversationId) {
|
||||
const data = await apiFetch('/conversations/' + conversationId + '/messages');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async sendMessage(conversationId, content) {
|
||||
const data = await apiFetch('/conversations/' + conversationId + '/messages', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ content })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async markMessageRead(messageId) {
|
||||
const data = await apiFetch('/messages/' + messageId + '/read', {
|
||||
method: 'PUT'
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 自定义页面
|
||||
// ============================================================
|
||||
async getCustomPages() {
|
||||
const data = await apiFetch('/custom-pages');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async getCustomPage(name) {
|
||||
const data = await apiFetch('/custom-pages/' + encodeURIComponent(name));
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async getAdminCustomPages() {
|
||||
const data = await apiFetch('/admin/custom-pages');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data || [];
|
||||
},
|
||||
|
||||
async createCustomPage(name, title, content) {
|
||||
const data = await apiFetch('/admin/custom-pages', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, title, content })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async updateCustomPage(id, title, content, enabled) {
|
||||
const data = await apiFetch('/admin/custom-pages/' + id, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ title, content, enabled })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async deleteCustomPage(id) {
|
||||
const data = await apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' });
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 头像
|
||||
// ============================================================
|
||||
async updateAvatar(userId, avatar_url) {
|
||||
const data = await apiFetch('/users/' + userId + '/avatar', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ avatar_url })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 恢复码
|
||||
// ============================================================
|
||||
async generateRecoveryCodes() {
|
||||
const data = await apiFetch('/auth/recovery-codes/generate', {
|
||||
method: 'POST'
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async getRecoveryCodesCount() {
|
||||
const data = await apiFetch('/auth/recovery-codes/count');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async resetPassword(email, recoveryCode, newPassword) {
|
||||
const data = await apiFetch('/auth/reset-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, recoveryCode, newPassword })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 修改密码和邮箱
|
||||
// ============================================================
|
||||
async changePassword(oldPassword, newPassword) {
|
||||
const data = await apiFetch('/users/' + currentUser.id + '/password', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ oldPassword, newPassword })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async changeEmail(password, newEmail) {
|
||||
const data = await apiFetch('/users/' + currentUser.id + '/email', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ password, newEmail })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
}
|
||||
};
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
// ============================================================
|
||||
// AUTH 对象(供其他模块使用)
|
||||
// ============================================================
|
||||
|
||||
const AUTH = {
|
||||
async getUserProfile(userId) {
|
||||
const data = await apiFetch('/users/' + userId);
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================
|
||||
// 🔐 认证
|
||||
// ============================================================
|
||||
|
||||
// 登录事件绑定
|
||||
document.getElementById('loginBtn').addEventListener('click', () => {
|
||||
document.getElementById('loginModal').classList.add('active');
|
||||
});
|
||||
|
||||
document.getElementById('loginSubmit').addEventListener('click', async () => {
|
||||
const email = document.getElementById('loginEmail').value.trim();
|
||||
const password = document.getElementById('loginPassword').value;
|
||||
if (!email || !password) { alert('请填写完整信息'); return; }
|
||||
try {
|
||||
const result = await API.login(email, password);
|
||||
document.getElementById('loginModal').classList.remove('active');
|
||||
document.getElementById('loginEmail').value = '';
|
||||
document.getElementById('loginPassword').value = '';
|
||||
if (result.user) {
|
||||
currentUser = result.user;
|
||||
API.logEvent('login').catch(() => {});
|
||||
renderNav();
|
||||
if (currentPage === 'admin' && currentUser.role !== 'admin') {
|
||||
switchPage('feed');
|
||||
} else if (currentPage === 'feed') {
|
||||
renderFeed();
|
||||
renderStats();
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
alert('登录失败:' + err.message);
|
||||
}
|
||||
});
|
||||
|
||||
// 注册事件绑定
|
||||
document.getElementById('registerBtn').addEventListener('click', () => {
|
||||
refreshCaptcha('reg');
|
||||
document.getElementById('registerModal').classList.add('active');
|
||||
});
|
||||
|
||||
document.getElementById('registerSubmit').addEventListener('click', async () => {
|
||||
const username = document.getElementById('regUsername').value.trim();
|
||||
const email = document.getElementById('regEmail').value.trim();
|
||||
const password = document.getElementById('regPassword').value;
|
||||
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
||||
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
||||
if (!username || !email || !password) { alert('请填写完整信息'); return; }
|
||||
if (password.length < 6) { alert('密码至少6位'); return; }
|
||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
|
||||
try {
|
||||
const result = await API.register(email, password, username);
|
||||
document.getElementById('registerModal').classList.remove('active');
|
||||
document.getElementById('regUsername').value = '';
|
||||
document.getElementById('regEmail').value = '';
|
||||
document.getElementById('regPassword').value = '';
|
||||
document.getElementById('regCaptchaInput').value = '';
|
||||
alert('注册成功!请登录');
|
||||
|
||||
// 生成恢复码
|
||||
try {
|
||||
const recoveryData = await API.generateRecoveryCodes();
|
||||
if (recoveryData.codes) {
|
||||
showRecoveryCodesModal(recoveryData.codes);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('恢复码生成失败:', e);
|
||||
}
|
||||
|
||||
const loginResult = await API.login(email, password);
|
||||
if (loginResult.user) {
|
||||
const profile = await AUTH.getUserProfile(loginResult.user.id);
|
||||
currentUser = { ...loginResult.user, ...profile };
|
||||
API.logEvent('register').catch(() => {});
|
||||
renderNav();
|
||||
if (currentPage === 'admin' && currentUser.role !== 'admin') {
|
||||
switchPage('feed');
|
||||
} else if (currentPage === 'feed') {
|
||||
renderFeed();
|
||||
renderStats();
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
alert('注册失败:' + err.message);
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('regCaptchaQuestion').addEventListener('click', function() {
|
||||
refreshCaptcha('reg');
|
||||
});
|
||||
|
||||
// 退出
|
||||
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
||||
if (!confirm('确定要退出吗?')) return;
|
||||
await API.logout();
|
||||
currentUser = null;
|
||||
renderNav();
|
||||
document.querySelectorAll('.page-slide').forEach(el => el.classList.remove('active'));
|
||||
switchPage('feed');
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
// ============================================================
|
||||
// 🧠 验证码
|
||||
// ============================================================
|
||||
|
||||
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) { let t = a;
|
||||
a = b;
|
||||
b = t; }
|
||||
let answer = op === '+' ? a + b : a - b;
|
||||
return { question: a + ' ' + op + ' ' + b + ' = ?', answer: answer };
|
||||
}
|
||||
|
||||
function refreshCaptcha(type) {
|
||||
let q = generateCaptcha();
|
||||
if (type === 'reg') {
|
||||
document.getElementById('regCaptchaQuestion').textContent = q.question;
|
||||
document.getElementById('regCaptchaInput').dataset.answer = q.answer;
|
||||
} else if (type === 'post') {
|
||||
document.getElementById('postCaptchaQuestion').textContent = q.question;
|
||||
document.getElementById('postCaptchaInput').dataset.answer = q.answer;
|
||||
} else if (type === 'reply') {
|
||||
document.getElementById('replyCaptchaQuestion').textContent = q.question;
|
||||
document.getElementById('replyCaptchaInput').dataset.answer = q.answer;
|
||||
}
|
||||
}
|
||||
-219
@@ -1,219 +0,0 @@
|
||||
// ============================================================
|
||||
// 📋 帖子列表
|
||||
// ============================================================
|
||||
|
||||
let currentSort = 'latest';
|
||||
let totalPages = 1;
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
function renderFeed() {
|
||||
const container = document.getElementById('postList');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
||||
API.getPosts(currentSort, currentPageNum, PAGE_SIZE).then(result => {
|
||||
const posts = result.data || [];
|
||||
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
|
||||
totalPages = pagination.totalPages || 1;
|
||||
currentPageNum = pagination.page || 1;
|
||||
|
||||
if (posts.length === 0 && currentPageNum === 1) {
|
||||
container.innerHTML =
|
||||
'<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
if (posts.length === 0 && currentPageNum > 1) {
|
||||
currentPageNum = 1;
|
||||
renderFeed();
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
posts.forEach(p => {
|
||||
const username = p.username || '匿名用户';
|
||||
const avatar = p.avatar_url ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||
let imagesHtml = '';
|
||||
if (p.images && p.images.length > 0) {
|
||||
imagesHtml = '<div class="post-images">';
|
||||
p.images.forEach(img => {
|
||||
imagesHtml += '<img src="' + img + '" class="post-image" />';
|
||||
});
|
||||
imagesHtml += '</div>';
|
||||
}
|
||||
const replyCount = p.reply_count || 0;
|
||||
|
||||
// Markdown 渲染
|
||||
const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, '<br>');
|
||||
|
||||
html += `
|
||||
<div class="post-card" data-postid="${p.id}" style="cursor:pointer;">
|
||||
<div class="post-header">
|
||||
<img src="${avatar}" class="post-avatar" />
|
||||
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="event.stopPropagation();switchPage('user','${username}')">${username}</span>
|
||||
<span class="post-time">${time}</span>
|
||||
${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''}
|
||||
</div>
|
||||
<div class="post-title">${p.title || '无标题'}</div>
|
||||
<div class="post-content">${renderedContent}</div>
|
||||
${imagesHtml}
|
||||
<div class="post-actions">
|
||||
<span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
${replyCount}
|
||||
</span>
|
||||
<button class="action-report" data-postid="${p.id}">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
||||
举报
|
||||
</button>
|
||||
${currentUser && currentUser.id === p.user_id ? `<button class="action-delete" data-postid="${p.id}">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
container.innerHTML = html;
|
||||
|
||||
// 分页控件
|
||||
if (totalPages > 1) {
|
||||
let paginationHtml = `
|
||||
<div style="display:flex;justify-content:center;align-items:center;gap:6px;padding:16px 0;margin-top:8px;border-top:1px solid var(--border);flex-wrap:wrap;">
|
||||
<button class="page-btn" data-page="${currentPageNum - 1}" ${currentPageNum <= 1 ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
|
||||
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
|
||||
«
|
||||
</button>
|
||||
`;
|
||||
|
||||
let startPage = Math.max(1, currentPageNum - 4);
|
||||
let endPage = Math.min(totalPages, currentPageNum + 4);
|
||||
|
||||
if (currentPageNum <= 4) {
|
||||
endPage = Math.min(totalPages, 9);
|
||||
}
|
||||
if (currentPageNum > totalPages - 4) {
|
||||
startPage = Math.max(1, totalPages - 8);
|
||||
}
|
||||
|
||||
if (startPage > 1) {
|
||||
paginationHtml += `<button class="page-btn" data-page="1" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">1</button>`;
|
||||
if (startPage > 2) {
|
||||
paginationHtml += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
const isActive = i === currentPageNum;
|
||||
paginationHtml += `
|
||||
<button class="page-btn" data-page="${i}" ${isActive ? 'disabled style="background:var(--primary);color:#fff;cursor:default;border-color:var(--primary);"' : ''}
|
||||
style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:${isActive ? 'var(--primary)' : 'var(--surface)'};color:${isActive ? '#fff' : 'var(--text)'};cursor:${isActive ? 'default' : 'pointer'};font-size:13px;min-width:32px;text-align:center;">
|
||||
${i}
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
if (endPage < totalPages) {
|
||||
if (endPage < totalPages - 1) {
|
||||
paginationHtml += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
|
||||
}
|
||||
paginationHtml += `<button class="page-btn" data-page="${totalPages}" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">${totalPages}</button>`;
|
||||
}
|
||||
|
||||
paginationHtml += `
|
||||
<button class="page-btn" data-page="${currentPageNum + 1}" ${currentPageNum >= totalPages ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : ''}
|
||||
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">
|
||||
»
|
||||
</button>
|
||||
<span style="font-size:13px;color:var(--text-light);margin-left:8px;">
|
||||
${pagination.total} 帖
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
container.innerHTML += paginationHtml;
|
||||
|
||||
container.querySelectorAll('.page-btn:not([disabled])').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
const page = parseInt(this.dataset.page);
|
||||
if (page >= 1 && page <= totalPages) {
|
||||
currentPageNum = page;
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.set('postpage', page);
|
||||
window.history.pushState({}, '', url);
|
||||
renderFeed();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
container.querySelectorAll('.post-card').forEach(card => {
|
||||
card.addEventListener('click', function(e) {
|
||||
if (e.target.closest('button')) return;
|
||||
const postId = this.dataset.postid;
|
||||
switchToPost(postId);
|
||||
});
|
||||
});
|
||||
|
||||
container.querySelectorAll('.action-report').forEach(btn => {
|
||||
btn.addEventListener('click', function(e) {
|
||||
e.stopPropagation();
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
reportTargetPostId = this.dataset.postid;
|
||||
document.getElementById('reportModal').classList.add('active');
|
||||
});
|
||||
});
|
||||
container.querySelectorAll('.action-delete').forEach(btn => {
|
||||
btn.addEventListener('click', function(e) {
|
||||
e.stopPropagation();
|
||||
if (confirm('确定要删除这条帖子吗?')) {
|
||||
API.deletePost(this.dataset.postid).then(() => {
|
||||
renderFeed();
|
||||
renderStats();
|
||||
}).catch(err => alert('删除失败:' + err.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
}).catch(err => {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message +
|
||||
'</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function renderStats() {
|
||||
API.getStats().then(stats => {
|
||||
document.getElementById('statTopics').textContent = stats.topics || 0;
|
||||
document.getElementById('statPosts').textContent = stats.posts || 0;
|
||||
document.getElementById('statUsers').textContent = stats.users || 0;
|
||||
document.getElementById('statOnline').textContent = stats.online || 0;
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
function renderLinks() {
|
||||
API.getLinks().then(links => {
|
||||
const ul = document.getElementById('friendlyLinks');
|
||||
if (!links || links.length === 0) {
|
||||
ul.innerHTML = '<li style="color:#94a3b8;font-size:13px;">暂无链接</li>';
|
||||
return;
|
||||
}
|
||||
let html = '';
|
||||
links.forEach(l => {
|
||||
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>';
|
||||
});
|
||||
ul.innerHTML = html;
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
// 排序切换
|
||||
document.querySelectorAll('.tab').forEach(tab => {
|
||||
tab.addEventListener('click', function() {
|
||||
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
||||
this.classList.add('active');
|
||||
currentSort = this.dataset.sort;
|
||||
currentPageNum = 1;
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.delete('postpage');
|
||||
window.history.pushState({}, '', url);
|
||||
renderFeed();
|
||||
});
|
||||
});
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
-207
@@ -1,207 +0,0 @@
|
||||
// ============================================================
|
||||
// 📄 帖子详情 + 回复
|
||||
// ============================================================
|
||||
|
||||
let currentPostId = null;
|
||||
let reportTargetPostId = null;
|
||||
|
||||
function switchToPost(postId) {
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.set('post', postId);
|
||||
url.searchParams.delete('page');
|
||||
window.history.pushState({ page: 'post', postId: postId }, '', url);
|
||||
showPostPage(postId);
|
||||
}
|
||||
|
||||
function showPostPage(postId) {
|
||||
document.getElementById('app').style.display = 'none';
|
||||
document.querySelectorAll('.page-slide').forEach(el => {
|
||||
el.classList.remove('active', 'slide-out');
|
||||
});
|
||||
const el = document.getElementById('pagePost');
|
||||
el.classList.add('active');
|
||||
el.style.animation = 'none';
|
||||
void el.offsetHeight;
|
||||
el.style.animation = '';
|
||||
currentPage = 'post';
|
||||
renderPostDetail(postId);
|
||||
}
|
||||
|
||||
async function renderPostDetail(postId) {
|
||||
const container = document.getElementById('postDetailContent');
|
||||
const replyArea = document.getElementById('replyArea');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
||||
replyArea.style.display = 'none';
|
||||
|
||||
try {
|
||||
const post = await API.getPost(postId);
|
||||
const replies = await API.getReplies(postId);
|
||||
|
||||
document.getElementById('postDetailTitle').textContent = post.title || '帖子详情';
|
||||
|
||||
const username = post.username || '匿名用户';
|
||||
const avatar = post.avatar_url ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
|
||||
|
||||
let imagesHtml = '';
|
||||
if (post.images && post.images.length > 0) {
|
||||
imagesHtml = '<div class="post-images">';
|
||||
post.images.forEach(img => {
|
||||
imagesHtml += '<img src="' + img + '" class="post-image" />';
|
||||
});
|
||||
imagesHtml += '</div>';
|
||||
}
|
||||
|
||||
// Markdown 渲染(安全处理)
|
||||
let renderedContent = post.content || '';
|
||||
try {
|
||||
if (typeof marked !== 'undefined' && marked.parse) {
|
||||
renderedContent = marked.parse(renderedContent);
|
||||
} else {
|
||||
renderedContent = renderedContent.replace(/\n/g, '<br>');
|
||||
}
|
||||
} catch (e) {
|
||||
renderedContent = renderedContent.replace(/\n/g, '<br>');
|
||||
}
|
||||
|
||||
let html = `
|
||||
<div class="post-detail-card">
|
||||
<div class="post-header">
|
||||
<img src="${avatar}" class="post-avatar" />
|
||||
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${username}')">${username}</span>
|
||||
<span class="post-time">${time}</span>
|
||||
${post.edited_at ? `<span style="font-size:12px;color:var(--text-light);margin-left:8px;">(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})</span>` : ''}
|
||||
<div style="display:flex;gap:4px;margin-left:auto;">
|
||||
${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-secondary" id="editPostBtn" data-postid="${post.id}" style="padding:4px 10px;">✏️ 编辑</button>` : ''}
|
||||
${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-danger" id="detailDeleteBtn" data-postid="${post.id}" style="padding:4px 10px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div>
|
||||
${imagesHtml}
|
||||
</div>
|
||||
<div style="margin-top:20px;font-size:14px;color:#64748b;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
${replies.length} 条回复
|
||||
</div>
|
||||
<div style="margin-top:12px;" id="repliesList">
|
||||
`;
|
||||
|
||||
if (replies.length === 0) {
|
||||
html += '<div style="color:#94a3b8;padding:20px 0;text-align:center;">还没有回复,快来抢沙发吧 🛋️</div>';
|
||||
} else {
|
||||
replies.forEach(r => {
|
||||
const rUsername = r.username || '匿名用户';
|
||||
const rAvatar = r.avatar_url ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(rUsername) +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
|
||||
html += `
|
||||
<div class="reply-item" data-replyid="${r.id}">
|
||||
<div class="reply-header">
|
||||
<img src="${rAvatar}" class="reply-avatar" />
|
||||
<span class="reply-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${rUsername}')">${rUsername}</span>
|
||||
<span class="reply-time">${rTime}</span>
|
||||
${currentUser && currentUser.id === r.user_id ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>` : ''}
|
||||
</div>
|
||||
<div class="reply-content">${(r.content || '').replace(/\n/g, '<br>')}</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
}
|
||||
|
||||
html += '</div>';
|
||||
container.innerHTML = html;
|
||||
|
||||
replyArea.style.display = 'block';
|
||||
document.getElementById('replyContent').value = '';
|
||||
document.getElementById('replyCaptchaInput').value = '';
|
||||
refreshCaptcha('reply');
|
||||
|
||||
// 编辑按钮
|
||||
const editBtn = document.getElementById('editPostBtn');
|
||||
if (editBtn) {
|
||||
editBtn.addEventListener('click', function() {
|
||||
const postId = this.dataset.postid;
|
||||
const currentTitle = post.title || '';
|
||||
const currentContent = post.content || '';
|
||||
openEditModal(postId, currentTitle, currentContent);
|
||||
});
|
||||
}
|
||||
|
||||
const deleteBtn = document.getElementById('detailDeleteBtn');
|
||||
if (deleteBtn) {
|
||||
deleteBtn.addEventListener('click', function() {
|
||||
if (confirm('确定要删除这条帖子吗?')) {
|
||||
API.deletePost(postId).then(() => {
|
||||
alert('删除成功');
|
||||
switchPage('feed');
|
||||
renderFeed();
|
||||
renderStats();
|
||||
}).catch(err => alert('删除失败:' + err.message));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll('.reply-delete-btn').forEach(btn => {
|
||||
btn.addEventListener('click', function(e) {
|
||||
e.stopPropagation();
|
||||
const replyId = this.dataset.replyid;
|
||||
if (confirm('确定要删除这条回复吗?')) {
|
||||
API.deleteReply(replyId).then(() => {
|
||||
renderPostDetail(postId);
|
||||
}).catch(err => alert('删除失败:' + err.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const replySubmit = document.getElementById('replySubmit');
|
||||
const newReplySubmit = replySubmit.cloneNode(true);
|
||||
replySubmit.parentNode.replaceChild(newReplySubmit, replySubmit);
|
||||
newReplySubmit.addEventListener('click', async function() {
|
||||
await handleReplySubmit(postId);
|
||||
});
|
||||
|
||||
const replyInput = document.getElementById('replyContent');
|
||||
replyInput.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
handleReplySubmit(postId);
|
||||
}
|
||||
});
|
||||
|
||||
currentPostId = postId;
|
||||
|
||||
} catch (err) {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message +
|
||||
'</div>';
|
||||
replyArea.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReplySubmit(postId) {
|
||||
if (!currentUser) { alert('请先登录'); return; }
|
||||
const content = document.getElementById('replyContent').value.trim();
|
||||
const captchaInput = document.getElementById('replyCaptchaInput').value.trim();
|
||||
const captchaAnswer = parseInt(document.getElementById('replyCaptchaInput').dataset.answer);
|
||||
if (!content) { alert('请填写回复内容'); return; }
|
||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; }
|
||||
try {
|
||||
await API.createReply(postId, content);
|
||||
API.logEvent('create_reply').catch(() => {});
|
||||
renderPostDetail(postId);
|
||||
if (currentPage === 'feed') {
|
||||
renderFeed();
|
||||
}
|
||||
renderStats();
|
||||
} catch (err) {
|
||||
alert('回复失败:' + err.message);
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
// ============================================================
|
||||
// 🌓 主题切换
|
||||
// ============================================================
|
||||
|
||||
function getTheme() {
|
||||
return localStorage.getItem('forumlify-theme') || 'light';
|
||||
}
|
||||
|
||||
function setTheme(theme) {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem('forumlify-theme', theme);
|
||||
updateThemeUI(theme);
|
||||
}
|
||||
|
||||
function toggleTheme(e) {
|
||||
if (e) { e.preventDefault();
|
||||
e.stopPropagation(); }
|
||||
const current = getTheme();
|
||||
const next = current === 'light' ? 'dark' : 'light';
|
||||
setTheme(next);
|
||||
}
|
||||
|
||||
function updateThemeUI(theme) {
|
||||
const icon = document.getElementById('themeIcon');
|
||||
const label = document.getElementById('themeLabel');
|
||||
if (!icon) return;
|
||||
if (theme === 'dark') {
|
||||
icon.innerHTML =
|
||||
`<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>`;
|
||||
if (label) label.textContent = '☀️ 亮色模式';
|
||||
} else {
|
||||
icon.innerHTML = `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`;
|
||||
if (label) label.textContent = '🌙 暗色模式';
|
||||
}
|
||||
}
|
||||
|
||||
function applyTheme() {
|
||||
const theme = getTheme();
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
updateThemeUI(theme);
|
||||
}
|
||||
|
||||
// 确保 DOM 加载完成后执行
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
applyTheme();
|
||||
});
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
// ============================================================
|
||||
// 👤 用户主页
|
||||
// ============================================================
|
||||
|
||||
async function renderUserProfile(username) {
|
||||
const container = document.getElementById('userProfileContent');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
||||
|
||||
try {
|
||||
const users = await apiFetch('/users?username=' + encodeURIComponent(username));
|
||||
const user = users && users.length > 0 ? users[0] : null;
|
||||
|
||||
if (!user) {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">用户不存在</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('userPageTitle').textContent = '👤 ' + user.username;
|
||||
|
||||
const result = await apiFetch('/posts?user_id=' + user.id + '&page=1&limit=100');
|
||||
const posts = result.data || [];
|
||||
|
||||
const avatar = user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128';
|
||||
|
||||
let html = `
|
||||
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
|
||||
<img src="${avatar}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
|
||||
<h2 style="margin:16px 0 4px;font-size:24px;">${user.username}</h2>
|
||||
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p>
|
||||
<div style="display:flex;justify-content:center;gap:32px;margin-top:16px;font-size:14px;color:var(--text-secondary);flex-wrap:wrap;">
|
||||
<span>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
||||
<span>📝 发了 ${posts.length} 个帖子</span>
|
||||
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''}
|
||||
</div>
|
||||
${currentUser && currentUser.id !== user.id ? `
|
||||
<button id="dmBtn" class="btn-primary" style="margin-top:16px;padding:8px 24px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
发私信
|
||||
</button>
|
||||
` : ''}
|
||||
</div>
|
||||
<h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3>
|
||||
`;
|
||||
|
||||
if (posts.length === 0) {
|
||||
html += '<div style="color:#94a3b8;padding:20px 0;text-align:center;">还没有发帖</div>';
|
||||
} else {
|
||||
posts.forEach(p => {
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||
html += `
|
||||
<div class="post-card" style="cursor:pointer;" onclick="switchToPost('${p.id}')">
|
||||
<div class="post-title" style="font-size:16px;font-weight:600;">${p.title || '无标题'}</div>
|
||||
<div class="post-content" style="font-size:14px;color:var(--text-secondary);">${(p.content || '').substring(0, 100)}${(p.content || '').length > 100 ? '...' : ''}</div>
|
||||
<div style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
}
|
||||
|
||||
container.innerHTML = html;
|
||||
|
||||
const dmBtn = document.getElementById('dmBtn');
|
||||
if (dmBtn) {
|
||||
dmBtn.addEventListener('click', function() {
|
||||
openPrivateChat(user.id, user.username);
|
||||
});
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function showUserPage(username) {
|
||||
document.getElementById('app').style.display = 'none';
|
||||
document.querySelectorAll('.page-slide').forEach(el => {
|
||||
el.classList.remove('active', 'slide-out');
|
||||
});
|
||||
const el = document.getElementById('pageUser');
|
||||
el.classList.add('active');
|
||||
el.style.animation = 'none';
|
||||
void el.offsetHeight;
|
||||
el.style.animation = '';
|
||||
currentPage = 'user';
|
||||
renderUserProfile(username);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
// 前端 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, userId, page = 1, limit = 20) {
|
||||
let q = '/posts?sort=' + (sort || 'latest') + '&page=' + page + '&limit=' + limit;
|
||||
if (userId) q += '&user_id=' + userId;
|
||||
return apiFetch(q);
|
||||
},
|
||||
getPost(postId) { return apiFetch('/posts/' + postId); },
|
||||
createPost(title, content, images) {
|
||||
return apiFetch('/posts', { method: 'POST', body: JSON.stringify({ title, content, images: images || [] }) });
|
||||
},
|
||||
updatePost(postId, title, content) {
|
||||
return apiFetch('/posts/' + postId, { method: 'PUT', body: JSON.stringify({ title, content }) });
|
||||
},
|
||||
deletePost(postId) { return apiFetch('/posts/' + postId, { method: 'DELETE' }); },
|
||||
|
||||
// 回复
|
||||
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'); },
|
||||
getUsersByUsername(username) { return apiFetch('/users?username=' + encodeURIComponent(username)); },
|
||||
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 }) });
|
||||
},
|
||||
updateAvatar(userId, avatar_url) {
|
||||
return apiFetch('/users/' + userId + '/avatar', { method: 'PUT', body: JSON.stringify({ avatar_url }) });
|
||||
},
|
||||
updatePassword(userId, oldPassword, newPassword) {
|
||||
return apiFetch('/users/' + userId + '/password', { method: 'PUT', body: JSON.stringify({ oldPassword, newPassword }) });
|
||||
},
|
||||
updateEmail(userId, password, newEmail) {
|
||||
return apiFetch('/users/' + userId + '/email', { method: 'PUT', body: JSON.stringify({ password, newEmail }) });
|
||||
},
|
||||
|
||||
// 举报
|
||||
getReports() { return apiFetch('/reports'); },
|
||||
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(() => {});
|
||||
},
|
||||
|
||||
// 私信
|
||||
getConversations() { return apiFetch('/conversations'); },
|
||||
getOrCreateConversation(other_user_id) {
|
||||
return apiFetch('/conversations', { method: 'POST', body: JSON.stringify({ other_user_id }) });
|
||||
},
|
||||
getMessages(conversationId) { return apiFetch('/conversations/' + conversationId + '/messages'); },
|
||||
sendMessage(conversationId, content) {
|
||||
return apiFetch('/conversations/' + conversationId + '/messages', { method: 'POST', body: JSON.stringify({ content }) });
|
||||
},
|
||||
markMessageRead(messageId) {
|
||||
return apiFetch('/messages/' + messageId + '/read', { method: 'PUT' });
|
||||
},
|
||||
|
||||
// 自定义页面
|
||||
getCustomPages() { return apiFetch('/custom-pages'); },
|
||||
getCustomPage(name) { return apiFetch('/custom-pages/' + name); },
|
||||
adminGetCustomPages() { return apiFetch('/admin/custom-pages'); },
|
||||
adminCreateCustomPage(name, title, content) {
|
||||
return apiFetch('/admin/custom-pages', { method: 'POST', body: JSON.stringify({ name, title, content }) });
|
||||
},
|
||||
adminUpdateCustomPage(id, title, content, enabled) {
|
||||
return apiFetch('/admin/custom-pages/' + id, { method: 'PUT', body: JSON.stringify({ title, content, enabled }) });
|
||||
},
|
||||
adminDeleteCustomPage(id) {
|
||||
return apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' });
|
||||
},
|
||||
|
||||
// 通知
|
||||
getNotifications() { return apiFetch('/notifications'); },
|
||||
markNotificationRead(id) { return apiFetch('/notifications/' + id + '/read', { method: 'PUT' }); },
|
||||
markAllNotificationsRead() { return apiFetch('/notifications/read-all', { method: 'PUT' }); },
|
||||
|
||||
// 恢复码
|
||||
generateRecoveryCodes() { return apiFetch('/auth/recovery-codes/generate', { method: 'POST' }); },
|
||||
getRecoveryCodeCount() { return apiFetch('/auth/recovery-codes/count'); },
|
||||
resetPassword(email, recoveryCode, newPassword) {
|
||||
return apiFetch('/auth/reset-password', { method: 'POST', body: JSON.stringify({ email, recoveryCode, newPassword }) });
|
||||
},
|
||||
};
|
||||
|
||||
// 图片上传 (multipart)
|
||||
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
+14
-11
@@ -1,18 +1,21 @@
|
||||
{
|
||||
"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",
|
||||
"test": "node --test --test-concurrency=1 \"test/*.test.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": {}
|
||||
}
|
||||
+62
-4
@@ -22,7 +22,8 @@ CREATE TABLE IF NOT EXISTS posts (
|
||||
content TEXT NOT NULL,
|
||||
images TEXT[] DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
updated_at TIMESTAMPTZ DEFAULT now(),
|
||||
edited_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- 回复表
|
||||
@@ -153,11 +154,68 @@ CREATE TRIGGER update_posts_updated_at
|
||||
BEFORE UPDATE ON posts
|
||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
|
||||
|
||||
ALTER TABLE posts ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ;
|
||||
<<<<<<< HEAD
|
||||
-- ============================================================
|
||||
-- 私信系统(conversations + messages)
|
||||
-- ============================================================
|
||||
CREATE TABLE IF NOT EXISTS conversations (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
UNIQUE(user1_id, user2_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
content TEXT NOT NULL,
|
||||
is_read BOOLEAN DEFAULT false,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_conversations_user1 ON conversations(user1_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_conversations_user2 ON conversations(user2_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_conversation ON messages(conversation_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_sender ON messages(sender_id);
|
||||
|
||||
-- ============================================================
|
||||
-- 恢复码表(密码重置用)
|
||||
-- 自定义页面表
|
||||
-- ============================================================
|
||||
CREATE TABLE IF NOT EXISTS custom_pages (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name VARCHAR(50) NOT NULL UNIQUE,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
enabled BOOLEAN DEFAULT true,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_custom_pages_name ON custom_pages(name);
|
||||
|
||||
-- ============================================================
|
||||
-- 通知系统
|
||||
-- ============================================================
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
type VARCHAR(30) NOT NULL,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
link TEXT,
|
||||
is_read BOOLEAN DEFAULT false,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_read ON notifications(is_read);
|
||||
-- ============================================================
|
||||
-- 恢复码系统(密码重置)
|
||||
-- ============================================================
|
||||
ALTER TABLE posts ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ;
|
||||
CREATE TABLE IF NOT EXISTS recovery_codes (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
@@ -166,4 +224,4 @@ CREATE TABLE IF NOT EXISTS recovery_codes (
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user ON recovery_codes(user_id);
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
# 测试
|
||||
|
||||
Forumlify 使用 Node.js 内置的 `node:test` 测试框架(零额外依赖)。
|
||||
|
||||
## 前置条件
|
||||
|
||||
测试需要一个可用的 PostgreSQL 数据库和运行中的服务实例。
|
||||
|
||||
```bash
|
||||
# 1. 启动测试数据库(PostgreSQL 15)
|
||||
docker run -d --name forumlify-test \
|
||||
-e POSTGRES_USER=forumlify -e POSTGRES_PASSWORD=123456 -e POSTGRES_DB=forumlify \
|
||||
-p 5433:5432 postgres:15
|
||||
|
||||
# 2. 导入表结构
|
||||
docker exec -i forumlify-test psql -U forumlify -d forumlify < schema.sql
|
||||
|
||||
# 3. 构建并启动服务(测试端口 3100)
|
||||
DATABASE_URL='postgresql://forumlify:123456@localhost:5433/forumlify' \
|
||||
JWT_SECRET=test-secret PORT=3100 npm run build && npm start
|
||||
```
|
||||
|
||||
## 运行测试
|
||||
|
||||
```bash
|
||||
# 默认连 http://localhost:3100
|
||||
npm test
|
||||
|
||||
# 指定服务地址
|
||||
BASE_URL=http://localhost:3200 npm test
|
||||
```
|
||||
|
||||
## 覆盖范围
|
||||
|
||||
- `api.test.js` — 认证(注册/登录/me)、帖子(创建/列表/分页/删除)、回复、举报、友链、统计、私信、权限(401/403/404)
|
||||
@@ -0,0 +1,141 @@
|
||||
// Forumlify API 集成测试 — 管理后台 + 权限
|
||||
// 运行: BASE_URL=http://localhost:3100 npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { makeAdmin } from './helpers.js';
|
||||
|
||||
const BASE = process.env.BASE_URL || 'http://localhost:3100';
|
||||
const suffix = Date.now() + Math.floor(Math.random() * 100000);
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const res = await fetch(BASE + '/api' + path, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers || {}),
|
||||
},
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { status: res.status, data };
|
||||
}
|
||||
|
||||
let adminToken = null;
|
||||
let userToken = null;
|
||||
let userId = null;
|
||||
const adminUser = { email: `adm${suffix}@test.com`, password: '123456', username: `adm${suffix}` };
|
||||
const normalUser = { email: `usr${suffix}@test.com`, password: '123456', username: `usr${suffix}` };
|
||||
|
||||
test('设置: 注册管理员 + 登录', async () => {
|
||||
await api('/auth/register', { method: 'POST', body: JSON.stringify(adminUser) });
|
||||
// 保证是 admin(即使库里已有其他用户)
|
||||
await makeAdmin(adminUser.email);
|
||||
const { data } = await api('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email: adminUser.email, password: adminUser.password }),
|
||||
});
|
||||
adminToken = data.token;
|
||||
assert.ok(adminToken);
|
||||
});
|
||||
|
||||
test('设置: 注册普通用户 + 登录', async () => {
|
||||
await api('/auth/register', { method: 'POST', body: JSON.stringify(normalUser) });
|
||||
const { data } = await api('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email: normalUser.email, password: normalUser.password }),
|
||||
});
|
||||
userToken = data.token;
|
||||
userId = data.user.id;
|
||||
});
|
||||
|
||||
test('普通用户访问管理接口返回 403', async () => {
|
||||
const { status } = await api('/users', { headers: { Authorization: `Bearer ${userToken}` } });
|
||||
assert.equal(status, 403);
|
||||
});
|
||||
|
||||
test('管理员获取用户列表', async () => {
|
||||
const { status, data } = await api('/users', { headers: { Authorization: `Bearer ${adminToken}` } });
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.length >= 2);
|
||||
});
|
||||
|
||||
test('按用户名查询用户', async () => {
|
||||
const { data } = await api('/users?username=' + normalUser.username, {
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
assert.ok(data.length === 1);
|
||||
assert.equal(data[0].username, normalUser.username);
|
||||
});
|
||||
|
||||
test('管理员不能修改自己的角色', async () => {
|
||||
const me = await api('/auth/me', { headers: { Authorization: `Bearer ${adminToken}` } });
|
||||
const { status } = await api('/users/' + me.data.id + '/role', {
|
||||
method: 'PUT',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
body: JSON.stringify({ role: 'user' }),
|
||||
});
|
||||
assert.equal(status, 400);
|
||||
});
|
||||
|
||||
test('管理员修改普通用户角色', async () => {
|
||||
const { status } = await api('/users/' + userId + '/role', {
|
||||
method: 'PUT',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
body: JSON.stringify({ role: 'admin' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
});
|
||||
|
||||
test('更新论坛名称', async () => {
|
||||
const { status } = await api('/settings', {
|
||||
method: 'PUT',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
body: JSON.stringify({ forum_name: '测试论坛' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
});
|
||||
|
||||
test('获取论坛设置', async () => {
|
||||
const { status, data } = await api('/settings');
|
||||
assert.equal(status, 200);
|
||||
assert.equal(data.forum_name, '测试论坛');
|
||||
});
|
||||
|
||||
test('添加友情链接', async () => {
|
||||
const { status, data } = await api('/links', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
body: JSON.stringify({ title: 'GitHub', url: 'https://github.com' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.id);
|
||||
});
|
||||
|
||||
test('获取友情链接列表', async () => {
|
||||
const { status, data } = await api('/links');
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.length >= 1);
|
||||
});
|
||||
|
||||
test('统计接口', async () => {
|
||||
const { status, data } = await api('/stats');
|
||||
assert.equal(status, 200);
|
||||
assert.ok(typeof data.posts === 'number');
|
||||
assert.ok(typeof data.users === 'number');
|
||||
});
|
||||
|
||||
test('记录事件日志', async () => {
|
||||
const { status } = await api('/event-logs', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
body: JSON.stringify({ action: 'test_action' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
});
|
||||
|
||||
test('管理员查看事件日志', async () => {
|
||||
const { status, data } = await api('/event-logs', {
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.ok(Array.isArray(data));
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
// Forumlify API 集成测试 — 认证 + 帖子
|
||||
// 运行: BASE_URL=http://localhost:3100 npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { makeAdmin } from './helpers.js';
|
||||
|
||||
const BASE = process.env.BASE_URL || 'http://localhost:3100';
|
||||
const suffix = Date.now() + Math.floor(Math.random() * 100000); // 每次运行唯一后缀,避免冲突
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const res = await fetch(BASE + '/api' + path, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers || {}),
|
||||
},
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { status: res.status, data };
|
||||
}
|
||||
|
||||
let adminToken = null;
|
||||
let adminId = null;
|
||||
let userId = null;
|
||||
let postId = null;
|
||||
let replyId = null;
|
||||
|
||||
const adminUser = { email: `admin${suffix}@test.com`, password: '123456', username: `admin${suffix}` };
|
||||
const normalUser = { email: `user${suffix}@test.com`, password: '123456', username: `user${suffix}` };
|
||||
|
||||
test('注册第一个用户自动成为管理员', async () => {
|
||||
const { status, data } = await api('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(adminUser),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.user.id);
|
||||
// 共享库中可能已有用户,makeAdmin 确保测试管理员有 admin 权限
|
||||
await makeAdmin(adminUser.email);
|
||||
});
|
||||
|
||||
test('登录并获取 token', async () => {
|
||||
const { status, data } = await api('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email: adminUser.email, password: adminUser.password }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.token);
|
||||
adminToken = data.token;
|
||||
adminId = data.user.id;
|
||||
});
|
||||
|
||||
test('GET /api/auth/me 返回当前用户', async () => {
|
||||
const { status, data } = await api('/auth/me', { headers: { Authorization: `Bearer ${adminToken}` } });
|
||||
assert.equal(status, 200);
|
||||
assert.equal(data.username, adminUser.username);
|
||||
});
|
||||
|
||||
test('注册普通用户', async () => {
|
||||
const { status, data } = await api('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(normalUser),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.equal(data.user.role, 'user');
|
||||
userId = data.user.id;
|
||||
});
|
||||
|
||||
test('密码少于6位被拒绝', async () => {
|
||||
const { status } = await api('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email: `x${suffix}@test.com`, password: '123', username: `x${suffix}` }),
|
||||
});
|
||||
assert.equal(status, 400);
|
||||
});
|
||||
|
||||
test('未登录访问受保护接口返回 401', async () => {
|
||||
const { status } = await api('/auth/me');
|
||||
assert.equal(status, 401);
|
||||
});
|
||||
|
||||
test('发布帖子', async () => {
|
||||
const { status, data } = await api('/posts', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
body: JSON.stringify({ title: '测试帖子', content: '这是测试内容' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.id);
|
||||
postId = data.id;
|
||||
});
|
||||
|
||||
test('帖子列表返回分页结构', async () => {
|
||||
const { status, data } = await api('/posts?page=1&limit=20');
|
||||
assert.equal(status, 200);
|
||||
assert.ok(Array.isArray(data.data));
|
||||
assert.ok(data.pagination);
|
||||
assert.ok(data.pagination.totalPages >= 1);
|
||||
assert.ok(data.data.some((p) => p.id === postId));
|
||||
});
|
||||
|
||||
test('按 user_id 筛选帖子', async () => {
|
||||
const { data } = await api('/posts?user_id=' + adminId);
|
||||
assert.ok(data.data.every((p) => p.user_id === adminId));
|
||||
});
|
||||
|
||||
test('帖子详情', async () => {
|
||||
const { status, data } = await api('/posts/' + postId);
|
||||
assert.equal(status, 200);
|
||||
assert.equal(data.title, '测试帖子');
|
||||
});
|
||||
|
||||
test('不存在的帖子返回 404', async () => {
|
||||
const { status } = await api('/posts/00000000-0000-0000-0000-000000000000');
|
||||
assert.equal(status, 404);
|
||||
});
|
||||
|
||||
test('非法 UUID 返回 404 而非 500', async () => {
|
||||
const { status } = await api('/posts/not-a-uuid');
|
||||
assert.equal(status, 404);
|
||||
});
|
||||
|
||||
test('回复帖子', async () => {
|
||||
const { status, data } = await api('/posts/' + postId + '/replies', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
body: JSON.stringify({ content: '第一条回复' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.id);
|
||||
replyId = data.id;
|
||||
});
|
||||
|
||||
test('获取回复列表', async () => {
|
||||
const { status, data } = await api('/posts/' + postId + '/replies');
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.length >= 1);
|
||||
});
|
||||
|
||||
test('删除自己的回复', async () => {
|
||||
const { status } = await api('/replies/' + replyId, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
});
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// Forumlify API 集成测试 — 私信系统
|
||||
// 运行: BASE_URL=http://localhost:3100 npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { makeAdmin } from './helpers.js';
|
||||
|
||||
const BASE = process.env.BASE_URL || 'http://localhost:3100';
|
||||
const suffix = Date.now() + Math.floor(Math.random() * 100000);
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const res = await fetch(BASE + '/api' + path, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers || {}),
|
||||
},
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { status: res.status, data };
|
||||
}
|
||||
|
||||
async function register(email, username) {
|
||||
await api('/auth/register', { method: 'POST', body: JSON.stringify({ email, password: '123456', username }) });
|
||||
const { data } = await api('/auth/login', { method: 'POST', body: JSON.stringify({ email, password: '123456' }) });
|
||||
return data.token;
|
||||
}
|
||||
|
||||
let tokenA, tokenB, tokenC, idB, convId;
|
||||
|
||||
test('私信: 注册三个用户', async () => {
|
||||
tokenA = await register(`ma${suffix}@test.com`, `ma${suffix}`);
|
||||
tokenB = await register(`mb${suffix}@test.com`, `mb${suffix}`);
|
||||
tokenC = await register(`mc${suffix}@test.com`, `mc${suffix}`);
|
||||
// /api/users 是 admin 接口,保证 A 是 admin 以便查询用户 id
|
||||
await makeAdmin(`ma${suffix}@test.com`);
|
||||
assert.ok(tokenA && tokenB && tokenC);
|
||||
});
|
||||
|
||||
test('私信: 找到用户 B 的 id', async () => {
|
||||
const { data } = await api('/users', { headers: { Authorization: `Bearer ${tokenA}` } });
|
||||
idB = data.find((u) => u.username === `mb${suffix}`).id;
|
||||
assert.ok(idB);
|
||||
});
|
||||
|
||||
test('私信: 创建会话', async () => {
|
||||
const { status, data } = await api('/conversations', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokenA}` },
|
||||
body: JSON.stringify({ other_user_id: idB }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.ok(data.id);
|
||||
convId = data.id;
|
||||
});
|
||||
|
||||
test('私信: 同一对用户复用会话', async () => {
|
||||
const { data } = await api('/conversations', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokenA}` },
|
||||
body: JSON.stringify({ other_user_id: idB }),
|
||||
});
|
||||
assert.equal(data.id, convId);
|
||||
});
|
||||
|
||||
test('私信: 不能与自己私信', async () => {
|
||||
const me = await api('/auth/me', { headers: { Authorization: `Bearer ${tokenA}` } });
|
||||
const { status } = await api('/conversations', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokenA}` },
|
||||
body: JSON.stringify({ other_user_id: me.data.id }),
|
||||
});
|
||||
assert.equal(status, 400);
|
||||
});
|
||||
|
||||
test('私信: A 发送消息给 B', async () => {
|
||||
const { status, data } = await api('/conversations/' + convId + '/messages', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokenA}` },
|
||||
body: JSON.stringify({ content: '你好 B' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
assert.equal(data.content, '你好 B');
|
||||
});
|
||||
|
||||
test('私信: B 看到未读消息', async () => {
|
||||
const { data } = await api('/conversations', { headers: { Authorization: `Bearer ${tokenB}` } });
|
||||
const conv = data.find((c) => c.id === convId);
|
||||
assert.ok(conv);
|
||||
assert.equal(parseInt(conv.unread_count), 1);
|
||||
assert.equal(conv.last_message, '你好 B');
|
||||
});
|
||||
|
||||
test('私信: B 读取消息后标记已读', async () => {
|
||||
await api('/conversations/' + convId + '/messages', { headers: { Authorization: `Bearer ${tokenB}` } });
|
||||
const { data } = await api('/conversations', { headers: { Authorization: `Bearer ${tokenB}` } });
|
||||
assert.equal(parseInt(data.find((c) => c.id === convId).unread_count), 0);
|
||||
});
|
||||
|
||||
test('私信: B 回复 A', async () => {
|
||||
const { status } = await api('/conversations/' + convId + '/messages', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${tokenB}` },
|
||||
body: JSON.stringify({ content: '你好 A' }),
|
||||
});
|
||||
assert.equal(status, 200);
|
||||
});
|
||||
|
||||
test('私信: 第三方 C 无权访问会话', async () => {
|
||||
const { status } = await api('/conversations/' + convId + '/messages', {
|
||||
headers: { Authorization: `Bearer ${tokenC}` },
|
||||
});
|
||||
assert.equal(status, 403);
|
||||
});
|
||||
|
||||
test('私信: 未登录返回 401', async () => {
|
||||
const { status } = await api('/conversations');
|
||||
assert.equal(status, 401);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// 测试辅助工具
|
||||
import pg from 'pg';
|
||||
|
||||
// 从 DATABASE_URL 或默认连接串读取(与测试库保持一致)
|
||||
const pool = new pg.Pool({
|
||||
connectionString: process.env.DATABASE_URL || 'postgresql://forumlify:123456@localhost:5433/forumlify',
|
||||
});
|
||||
|
||||
// 把指定用户提升为管理员(绕过"第一个用户才 admin"的限制,保证每个测试文件可独立获得 admin)
|
||||
export async function makeAdmin(email) {
|
||||
await pool.query('UPDATE users SET role = $1 WHERE email = $2', ['admin', email]);
|
||||
await pool.end();
|
||||
}
|
||||
|
||||
// 清理测试数据(可选)
|
||||
export async function cleanup(emails) {
|
||||
for (const email of emails) {
|
||||
await pool.query('DELETE FROM users WHERE email = $1', [email]);
|
||||
}
|
||||
await pool.end();
|
||||
}
|
||||
Reference in new issue
Block a user