Compare commits
26
Commits
| Author | SHA1 | Date | ||
|---|---|---|---|---|
| ||||
|
|
a085b385b1 | |||
|
|
ec235d37bd | |||
| ||||
|
|
3808fd2e94 | |||
| ||||
|
|
5b1b16c222 | |||
|
|
593e766596 | |||
|
|
5314d60f53 | |||
|
|
8a2036035a | |||
|
|
1fce581c52 | |||
|
|
547742cb6d | |||
|
|
01250c0e3f | |||
|
|
b7db82ec0b | |||
|
|
17dc1c4f41 | |||
|
|
28bdea9572 | |||
|
|
c3e87d5a92 | |||
|
|
d2f87b13ae | |||
|
|
50d916bb28 | |||
|
|
1104b6e2e4 | |||
|
|
bce8d1fdc7 | |||
|
|
6e6e8ca8f4 | |||
|
|
52fed4212b | |||
| ||||
|
|
8ad3ca578f | |||
| ||||
|
|
feefadae11 | |||
|
|
924f9ffcc6 | |||
|
|
2e12468293 | |||
|
|
5605ded575 | |||
|
|
5aa16b0f05 | |||
No files matched your search
@@ -0,0 +1,10 @@
|
|||||||
|
.git
|
||||||
|
.github
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
node_modules
|
||||||
|
npm-debug.log*
|
||||||
|
uploads
|
||||||
|
coverage
|
||||||
|
*.md
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Copy to .env, then set both required secrets before running Docker Compose.
|
||||||
|
POSTGRES_PASSWORD=
|
||||||
|
JWT_SECRET=
|
||||||
|
PORT=3000
|
||||||
@@ -49,6 +49,7 @@ jobs:
|
|||||||
repository_name: ${{ github.event.repository.name }}
|
repository_name: ${{ github.event.repository.name }}
|
||||||
repository_id: ${{ github.repository_id }}
|
repository_id: ${{ github.repository_id }}
|
||||||
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
|
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||||
|
pull_head_repository: ${{ github.event.pull_request.head.repo.full_name || '' }}
|
||||||
comment_id: ${{ github.event.comment.id || '' }}
|
comment_id: ${{ github.event.comment.id || '' }}
|
||||||
commenter_login: ${{ github.event.comment.user.login || '' }}
|
commenter_login: ${{ github.event.comment.user.login || '' }}
|
||||||
comment_body: ${{ github.event.comment.body || '' }}
|
comment_body: ${{ github.event.comment.body || '' }}
|
||||||
|
|||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
FROM node:22.23.2-bookworm-slim
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci --omit=dev && npm cache clean --force
|
||||||
|
|
||||||
|
COPY --chown=node:node . .
|
||||||
|
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||||
|
RUN chmod +x /app/scripts/docker-entrypoint.sh
|
||||||
|
|
||||||
|
USER node
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||||
|
CMD ["node", "scripts/healthcheck.js"]
|
||||||
|
|
||||||
|
ENTRYPOINT ["/app/scripts/docker-entrypoint.sh"]
|
||||||
@@ -39,8 +39,11 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环
|
|||||||
```
|
```
|
||||||
git clone https://github.com/forumlify/public.git
|
git clone https://github.com/forumlify/public.git
|
||||||
cd forumlify
|
cd forumlify
|
||||||
printf 'JWT_SECRET=%s\n' "$(openssl rand -hex 32)" > .env
|
|
||||||
docker compose up -d
|
cp .env.example .env
|
||||||
|
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
|
||||||
|
docker compose up --build -d
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
|
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
|
||||||
@@ -48,6 +51,33 @@ docker compose up -d
|
|||||||
|
|
||||||
应用默认运行在 `http://localhost:3000`。
|
应用默认运行在 `http://localhost:3000`。
|
||||||
|
|
||||||
|
容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose ps
|
||||||
|
docker compose logs -f app
|
||||||
|
curl http://localhost:3000/health/live
|
||||||
|
curl http://localhost:3000/health/ready
|
||||||
|
```
|
||||||
|
|
||||||
|
- `/health/live` 表示 Node.js 服务正在运行。
|
||||||
|
- `/health/ready` 仅在 PostgreSQL 可用时返回成功。
|
||||||
|
- PostgreSQL 不再暴露到宿主机网络;应用通过 Compose 内部网络访问数据库。
|
||||||
|
- 应用收到 `SIGTERM`/`SIGINT` 后会停止接收新连接并关闭数据库连接池。
|
||||||
|
|
||||||
|
升级代码后执行 `docker compose up --build -d`,应用会在启动前自动应用新增迁移。
|
||||||
|
|
||||||
|
#### Docker 数据备份
|
||||||
|
|
||||||
|
数据库保存在 `db_data` 卷中,上传文件继续保存在宿主机的 `./uploads` 目录,以兼容旧版部署。升级或删除容器前请备份:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec -T db pg_dump -U forumlify forumlify > forumlify.sql
|
||||||
|
tar czf forumlify-uploads.tar.gz uploads/
|
||||||
|
```
|
||||||
|
|
||||||
|
`docker compose down` 会保留数据卷;只有明确执行 `docker compose down -v` 才会删除数据。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
|
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
|
||||||
@@ -68,8 +98,8 @@ docker compose up -d
|
|||||||
1. **克隆并安装依赖**
|
1. **克隆并安装依赖**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/public/tree/next.git
|
git clone https://github.com/forumlify/public.git
|
||||||
cd forumlify
|
cd public
|
||||||
npm install
|
npm install
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -81,19 +111,23 @@ psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
|
|||||||
psql -U forumlify -d forumlify -f schema.sql
|
psql -U forumlify -d forumlify -f schema.sql
|
||||||
```
|
```
|
||||||
|
|
||||||
3. **配置环境变量**(可选)
|
3. **配置环境变量**
|
||||||
|
|
||||||
| 变量 | 默认值 | 说明 |
|
| 变量 | 默认值 | 说明 |
|
||||||
|------|--------|------|
|
|------|--------|------|
|
||||||
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
||||||
| `PORT` | `3000` | HTTP 监听端口 |
|
| `PORT` | `3000` | HTTP 监听端口 |
|
||||||
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 |
|
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置,建议至少 32 个字符。较短的旧密钥会产生警告但仍可启动,便于安排会话失效窗口后再轮换 |
|
||||||
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
|
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
|
||||||
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
|
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
|
||||||
|
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
|
||||||
|
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册页填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
|
||||||
|
|
||||||
4. **启动**
|
|
||||||
|
4. **执行迁移并启动**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
npm run migrate
|
||||||
npm start
|
npm start
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+34
-15
@@ -1,35 +1,54 @@
|
|||||||
version: '3'
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
image: postgres:15
|
image: postgres:15.14-alpine
|
||||||
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: forumlify
|
POSTGRES_USER: forumlify
|
||||||
POSTGRES_PASSWORD: 123456
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||||
POSTGRES_DB: forumlify
|
POSTGRES_DB: forumlify
|
||||||
volumes:
|
volumes:
|
||||||
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
|
|
||||||
- db_data:/var/lib/postgresql/data
|
- db_data:/var/lib/postgresql/data
|
||||||
ports:
|
|
||||||
- "5432:5432"
|
healthcheck:
|
||||||
restart: unless-stopped
|
test: ["CMD-SHELL", "pg_isready -U forumlify -d forumlify"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
app:
|
app:
|
||||||
# 从 GHCR 拉取镜像(每次 push Lite 自动重建),不再本地构建
|
build:
|
||||||
image: ghcr.io/furrium/forumlify:lite
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
ports:
|
ports:
|
||||||
- "3000:3000"
|
- "${PORT:-3000}:3000"
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
db:
|
||||||
|
condition: service_healthy
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify
|
|
||||||
|
NODE_ENV: production
|
||||||
PORT: 3000
|
PORT: 3000
|
||||||
|
PGHOST: db
|
||||||
|
PGPORT: 5432
|
||||||
|
PGUSER: forumlify
|
||||||
|
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||||
|
PGDATABASE: forumlify
|
||||||
|
JWT_SECRET: ${JWT_SECRET:?Set JWT_SECRET in .env}
|
||||||
|
ADMIN_BOOTSTRAP_TOKEN: ${ADMIN_BOOTSTRAP_TOKEN:-}
|
||||||
ENABLE_CAPTCHA: "true"
|
ENABLE_CAPTCHA: "true"
|
||||||
JWT_SECRET: "${JWT_SECRET:?Set JWT_SECRET in .env before starting Forumlify}"
|
|
||||||
# 信任反向代理(Nginx / Docker 端口转发),修复限流警告
|
|
||||||
TRUST_PROXY: "true"
|
TRUST_PROXY: "true"
|
||||||
volumes:
|
volumes:
|
||||||
- ./uploads:/app/uploads
|
- ./uploads:/app/uploads
|
||||||
restart: unless-stopped
|
healthcheck:
|
||||||
|
test: ["CMD", "node", "scripts/healthcheck.js"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
|
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db_data:
|
db_data:
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
FROM node:18-alpine
|
|
||||||
WORKDIR /app
|
|
||||||
COPY package*.json ./
|
|
||||||
RUN npm install
|
|
||||||
COPY . .
|
|
||||||
EXPOSE 3000
|
|
||||||
CMD ["npm", "start"]
|
|
||||||
@@ -362,6 +362,7 @@
|
|||||||
<input type="text" id="regUsername" placeholder="用户名" />
|
<input type="text" id="regUsername" placeholder="用户名" />
|
||||||
<input type="email" id="regEmail" placeholder="邮箱" />
|
<input type="email" id="regEmail" placeholder="邮箱" />
|
||||||
<input type="password" id="regPassword" placeholder="密码(至少6位)" />
|
<input type="password" id="regPassword" placeholder="密码(至少6位)" />
|
||||||
|
<input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌(仅首次部署,可选)" autocomplete="off" />
|
||||||
<div class="captcha-row">
|
<div class="captcha-row">
|
||||||
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
||||||
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
||||||
|
|||||||
@@ -3,15 +3,17 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
let token = localStorage.getItem('forumlify-token') || null;
|
let token = localStorage.getItem('forumlify-token') || null;
|
||||||
|
|
||||||
|
function getAuthHeaders() {
|
||||||
|
return token ? { 'Authorization': 'Bearer ' + token } : {};
|
||||||
|
}
|
||||||
|
|
||||||
function apiFetch(path, options = {}) {
|
function apiFetch(path, options = {}) {
|
||||||
const url = CONFIG.API_BASE_URL + path;
|
const url = CONFIG.API_BASE_URL + path;
|
||||||
const headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
...(options.headers || {})
|
...(options.headers || {})
|
||||||
};
|
};
|
||||||
if (token) {
|
|
||||||
headers['Authorization'] = 'Bearer ' + token;
|
|
||||||
}
|
|
||||||
return fetch(url, {
|
return fetch(url, {
|
||||||
...options,
|
...options,
|
||||||
headers
|
headers
|
||||||
@@ -35,10 +37,10 @@ const API = {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
async register(email, password, username) {
|
async register(email, password, username, bootstrapToken = '') {
|
||||||
const data = await apiFetch('/auth/register', {
|
const data = await apiFetch('/auth/register', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ email, password, username })
|
body: JSON.stringify({ email, password, username, bootstrap_token: bootstrapToken || undefined })
|
||||||
});
|
});
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
return data;
|
return data;
|
||||||
@@ -80,6 +82,19 @@ const API = {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async uploadImage(file) {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
const response = await fetch(CONFIG.API_BASE_URL + '/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: getAuthHeaders(),
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
const data = await response.json().catch(() => ({ error: '上传响应无效' }));
|
||||||
|
if (!response.ok || data.error) throw new Error(data.error || '图片上传失败');
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
async updatePost(postId, title, content) {
|
async updatePost(postId, title, content) {
|
||||||
const data = await apiFetch('/posts/' + postId, {
|
const data = await apiFetch('/posts/' + postId, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
@@ -360,13 +375,23 @@ const API = {
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
// 修改密码和邮箱
|
// 修改密码和邮箱
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
// 这两个接口会递增 token_version 使旧令牌失效,服务端随即补发一个
|
||||||
|
// 新令牌。这里必须接住它,否则用户操作成功后会被立刻登出。
|
||||||
|
_persistRefreshedToken(data) {
|
||||||
|
if (data && data.token) {
|
||||||
|
token = data.token;
|
||||||
|
localStorage.setItem('forumlify-token', token);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
async changePassword(oldPassword, newPassword) {
|
async changePassword(oldPassword, newPassword) {
|
||||||
const data = await apiFetch('/users/' + currentUser.id + '/password', {
|
const data = await apiFetch('/users/' + currentUser.id + '/password', {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
body: JSON.stringify({ oldPassword, newPassword })
|
body: JSON.stringify({ oldPassword, newPassword })
|
||||||
});
|
});
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
return data;
|
return this._persistRefreshedToken(data);
|
||||||
},
|
},
|
||||||
|
|
||||||
async changeEmail(password, newEmail) {
|
async changeEmail(password, newEmail) {
|
||||||
@@ -375,19 +400,7 @@ const API = {
|
|||||||
body: JSON.stringify({ password, newEmail })
|
body: JSON.stringify({ password, newEmail })
|
||||||
});
|
});
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
return data;
|
return this._persistRefreshedToken(data);
|
||||||
},
|
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// 置顶
|
|
||||||
// ============================================================
|
|
||||||
|
|
||||||
async togglePinPost(postId) {
|
|
||||||
const data = await apiFetch('/posts/' + postId + '/pin', {
|
|
||||||
method: 'PUT'
|
|
||||||
});
|
|
||||||
if (data.error) throw new Error(data.error);
|
|
||||||
return data;
|
|
||||||
},
|
},
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|||||||
@@ -162,7 +162,7 @@ function switchPage(page, param) {
|
|||||||
if (page === 'new') {
|
if (page === 'new') {
|
||||||
document.getElementById('postTitle').value = '';
|
document.getElementById('postTitle').value = '';
|
||||||
document.getElementById('postContent').value = '';
|
document.getElementById('postContent').value = '';
|
||||||
document.getElementById('imagePreview').innerHTML = '';
|
clearSelectedImages();
|
||||||
document.getElementById('fileInput').value = '';
|
document.getElementById('fileInput').value = '';
|
||||||
document.getElementById('postCaptchaInput').value = '';
|
document.getElementById('postCaptchaInput').value = '';
|
||||||
refreshCaptcha('post');
|
refreshCaptcha('post');
|
||||||
@@ -368,24 +368,56 @@ async function openPrivateChat(otherUserId, otherUsername) {
|
|||||||
// 📸 图片上传(拖拽上传)
|
// 📸 图片上传(拖拽上传)
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
|
let selectedImageFiles = [];
|
||||||
|
|
||||||
|
function clearSelectedImages() {
|
||||||
|
selectedImageFiles.forEach(entry => URL.revokeObjectURL(entry.previewUrl));
|
||||||
|
selectedImageFiles = [];
|
||||||
|
const preview = document.getElementById('imagePreview');
|
||||||
|
if (preview) preview.innerHTML = '';
|
||||||
|
}
|
||||||
|
|
||||||
function handleImageFiles(files) {
|
function handleImageFiles(files) {
|
||||||
const preview = document.getElementById('imagePreview');
|
const preview = document.getElementById('imagePreview');
|
||||||
if (!preview) return;
|
if (!preview) return;
|
||||||
for (let file of files) {
|
|
||||||
if (!file.type.startsWith('image/')) continue;
|
for (const file of files) {
|
||||||
|
if (selectedImageFiles.length >= 6) {
|
||||||
|
alert('每篇帖子最多上传 6 张图片');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
|
||||||
|
alert('图片 ' + file.name + ' 格式不支持');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (file.size > 5 * 1024 * 1024) {
|
if (file.size > 5 * 1024 * 1024) {
|
||||||
alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
|
alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = function(e) {
|
const entry = { file, previewUrl: URL.createObjectURL(file) };
|
||||||
|
selectedImageFiles.push(entry);
|
||||||
|
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.style.cssText = 'position:relative;width:80px;height:80px;';
|
||||||
const img = document.createElement('img');
|
const img = document.createElement('img');
|
||||||
img.src = e.target.result;
|
img.src = entry.previewUrl;
|
||||||
|
img.alt = file.name;
|
||||||
img.style.cssText = 'width:80px;height:80px;object-fit:cover;border-radius:4px;border:1px solid var(--border);';
|
img.style.cssText = 'width:80px;height:80px;object-fit:cover;border-radius:4px;border:1px solid var(--border);';
|
||||||
preview.appendChild(img);
|
const remove = document.createElement('button');
|
||||||
};
|
remove.type = 'button';
|
||||||
reader.readAsDataURL(file);
|
remove.textContent = '×';
|
||||||
|
remove.setAttribute('aria-label', '移除 ' + file.name);
|
||||||
|
remove.style.cssText = 'position:absolute;top:2px;right:2px;width:22px;height:22px;border:0;border-radius:50%;background:rgba(0,0,0,.7);color:#fff;cursor:pointer;';
|
||||||
|
remove.addEventListener('click', () => {
|
||||||
|
selectedImageFiles = selectedImageFiles.filter(item => item !== entry);
|
||||||
|
URL.revokeObjectURL(entry.previewUrl);
|
||||||
|
wrapper.remove();
|
||||||
|
});
|
||||||
|
wrapper.append(img, remove);
|
||||||
|
preview.appendChild(wrapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
const fileInput = document.getElementById('fileInput');
|
const fileInput = document.getElementById('fileInput');
|
||||||
if (fileInput) fileInput.value = '';
|
if (fileInput) fileInput.value = '';
|
||||||
}
|
}
|
||||||
@@ -811,8 +843,10 @@ async function renderSettingsPage(tab = 'profile') {
|
|||||||
await API.changePassword(oldPassword, newPassword);
|
await API.changePassword(oldPassword, newPassword);
|
||||||
document.getElementById('changeOldPassword').value = '';
|
document.getElementById('changeOldPassword').value = '';
|
||||||
document.getElementById('changeNewPassword').value = '';
|
document.getElementById('changeNewPassword').value = '';
|
||||||
statusEl.textContent = getIcon('success') + ' 密码修改成功!';
|
statusEl.textContent = getIcon('success') + ' 密码修改成功,正在返回首页…';
|
||||||
statusEl.style.color = '#22c55e';
|
statusEl.style.color = '#22c55e';
|
||||||
|
// 服务端已补发新令牌(见 API.changePassword),本次登录保持有效。
|
||||||
|
setTimeout(() => switchPage('feed'), 800);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
||||||
statusEl.style.color = '#ef4444';
|
statusEl.style.color = '#ef4444';
|
||||||
@@ -835,9 +869,10 @@ async function renderSettingsPage(tab = 'profile') {
|
|||||||
await API.changeEmail(password, newEmail);
|
await API.changeEmail(password, newEmail);
|
||||||
document.getElementById('changeEmailPassword').value = '';
|
document.getElementById('changeEmailPassword').value = '';
|
||||||
document.getElementById('changeNewEmail').value = '';
|
document.getElementById('changeNewEmail').value = '';
|
||||||
currentUser.email = newEmail;
|
statusEl.textContent = getIcon('success') + ' 邮箱修改成功,正在返回首页…';
|
||||||
statusEl.textContent = getIcon('success') + ' 邮箱修改成功!';
|
|
||||||
statusEl.style.color = '#22c55e';
|
statusEl.style.color = '#22c55e';
|
||||||
|
// 同上:令牌由服务端补发,保持登录状态。
|
||||||
|
setTimeout(() => switchPage('feed'), 800);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
||||||
statusEl.style.color = '#ef4444';
|
statusEl.style.color = '#ef4444';
|
||||||
@@ -1236,19 +1271,27 @@ async function init() {
|
|||||||
const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer);
|
const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer);
|
||||||
if (!content) { alert('请填写内容'); return; }
|
if (!content) { alert('请填写内容'); return; }
|
||||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('post'); return; }
|
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('post'); return; }
|
||||||
const images = [];
|
const submitButton = document.getElementById('postSubmit');
|
||||||
document.querySelectorAll('#imagePreview img').forEach(img => {
|
submitButton.disabled = true;
|
||||||
images.push(img.src);
|
submitButton.textContent = selectedImageFiles.length ? '上传图片中...' : '发布中...';
|
||||||
});
|
|
||||||
try {
|
try {
|
||||||
|
const images = [];
|
||||||
|
for (const entry of selectedImageFiles) {
|
||||||
|
const uploaded = await API.uploadImage(entry.file);
|
||||||
|
images.push(uploaded.url);
|
||||||
|
}
|
||||||
await API.createPost(title, content, images);
|
await API.createPost(title, content, images);
|
||||||
|
|
||||||
alert('发布成功!');
|
alert('发布成功!');
|
||||||
|
clearSelectedImages();
|
||||||
switchPage('feed');
|
switchPage('feed');
|
||||||
renderFeed();
|
renderFeed();
|
||||||
renderStats();
|
renderStats();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('发布失败:' + err.message);
|
alert('发布失败:' + err.message);
|
||||||
|
} finally {
|
||||||
|
submitButton.disabled = false;
|
||||||
|
submitButton.textContent = '发布帖子';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -41,13 +41,14 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
|||||||
const username = document.getElementById('regUsername').value.trim();
|
const username = document.getElementById('regUsername').value.trim();
|
||||||
const email = document.getElementById('regEmail').value.trim();
|
const email = document.getElementById('regEmail').value.trim();
|
||||||
const password = document.getElementById('regPassword').value;
|
const password = document.getElementById('regPassword').value;
|
||||||
|
const bootstrapToken = document.getElementById('regBootstrapToken').value.trim();
|
||||||
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
||||||
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
||||||
if (!username || !email || !password) { alert('请填写完整信息'); return; }
|
if (!username || !email || !password) { alert('请填写完整信息'); return; }
|
||||||
if (password.length < 6) { alert('密码至少6位'); return; }
|
if (password.length < 6) { alert('密码至少6位'); return; }
|
||||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
|
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
|
||||||
try {
|
try {
|
||||||
await API.register(email, password, username);
|
await API.register(email, password, username, bootstrapToken);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('注册失败:' + err.message);
|
alert('注册失败:' + err.message);
|
||||||
return;
|
return;
|
||||||
@@ -57,6 +58,7 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
|||||||
document.getElementById('regUsername').value = '';
|
document.getElementById('regUsername').value = '';
|
||||||
document.getElementById('regEmail').value = '';
|
document.getElementById('regEmail').value = '';
|
||||||
document.getElementById('regPassword').value = '';
|
document.getElementById('regPassword').value = '';
|
||||||
|
document.getElementById('regBootstrapToken').value = '';
|
||||||
document.getElementById('regCaptchaInput').value = '';
|
document.getElementById('regCaptchaInput').value = '';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,209 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- Forumlify 数据库表结构
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- 用户表
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
email VARCHAR(255) UNIQUE NOT NULL,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
username VARCHAR(20) UNIQUE NOT NULL,
|
||||||
|
avatar_url TEXT,
|
||||||
|
bio TEXT DEFAULT '',
|
||||||
|
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 帖子表
|
||||||
|
CREATE TABLE IF NOT EXISTS posts (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
title VARCHAR(200) NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
images TEXT[] DEFAULT '{}',
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 回复表
|
||||||
|
CREATE TABLE IF NOT EXISTS replies (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 友情链接表
|
||||||
|
CREATE TABLE IF NOT EXISTS friendly_links (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
title VARCHAR(100) NOT NULL,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
sort_order INT DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 举报表
|
||||||
|
CREATE TABLE IF NOT EXISTS reports (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
|
||||||
|
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
reason VARCHAR(100) NOT NULL,
|
||||||
|
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now(),
|
||||||
|
handled_at TIMESTAMPTZ,
|
||||||
|
handler_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
handler_note TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Preserve moderation history when a reported post is deleted. This also
|
||||||
|
-- upgrades databases created with the previous ON DELETE CASCADE constraint.
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
constraint_name TEXT;
|
||||||
|
BEGIN
|
||||||
|
SELECT con.conname INTO constraint_name
|
||||||
|
FROM pg_constraint con
|
||||||
|
JOIN pg_class rel ON rel.oid = con.conrelid
|
||||||
|
JOIN pg_attribute attr ON attr.attrelid = rel.oid AND attr.attnum = ANY(con.conkey)
|
||||||
|
WHERE rel.relname = 'reports'
|
||||||
|
AND con.contype = 'f'
|
||||||
|
AND attr.attname = 'post_id'
|
||||||
|
LIMIT 1;
|
||||||
|
|
||||||
|
IF constraint_name IS NOT NULL THEN
|
||||||
|
EXECUTE format('ALTER TABLE reports DROP CONSTRAINT %I', constraint_name);
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
ALTER TABLE reports ALTER COLUMN post_id DROP NOT NULL;
|
||||||
|
ALTER TABLE reports
|
||||||
|
ADD CONSTRAINT reports_post_id_fkey
|
||||||
|
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE SET NULL;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 事件日志表
|
||||||
|
CREATE TABLE IF NOT EXISTS event_logs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
action VARCHAR(50) NOT NULL,
|
||||||
|
ip VARCHAR(45),
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 论坛设置表
|
||||||
|
-- ============================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS settings (
|
||||||
|
key VARCHAR(50) PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
updated_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 私信系统
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- 私信会话表
|
||||||
|
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_messages_conversation_id ON messages(conversation_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_sender_id ON messages(sender_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_conversations_user1_id ON conversations(user1_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_conversations_user2_id ON conversations(user2_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_id ON notifications(user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_notifications_is_read ON notifications(is_read);
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 自动更新 updated_at 的触发器
|
||||||
|
-- ============================================================
|
||||||
|
CREATE OR REPLACE FUNCTION update_updated_at()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
NEW.updated_at = now();
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS update_posts_updated_at ON posts;
|
||||||
|
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;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 恢复码表(密码重置用)
|
||||||
|
-- ============================================================
|
||||||
|
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,
|
||||||
|
code_hash VARCHAR(255) NOT NULL,
|
||||||
|
is_used BOOLEAN DEFAULT false,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id);
|
||||||
|
|
||||||
|
-- 帖子表添加置顶字段
|
||||||
|
ALTER TABLE posts ADD COLUMN IF NOT EXISTS is_pinned BOOLEAN DEFAULT false;
|
||||||
|
ALTER TABLE posts ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
|
||||||
|
|
||||||
|
-- 创建索引
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
|
||||||
|
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 论坛默认设置
|
||||||
|
-- ============================================================
|
||||||
|
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- 恢复认证与审计日志所需的缺失列
|
||||||
|
-- ============================================================
|
||||||
|
--
|
||||||
|
-- 背景:001_initial.sql 创建了 users / event_logs 表,但遗漏了
|
||||||
|
-- server.js 强依赖的若干列。schema.sql 里一直有这些列,两套定义
|
||||||
|
-- 因此产生漂移,导致 npm run migrate / Docker 部署出来的库在
|
||||||
|
-- 登录之后所有需要鉴权的接口全部返回 500:
|
||||||
|
--
|
||||||
|
-- users.token_version 认证中间件每个请求都会查询它
|
||||||
|
-- event_logs.method 审计日志写入
|
||||||
|
-- event_logs.path 审计日志写入
|
||||||
|
-- event_logs.user_agent 审计日志写入
|
||||||
|
-- event_logs.metadata 审计日志写入
|
||||||
|
--
|
||||||
|
-- 001_initial.sql 已经被记录进 schema_migrations,无法重跑,
|
||||||
|
-- 因此这里单独追加一版让已部署的库获得同样的修复。
|
||||||
|
-- 全部语句都是幂等的,对全新库同样安全。
|
||||||
|
|
||||||
|
-- token_version:用于在改密码/改邮箱后使旧 JWT 立即失效。
|
||||||
|
-- NOT NULL DEFAULT 0 会让存量用户的现有令牌保持有效(值为 0),
|
||||||
|
-- 不会强制所有人重新登录。
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS token_version INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- 事件日志的扩展字段,与 schema.sql 第 100-105 行保持一致。
|
||||||
|
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS method VARCHAR(10);
|
||||||
|
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS path TEXT;
|
||||||
|
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS user_agent TEXT;
|
||||||
|
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
|
|
||||||
|
-- 管理员事件日志按时间倒序分页,另有按用户检索的需求。
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_event_logs_created_at ON event_logs(created_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_event_logs_user_id ON event_logs(user_id);
|
||||||
|
|
||||||
|
-- 兼容混合大小写的历史邮箱,让 LOWER(email) 查询走索引。
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_email_lower ON users (LOWER(email));
|
||||||
@@ -9,8 +9,10 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server.js",
|
"start": "node server.js",
|
||||||
"dev": "node server.js",
|
"dev": "node server.js",
|
||||||
|
"migrate": "node scripts/migrate.js",
|
||||||
"check": "node scripts/check-syntax.js",
|
"check": "node scripts/check-syntax.js",
|
||||||
"test": "node --test"
|
"test": "node --test"
|
||||||
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bcryptjs": "3.0.3",
|
"bcryptjs": "3.0.3",
|
||||||
|
|||||||
+69
@@ -11,9 +11,13 @@ CREATE TABLE IF NOT EXISTS users (
|
|||||||
avatar_url TEXT,
|
avatar_url TEXT,
|
||||||
bio TEXT DEFAULT '',
|
bio TEXT DEFAULT '',
|
||||||
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
|
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
|
||||||
|
token_version INTEGER NOT NULL DEFAULT 0,
|
||||||
created_at TIMESTAMPTZ DEFAULT now()
|
created_at TIMESTAMPTZ DEFAULT now()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- Keep case-insensitive lookups index-backed for legacy mixed-case emails.
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_email_lower ON users (LOWER(email));
|
||||||
|
|
||||||
-- 帖子表
|
-- 帖子表
|
||||||
CREATE TABLE IF NOT EXISTS posts (
|
CREATE TABLE IF NOT EXISTS posts (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
@@ -123,6 +127,7 @@ CREATE TABLE IF NOT EXISTS conversations (
|
|||||||
user2_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(),
|
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||||
created_at TIMESTAMPTZ DEFAULT now(),
|
created_at TIMESTAMPTZ DEFAULT now(),
|
||||||
|
CHECK (user1_id < user2_id),
|
||||||
UNIQUE(user1_id, user2_id)
|
UNIQUE(user1_id, user2_id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -212,6 +217,70 @@ ALTER TABLE posts ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
|
|||||||
CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
|
CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
|
||||||
|
|
||||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS token_version INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- Canonicalize conversation pairs and merge any pre-existing reverse/duplicate
|
||||||
|
-- conversations before enforcing one row per unordered user pair.
|
||||||
|
ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_user1_id_user2_id_key;
|
||||||
|
ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_canonical_pair;
|
||||||
|
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
FIRST_VALUE(id) OVER (
|
||||||
|
PARTITION BY LEAST(user1_id, user2_id), GREATEST(user1_id, user2_id)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
) AS keep_id
|
||||||
|
FROM conversations
|
||||||
|
)
|
||||||
|
UPDATE messages AS m
|
||||||
|
SET conversation_id = ranked.keep_id
|
||||||
|
FROM ranked
|
||||||
|
WHERE m.conversation_id = ranked.id
|
||||||
|
AND ranked.id <> ranked.keep_id;
|
||||||
|
|
||||||
|
WITH ranked AS (
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
ROW_NUMBER() OVER (
|
||||||
|
PARTITION BY LEAST(user1_id, user2_id), GREATEST(user1_id, user2_id)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
) AS row_number
|
||||||
|
FROM conversations
|
||||||
|
)
|
||||||
|
DELETE FROM conversations AS c
|
||||||
|
USING ranked
|
||||||
|
WHERE c.id = ranked.id AND ranked.row_number > 1;
|
||||||
|
|
||||||
|
UPDATE conversations
|
||||||
|
SET user1_id = LEAST(user1_id, user2_id),
|
||||||
|
user2_id = GREATEST(user1_id, user2_id);
|
||||||
|
|
||||||
|
ALTER TABLE conversations
|
||||||
|
ADD CONSTRAINT conversations_canonical_pair CHECK (user1_id < user2_id);
|
||||||
|
ALTER TABLE conversations
|
||||||
|
ADD CONSTRAINT conversations_user1_id_user2_id_key UNIQUE (user1_id, user2_id);
|
||||||
|
|
||||||
|
-- Keep one pending report per reporter/post at the database layer. Historical
|
||||||
|
-- duplicates are rejected before creating the partial unique index.
|
||||||
|
WITH duplicates AS (
|
||||||
|
SELECT id, ROW_NUMBER() OVER (
|
||||||
|
PARTITION BY post_id, reporter_id
|
||||||
|
ORDER BY created_at, id
|
||||||
|
) AS row_number
|
||||||
|
FROM reports
|
||||||
|
WHERE status = 'pending' AND post_id IS NOT NULL
|
||||||
|
)
|
||||||
|
UPDATE reports AS r
|
||||||
|
SET status = 'rejected',
|
||||||
|
handled_at = COALESCE(r.handled_at, NOW()),
|
||||||
|
handler_note = COALESCE(r.handler_note, '重复举报已自动合并')
|
||||||
|
FROM duplicates
|
||||||
|
WHERE r.id = duplicates.id AND duplicates.row_number > 1;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_reports_unique_pending
|
||||||
|
ON reports(post_id, reporter_id)
|
||||||
|
WHERE status = 'pending' AND post_id IS NOT NULL;
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- 论坛默认设置
|
-- 论坛默认设置
|
||||||
|
|||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
node scripts/migrate.js
|
||||||
|
exec node server.js
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
const port = process.env.PORT || 3000;
|
||||||
|
const url = `http://127.0.0.1:${port}/health/ready`;
|
||||||
|
|
||||||
|
fetch(url, { signal: AbortSignal.timeout(4000) })
|
||||||
|
.then(response => {
|
||||||
|
if (!response.ok) throw new Error(`readiness returned ${response.status}`);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error(error.message);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
const fs = require('node:fs/promises');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { Pool } = require('pg');
|
||||||
|
|
||||||
|
const migrationsDir = path.join(__dirname, '..', 'migrations');
|
||||||
|
if (!process.env.DATABASE_URL && !process.env.PGHOST) {
|
||||||
|
console.error('DATABASE_URL or PGHOST is required to run migrations.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function migrate() {
|
||||||
|
const pool = new Pool();
|
||||||
|
const client = await pool.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
filename TEXT PRIMARY KEY,
|
||||||
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
const files = (await fs.readdir(migrationsDir))
|
||||||
|
.filter(file => /^\d+.*\.sql$/.test(file))
|
||||||
|
.sort();
|
||||||
|
|
||||||
|
const applied = await client.query('SELECT filename FROM schema_migrations');
|
||||||
|
const appliedFiles = new Set(applied.rows.map(row => row.filename));
|
||||||
|
|
||||||
|
for (const filename of files) {
|
||||||
|
if (appliedFiles.has(filename)) continue;
|
||||||
|
|
||||||
|
const sql = await fs.readFile(path.join(migrationsDir, filename), 'utf8');
|
||||||
|
console.log(`Applying migration ${filename}`);
|
||||||
|
await client.query('BEGIN');
|
||||||
|
try {
|
||||||
|
await client.query(sql);
|
||||||
|
await client.query(
|
||||||
|
'INSERT INTO schema_migrations (filename) VALUES ($1)',
|
||||||
|
[filename]
|
||||||
|
);
|
||||||
|
await client.query('COMMIT');
|
||||||
|
} catch (error) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Database migrations are up to date.');
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
await pool.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
migrate().catch(error => {
|
||||||
|
console.error('Database migration failed:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -2561,3 +2561,8 @@ a.btn-secondary {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
#sidebar {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
// 这些测试锁定迁移文件与 server.js 之间的契约,不需要数据库连接。
|
||||||
|
//
|
||||||
|
// 背景:migrations/ 与 schema.sql 曾各自维护 table 定义,001_initial.sql
|
||||||
|
// 漏掉了 users.token_version 和 event_logs 的审计字段,导致登录之后所有
|
||||||
|
// 需要鉴权的接口 500。当时的测试只覆盖未认证路径,因此完全没有察觉。
|
||||||
|
// 这里直接在 SQL 文本层面断言这些列存在,让同样的漂移在 CI 里立刻失败。
|
||||||
|
|
||||||
|
const migrationsDir = path.join(__dirname, '..', 'migrations');
|
||||||
|
const migrationFiles = fs.readdirSync(migrationsDir).filter(file => file.endsWith('.sql')).sort();
|
||||||
|
const migrationSQL = migrationFiles
|
||||||
|
.map(file => fs.readFileSync(path.join(migrationsDir, file), 'utf8'))
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
// server.js 直接引用、缺失即导致运行时 500 的列。
|
||||||
|
const REQUIRED_COLUMNS = [
|
||||||
|
{ table: 'users', column: 'token_version' },
|
||||||
|
{ table: 'event_logs', column: 'method' },
|
||||||
|
{ table: 'event_logs', column: 'path' },
|
||||||
|
{ table: 'event_logs', column: 'user_agent' },
|
||||||
|
{ table: 'event_logs', column: 'metadata' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function migrationDefinesColumn(table, column) {
|
||||||
|
// 命中 CREATE TABLE 内的列定义,或后续的 ALTER TABLE ... ADD COLUMN。
|
||||||
|
const createTable = new RegExp(`CREATE TABLE[^;]*?\\b${table}\\b[^;]*?;`, 'is');
|
||||||
|
const createBlock = migrationSQL.match(createTable);
|
||||||
|
if (createBlock && new RegExp(`\\b${column}\\b`, 'i').test(createBlock[0])) return true;
|
||||||
|
|
||||||
|
const alterColumn = new RegExp(
|
||||||
|
`ALTER TABLE\\s+${table}\\s+ADD COLUMN(?:\\s+IF NOT EXISTS)?\\s+${column}\\b`,
|
||||||
|
'i'
|
||||||
|
);
|
||||||
|
return alterColumn.test(migrationSQL);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('migrations define every column the server queries', () => {
|
||||||
|
for (const { table, column } of REQUIRED_COLUMNS) {
|
||||||
|
assert.ok(
|
||||||
|
migrationDefinesColumn(table, column),
|
||||||
|
`migrations/ 未定义 ${table}.${column};server.js 依赖该列,缺失会导致登录后接口 500`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('schema.sql and migrations stay in sync on required columns', () => {
|
||||||
|
const schemaSQL = fs.readFileSync(path.join(__dirname, '..', 'schema.sql'), 'utf8');
|
||||||
|
for (const { table, column } of REQUIRED_COLUMNS) {
|
||||||
|
const inSchema = new RegExp(`\\b${column}\\b`, 'i').test(schemaSQL);
|
||||||
|
assert.ok(inSchema, `schema.sql 缺少 ${table}.${column},两套定义发生漂移`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('migration files are named so the runner applies them in order', () => {
|
||||||
|
assert.ok(migrationFiles.length > 0, 'migrations/ 目录为空');
|
||||||
|
for (const file of migrationFiles) {
|
||||||
|
assert.match(file, /^\d+.*\.sql$/, `迁移文件名 ${file} 不匹配 runner 的 /^\\d+.*\\.sql$/ 过滤规则`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('migration statements are idempotent for already-deployed databases', () => {
|
||||||
|
// 001 已被记录进 schema_migrations,修复只能靠新增迁移;新增的
|
||||||
|
// ALTER TABLE 必须带 IF NOT EXISTS,否则对全新库会重复执行报错。
|
||||||
|
const alterStatements = migrationSQL.match(/ALTER TABLE\s+\w+\s+ADD COLUMN[^;]*/gi) || [];
|
||||||
|
assert.ok(alterStatements.length > 0, '未找到任何 ADD COLUMN 语句');
|
||||||
|
for (const statement of alterStatements) {
|
||||||
|
assert.match(
|
||||||
|
statement,
|
||||||
|
/ADD COLUMN IF NOT EXISTS/i,
|
||||||
|
`非幂等语句会导致重复执行失败:${statement.trim()}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in new issue
Block a user