Author SHA1 Message Date

2026-08-14

lezi-fun 3f7b9dbb9c fix: note that npm run build is next-branch only in PR template 2026-08-14 09:38:22 +08:00
lezi-fun b036a51eef feat: add bilingual PR and issue templates with branch selection 2026-08-14 09:31:55 +08:00

2026-08-13

Furrium Network 07596ea83c Update README.md 2026-08-13 23:26:49 +08:00
lezi-fun 3adbe4fab4 Configure ghbot R2 persistence 2026-08-13 22:56:40 +08:00
lezi f074ab890c Merge pull request #22 from ANONYMOUSZED-beep/fix/server-owned-audit-logs
Make audit logs server owned
2026-08-13 22:26:48 +08:00
lezi cb0377220c chore: stop running ghbot on PR close 2026-08-13 22:00:42 +08:00
lezi 0864aa2b92 chore: enable ghbot review modes and conflict recovery 2026-08-13 21:56:43 +08:00
lezi 14b63f4e1c chore: migrate ghbot workflow to goose 2026-08-13 14:28:02 +08:00
lezi c3b197d488 chore: migrate ghbot workflow to goose 2026-08-13 14:27:23 +08:00
lezi 29f7795f00 ci: configure ghbot review automation 2026-08-13 11:42:57 +08:00

2026-08-12

lezi-fun ab66d9a6fc fix: require unique Lite JWT secret 2026-08-12 22:34:05 +08:00
lezi-fun 16f39fc7c6 fix: restore Lite server bootstrap 2026-08-12 22:19:02 +08:00
Furrium Network 5721a84c54 安全问题 2026-08-12 19:45:35 +08:00
Furrium Network 1cd6b5c4dd 代理 2026-08-12 16:40:46 +08:00
lezi-fun 39f219d2ac fix: push to ghcr.io/furrium/forumlify:lite (repo's own GHCR package)
GITHUB_TOKEN from Furrium/forumlify cannot push lezi-fun/forumlify-deploy
(permission_denied). Use github.repository → ghcr.io/furrium/forumlify:lite
in workflow and compose.
2026-08-12 09:31:52 +08:00
lezi-fun aa9bcd8d12 ci: GHCR docker build for Lite branch (repo's own package) + cleanup
- .github/workflows/docker-lite.yml: build & push on Lite branch push
  → ghcr.io/furrium/forumlify:lite (linux/amd64+arm64)
- docker-compose.yml: pull :lite image from GHCR, PORT/ENABLE_CAPTCHA
  env, restart: unless-stopped
- .gitignore: ignore .open-next/.vercel/.next/.wrangler build artifacts
- Remove build artifacts accidentally committed earlier
2026-08-12 09:28:38 +08:00
lezi-fun 9f5944020b chore: ignore .wrangler local state 2026-08-12 09:21:13 +08:00
lezi-fun 9e407d0a2d ci: GHCR docker build for Lite branch + compose updates
- .github/workflows/docker-lite.yml: build & push ghcr.io/lezi-fun/
  forumlify-deploy:lite on Lite branch push (linux/amd64+arm64)
- docker-compose.yml: pull :lite image from GHCR, add PORT / ENABLE_
  CAPTCHA env, restart: unless-stopped on both services
2026-08-12 09:21:12 +08:00
lezi-fun 8f88f803f5 chore: ignore .wrangler local state 2026-08-12 09:21:10 +08:00
Furrium Network 5d71e66354 允许跳转 2026-08-12 09:19:00 +08:00
Furrium Network 320000c8b9 允许点击iframe中的超链接 2026-08-12 09:15:59 +08:00
Furrium Network 46dd281c7b 修复了吗? 2026-08-12 07:51:36 +08:00
Furrium Network 503a34f5fb 自定义页面更新 2026-08-12 07:48:20 +08:00

2026-08-11

Arun a5a880dfb2 Make audit logs server owned 2026-08-11 10:59:58 +00:00
Arun 3fc74ae189 Add integrated tests and patch dependencies 2026-08-11 10:34:46 +00:00
lezi 145f13fee5 Update README.md 2026-08-11 17:28:26 +08:00
lezi 3ed09fbcdf Update README.md 2026-08-11 17:27:39 +08:00
lezi 3ffb92dc23 Update README.md 2026-08-11 17:24:32 +08:00
Furrium Network 3fbf2743d0 3000吧还是 2026-08-11 17:17:55 +08:00
Furrium Network b4330666a4 Update README.md 2026-08-11 17:13:29 +08:00
Furrium Network 51a6b49459 Update README.md 2026-08-11 17:11:58 +08:00
Furrium Network 8d1b59479e Pass.
Fix registration and recovery-code setup
2026-08-11 16:58:51 +08:00
Furrium Network 3cee3ae530 Pass.
Prevent stored XSS in rendered content
2026-08-11 16:58:31 +08:00
Furrium Network 2e745b547d Pass.
Make moderation actions atomic and authorized
2026-08-11 16:58:13 +08:00
Furrium Network 7cf69ad476 Pass!
Harden HTTP server defaults
2026-08-11 16:57:37 +08:00
Arun c57863fc47 Make moderation actions atomic and authorized 2026-08-11 07:57:39 +00:00
lezi b449e05f3f Update README.md 2026-08-11 15:56:45 +08:00
Arun 5d0a148804 Harden HTTP server defaults 2026-08-11 07:48:33 +00:00
Arun f30a3dcacb Prevent stored XSS in rendered content 2026-08-11 07:39:37 +00:00
Arun 9e99d6909a Fix registration recovery setup flow 2026-08-11 07:23:14 +00:00
Furrium Network 2e74b1505b 修复了设置为深色模式是刷新显示浅色的问题 2026-08-11 11:32:12 +08:00
Furrium Network db34b09b2e Update i18n.js 2026-08-11 11:05:51 +08:00
Furrium Network 63b804d2a0 Update i18n.js 2026-08-11 11:02:13 +08:00
Furrium Network 1f51e66d8c Update i18n.js 2026-08-11 10:55:37 +08:00
Furrium Network 383ad94d41 Update i18n.js 2026-08-11 10:50:24 +08:00
Furrium Network b72732a774 Update i18n.js 2026-08-11 10:44:45 +08:00
Furrium Network b2539ea911 又补上了一些 2026-08-11 10:40:02 +08:00
Furrium Network dbb72b8afe 补了几个 2026-08-11 10:36:09 +08:00
Furrium Network 2746f50685 支持了翻译 2026-08-11 10:34:56 +08:00
Furrium Network 0169db134c 0!!!! 2026-08-11 10:30:01 +08:00
Furrium Network a6dcf461ec Update i18n.js 2026-08-11 10:25:26 +08:00
Furrium Network a660d605c9 Update style.css 2026-08-11 10:23:39 +08:00
Furrium Network 4e1e24699d Update i18n.js 2026-08-11 10:22:22 +08:00
Furrium Network 955c9d38d1 Update i18n.js 2026-08-11 10:21:10 +08:00
Furrium Network bc4d0d9471 延迟加载 2026-08-11 10:18:46 +08:00
Furrium Network 756ccf34a1 Update index.html 2026-08-11 10:15:22 +08:00
Furrium Network e8bc9ab302 语言包文件 2026-08-11 10:14:23 +08:00
Furrium Network 10e8db0b2d 修复了帖子内部论坛数据错误的问题 2026-08-11 10:09:22 +08:00
Furrium Network d40c8bd866 修复个人资料 2026-08-11 10:00:45 +08:00
Furrium Network 496234b519 Update user.js 2026-08-11 09:58:35 +08:00
Furrium Network bb849fc67a 添加了查看个人资料接口 2026-08-11 09:57:48 +08:00
Furrium Network c563e2ed55 Update server.js 2026-08-11 09:57:31 +08:00
Furrium Network cbb15df923 Delete js/hi 2026-08-11 09:51:55 +08:00
Furrium Network 287c8c2a12 将所有emoji修改为svg 2026-08-11 09:49:18 +08:00
Furrium Network 8c09df2978 替换了所有emoji 2026-08-11 09:46:36 +08:00
Furrium Network f4998524c6 Update icons.js 添加了一些svg 2026-08-11 09:43:36 +08:00
Furrium Network 27638e6d34 新增调用icons.js 2026-08-11 09:38:59 +08:00
Furrium Network 8d651cba38 SVG图标映射文件 2026-08-11 09:37:09 +08:00
Furrium Network 3eaa276a1f Update style.css 2026-08-11 09:34:14 +08:00
Furrium Network 27364074ea 更新了添加自定义页面模态框的样式 2026-08-11 09:29:25 +08:00
Furrium Network 2010652895 消息气泡样式 2026-08-11 09:26:43 +08:00
Furrium Network 2a01e8ca3d 管理删除气泡 2026-08-11 09:25:56 +08:00
Furrium Network 222c9b8f3c 追加消息气泡格式 2026-08-11 09:22:32 +08:00
Furrium Network 1526fce759 Update README.md 2026-08-11 08:53:41 +08:00
Furrium Network 12b3513f29 Reupload 2026-08-11 08:48:53 +08:00
Furrium Network 6eb60df5ee Create hi 2026-08-11 08:47:11 +08:00
Furrium Network 7c2b303b02 Reupload 2026-08-11 08:45:39 +08:00
Furrium Network f0e83d2484 Delete style.css 2026-08-11 08:39:07 +08:00
Furrium Network d4f25bf098 Delete server.js 2026-08-11 08:38:15 +08:00
Furrium Network 205c97ed6b Delete schema.sql 2026-08-11 08:37:18 +08:00
Furrium Network 851a445beb Delete package.json 2026-08-11 08:36:58 +08:00
Furrium Network 1503864f37 Delete package-lock.json 2026-08-11 08:36:20 +08:00
Furrium Network c0ad458b3e Delete index.html 2026-08-11 08:35:44 +08:00
Furrium Network 429f8fff64 Delete dockerfile 2026-08-11 08:35:27 +08:00
Furrium Network 4252f54a7e Delete docker-compose.yml 2026-08-11 08:33:59 +08:00
Furrium Network 291ad9c06c Delete config.js 2026-08-11 08:33:26 +08:00
Furrium Network c7f6496161 Delete README.md 2026-08-11 08:29:27 +08:00
Furrium Network 5b89506040 Delete js directory 2026-08-11 08:29:08 +08:00

2026-08-10

Furrium Network b421cb297a Update README.md 2026-08-10 23:21:23 +08:00
Furrium Network 4ced755deb Update README.md 2026-08-10 23:20:55 +08:00
Furrium Network ce932784bc Update README.md 2026-08-10 23:20:36 +08:00
Furrium Network 942c71cacb 修复了个人设置的侧边栏样式 2026-08-10 23:06:33 +08:00
Furrium Network f8916b580d 追加了对个人设置页面的侧边栏样式 2026-08-10 23:04:22 +08:00
Furrium Network cd770a082e 添加了个人主页的标签页(js) 2026-08-10 23:01:50 +08:00
Furrium Network 6f58aa4fdc Update app.js 2026-08-10 23:01:19 +08:00
Furrium Network 706286eb1c Update style.css 2026-08-10 21:32:42 +08:00
Furrium Network 6ab52bd7ac Update app.js 2026-08-10 21:30:43 +08:00
Furrium Network 4e172f193a Update index.html 2026-08-10 21:29:21 +08:00
Furrium Network d167ab3132 Update index.html 2026-08-10 21:22:09 +08:00
Furrium Network 03d46f95d7 Update index.html 2026-08-10 21:20:46 +08:00
Furrium Network 197350d7a9 Update admin.js 2026-08-10 21:18:49 +08:00
Furrium Network 155e3a465e Update index.html 2026-08-10 21:17:14 +08:00
Furrium Network 7498f07b98 Update README.md 2026-08-10 21:04:26 +08:00
Furrium Network 8e417048ee Update style.css 2026-08-10 18:58:41 +08:00
Furrium Network 427d1cb624 Update app.js 2026-08-10 18:48:26 +08:00
Furrium Network 3108dfc4cd Update app.js 2026-08-10 18:45:14 +08:00
Furrium Network 5a03c56ff4 Update index.html 2026-08-10 18:41:24 +08:00
Furrium Network 3f3e44a737 Update index.html 2026-08-10 18:39:36 +08:00
Furrium Network 963791b0bb Update app.js 2026-08-10 18:21:02 +08:00
Furrium Network c25564588d Update index.html 2026-08-10 18:18:28 +08:00
Furrium Network 737ba6c587 Update app.js 2026-08-10 18:17:28 +08:00
Furrium Network 223a003f5f Update index.html 2026-08-10 18:16:54 +08:00
Furrium Network 34a24920a8 Update index.html 2026-08-10 18:16:40 +08:00
Furrium Network 17b195c10e Update index.html 2026-08-10 18:14:32 +08:00
Furrium Network 115dd7131d Update app.js 2026-08-10 18:11:25 +08:00
Furrium Network fd15e7b427 Update style.css 2026-08-10 18:08:58 +08:00
Furrium Network 04759a0716 Update index.html 2026-08-10 18:08:43 +08:00
Furrium Network da88709d6f Update index.html 2026-08-10 18:07:42 +08:00
Furrium Network 44ba238ef6 Update index.html 2026-08-10 18:05:38 +08:00
Furrium Network e40be0ceb4 Update index.html 2026-08-10 18:00:58 +08:00
Furrium Network 23b236c9d7 Update app.js 2026-08-10 17:58:58 +08:00
Furrium Network d9b3417469 Update index.html 2026-08-10 17:58:05 +08:00
Furrium Network 4abe6d75d7 Update app.js 2026-08-10 17:52:03 +08:00
Furrium Network a6b3a587eb Update index.html 2026-08-10 17:49:11 +08:00
Furrium Network 1d960fca3e Update schema.sql 2026-08-10 17:48:42 +08:00
Furrium Network aa38a31aa3 Update style.css 2026-08-10 17:42:29 +08:00
Furrium Network d188c3eded Update index.html 2026-08-10 17:34:58 +08:00
Furrium Network b109e59fc4 Update admin.js 2026-08-10 17:30:27 +08:00
Furrium Network 77e5c8c3ba Update api.js 2026-08-10 17:29:57 +08:00
Furrium Network 5f274c2d86 Update server.js 2026-08-10 17:29:36 +08:00
Furrium Network 7a32d23976 Update style.css 2026-08-10 17:28:40 +08:00
Furrium Network 454578e8d6 Update admin.js 2026-08-10 17:22:25 +08:00
Furrium Network b0d2f94207 Update api.js 2026-08-10 17:21:46 +08:00
Furrium Network 59ef72fbc3 Update server.js 2026-08-10 17:21:04 +08:00
Furrium Network 6dccedc781 Update index.html 2026-08-10 17:02:35 +08:00
Furrium Network 84a11df8b2 液态玻璃!!!!!! 2026-08-10 16:59:41 +08:00
Furrium Network 8e86473429 液态玻璃yyds 2026-08-10 16:58:26 +08:00
Furrium Network 71afe65f63 Update style.css 2026-08-10 16:58:12 +08:00
Furrium Network e2fd713539 Update style.css 2026-08-10 12:49:47 +08:00
Furrium Network b2d85e9e1d Update index.html 2026-08-10 12:49:00 +08:00
Furrium Network 0953234bc9 Update admin.js 2026-08-10 12:44:56 +08:00
Furrium Network d87f1b2ab9 Update style.css 2026-08-10 12:43:40 +08:00
Furrium Network 58d6ee7018 Update index.html 2026-08-10 12:43:07 +08:00
Furrium Network f677eae6f5 Update admin.js 2026-08-10 11:41:00 +08:00
Furrium Network 2bec523999 Update index.html 2026-08-10 11:37:54 +08:00
Furrium Network 68d0d158c9 Update admin.js 2026-08-10 11:35:08 +08:00
Furrium Network b6a7450ef8 Update api.js 2026-08-10 11:34:40 +08:00
Furrium Network 19ec83d3a6 Update server.js 2026-08-10 11:34:11 +08:00
Furrium Network 12006d39e3 Update feed.js 2026-08-10 11:27:02 +08:00
Furrium Network 5c7f02d586 Update index.html 2026-08-10 11:26:49 +08:00
Furrium Network d31cb1523f Update server.js 2026-08-10 11:19:48 +08:00
Furrium Network 31ef7e6fd0 Update post.js 2026-08-10 11:17:05 +08:00
Furrium Network 7664d172ae Update feed.js 2026-08-10 11:16:38 +08:00
Furrium Network e693627e5b Update app.js 2026-08-10 11:15:41 +08:00
Furrium Network 146b7dd1f3 Update api.js 2026-08-10 11:14:14 +08:00
Furrium Network 5cf8fed892 Update schema.sql 2026-08-10 11:13:50 +08:00
Furrium Network 39af657905 Update app.js 2026-08-10 11:08:08 +08:00
Furrium Network 00a36b570f Update post.js 2026-08-10 11:07:27 +08:00
Furrium Network 90678440eb Update feed.js 2026-08-10 11:06:55 +08:00
Furrium Network a74181a97d Update README.md 2026-08-10 10:50:10 +08:00
Furrium Network d97645fdc8 Update README.md 2026-08-10 10:49:58 +08:00
Furrium Network 0581aa0027 Update README.md 2026-08-10 10:49:26 +08:00
Furrium Network 3aa6f0130d Update server.js 2026-08-10 10:39:27 +08:00
Furrium Network 233c919738 Update post.js 2026-08-10 10:36:48 +08:00
Furrium Network 73f8ed581f Update feed.js 2026-08-10 10:35:16 +08:00
Furrium Network bdfbdb7375 Update api.js 2026-08-10 10:34:39 +08:00
Furrium Network 283724fc14 Update schema.sql 2026-08-10 10:34:08 +08:00
30 changed files with 4970 additions and 1341 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
NEXTJS_ENV=development
+90
View File
@@ -0,0 +1,90 @@
name: 🐛 Bug 报告 / Bug Report
description: 报告一个 Bug / Report a bug
title: "[Bug] "
labels: [bug]
body:
- type: markdown
attributes:
value: |
## 感谢你报告问题!/ Thanks for reporting an issue!
请填写以下信息,帮助我们快速定位问题。/ Please fill in the following information to help us locate the issue quickly.
- type: dropdown
id: branch
attributes:
label: 你使用的是哪个分支?/ Which branch are you using?
description: 请选择你所使用的分支。/ Please select the branch you are using.
options:
- Lite(原生单文件版 / Original single-file version)
- next(Next.js 16 版 / Next.js 16 version)
validations:
required: true
- type: input
id: version
attributes:
label: 后台版本号 / Backend version (管理员填写 / admins only)
description: |
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
placeholder: "例如 / e.g. 2.0.0"
validations:
required: false
- type: textarea
id: description
attributes:
label: 问题描述 / Description
description: 请清晰描述你遇到的问题。/ Please clearly describe the issue you encountered.
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤 / Steps to reproduce
description: 如何复现这个问题?/ How can this issue be reproduced?
placeholder: |
1. 打开... / Open ...
2. 点击... / Click ...
3. 看到错误... / See the error...
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望行为 / Expected behavior
description: 你期望发生什么?/ What did you expect to happen?
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际行为 / Actual behavior
description: 实际发生了什么?/ What actually happened?
validations:
required: true
- type: textarea
id: environment
attributes:
label: 环境信息 / Environment
description: 你的运行环境。/ Your running environment.
placeholder: |
- 操作系统 / OS:
- 浏览器 / Browser:
- Node.js 版本 / Node.js version:
- 部署方式 / Deployment method (Docker / 源码 / Source):
validations:
required: false
- type: textarea
id: logs
attributes:
label: 日志 / Logs
description: 如有报错日志,请粘贴于此。/ Paste any error logs here if available.
render: shell
validations:
required: false
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
@@ -0,0 +1,65 @@
name: ✨ 功能建议 / Feature Request
description: 提出一个新功能或改进建议 / Suggest an idea for this project
title: "[Feature] "
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
## 感谢你的建议!/ Thanks for your suggestion!
请填写以下信息,让我们了解你的想法。/ Please fill in the information below to help us understand your idea.
- type: dropdown
id: branch
attributes:
label: 这个功能针对哪个分支?/ Which branch is this feature for?
description: 请选择你所使用的分支。/ Please select the branch you are using.
options:
- Lite(原生单文件版 / Original single-file version)
- next(Next.js 16 版 / Next.js 16 version)
validations:
required: true
- type: input
id: version
attributes:
label: 后台版本号 / Backend version (管理员填写 / admins only)
description: |
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
placeholder: "例如 / e.g. 2.0.0"
validations:
required: false
- type: textarea
id: problem
attributes:
label: 要解决的问题 / Problem to solve
description: 这个功能解决什么问题?/ What problem does this feature solve?
placeholder: "当我...时,我希望... / When I ..., I wish ..."
validations:
required: true
- type: textarea
id: solution
attributes:
label: 期望的解决方案 / Proposed solution
description: 你希望如何实现?/ How would you like it to work?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 替代方案 / Alternatives considered
description: 你考虑过其他方案吗?/ Have you considered any alternative approaches?
validations:
required: false
- type: textarea
id: additional
attributes:
label: 补充说明 / Additional context
description: 其他任何信息、截图或示例。/ Any other information, screenshots, or examples.
validations:
required: false
+52
View File
@@ -0,0 +1,52 @@
# 感谢你为 Forumlify 提交贡献!/ Thank you for contributing to Forumlify!
<!-- 请填写以下信息,帮助我们快速处理你的 PR。/ Please fill in the information below to help us process your PR quickly. -->
## 目标分支 / Target branch
**你提交的代码是基于哪个分支?/ Which branch is your code based on?**
- [ ] **Lite**(原生单文件版 / Original single-file version)
- [ ] **next**(Next.js 16 版 / Next.js 16 version)
> ⚠️ 请确保 PR 的 base 分支与你的代码来源分支一致。/ Please make sure the PR's base branch matches the branch your code comes from.
## 版本信息 / Version info
<!-- 仅当你选择 next 分支且为管理员时填写。/ Only fill in if you chose the next branch AND you are an administrator. -->
**后台版本号 / Backend version (admin only):**
```
(在此粘贴后台显示的版本号 / Paste the version shown in the admin panel here)
```
## 变更内容 / What does this PR do?
<!-- 简要描述你的改动。/ Briefly describe your changes. -->
-
## 动机 / Motivation
<!-- 为什么需要这个改动?/ Why is this change needed? -->
-
## 测试 / Testing
<!-- 你如何验证这些改动?/ How did you verify these changes? -->
- [ ] 本地构建通过 / Local build passes (`npm run build`,仅 next 分支 / next branch only)
- [ ] 相关功能已手动测试 / Related features manually tested
- [ ] 测试用例已更新 / Tests updated
## 截图 / Screenshots
<!-- 如有 UI 改动,请附截图。/ Attach screenshots if this changes the UI. -->
## 检查清单 / Checklist
- [ ] 我已阅读并遵循了贡献指南 / I have read and followed the contributing guidelines
- [ ] 我的代码遵循现有代码风格 / My code follows the existing code style
- [ ] 我已同步最新的上游分支 / I have synced with the latest upstream branch
- [ ] 本 PR 只包含必要的改动 / This PR contains only the necessary changes
+55
View File
@@ -0,0 +1,55 @@
name: Build & Push Docker to GHCR (Lite)
on:
push:
branches: [Lite]
tags: ['v*']
workflow_dispatch:
env:
REGISTRY: ghcr.io
# 推仓库自己的 GHCR 包(github.repository = Furrium/forumlify)——
# 仓库 GITHUB_TOKEN 无权推跨仓库包(如 lezi-fun/forumlify-deploy)
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
# Lite 分支 → lite 标签(与 next 镜像隔离,避免覆盖)
type=raw,value=lite,enable=${{ github.ref == 'refs/heads/Lite' }}
type=semver,pattern={{version}}
type=sha,prefix=git-
- name: Build and push (linux/amd64 + linux/arm64)
uses: docker/build-push-action@v6
with:
context: .
push: true
platforms: linux/amd64, linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
+82
View File
@@ -0,0 +1,82 @@
name: ghbot
on:
pull_request_target:
types:
- opened
- synchronize
- reopened
- ready_for_review
- edited
issues:
types:
- opened
- edited
- reopened
issue_comment:
types:
- created
pull_request_review:
types:
- submitted
permissions:
contents: write
pull-requests: write
checks: write
statuses: read
issues: write
jobs:
review:
if: |
github.event_name == 'pull_request_target' ||
github.event_name == 'issues' ||
(github.event_name == 'issue_comment' && github.event.issue.pull_request != null) ||
github.event_name == 'pull_request_review'
uses: lezi-fun/ghbot/.github/workflows/review-reusable.yml@main
secrets:
GOOSE_API_KEY: ${{ secrets.GOOSE_API_KEY || secrets.OPENCODE_API_KEY }}
GH_APP_ID: ${{ secrets.GH_APP_ID }}
GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
GH_APP_INSTALLATION_ID: ${{ secrets.GH_APP_INSTALLATION_ID }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
with:
event_name: ${{ github.event_name }}
event_action: ${{ github.event.action }}
repository_owner: ${{ github.repository_owner }}
repository_name: ${{ github.event.repository.name }}
repository_id: ${{ github.repository_id }}
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
comment_id: ${{ github.event.comment.id || '' }}
commenter_login: ${{ github.event.comment.user.login || '' }}
comment_body: ${{ github.event.comment.body || '' }}
reviewer_login: ${{ github.event.review.user.login || '' }}
review_state: ${{ github.event.review.state || '' }}
review_commit_id: ${{ github.event.review.commit_id || '' }}
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
review_policy: ${{ vars.REVIEW_POLICY || 'allow' }}
review_strictness: ${{ vars.REVIEW_STRICTNESS || 'normal' }}
review_instructions: ${{ vars.REVIEW_INSTRUCTIONS || '' }}
review_branches: ${{ vars.REVIEW_BRANCHES || '' }}
repository_knowledge_enabled: ${{ vars.REPOSITORY_KNOWLEDGE_ENABLED || 'true' }}
repository_knowledge_write: ${{ vars.REPOSITORY_KNOWLEDGE_WRITE || 'false' }}
r2_endpoint: ${{ vars.R2_ENDPOINT || '' }}
r2_bucket_name: ${{ vars.R2_BUCKET_NAME || '' }}
r2_prefix: ${{ vars.R2_PREFIX || '' }}
triage_enabled: ${{ vars.TRIAGE_ENABLED || 'true' }}
triage_labels: ${{ vars.TRIAGE_LABELS || 'bug,enhancement,documentation,question' }}
triage_duplicate_label: ${{ vars.TRIAGE_DUPLICATE_LABEL || 'duplicate' }}
triage_candidate_limit: ${{ vars.TRIAGE_CANDIDATE_LIMIT || '50' }}
triage_instructions: ${{ vars.TRIAGE_INSTRUCTIONS || '' }}
auto_merge: ${{ vars.AUTO_MERGE || 'false' }}
auto_resolve_conflicts: ${{ vars.AUTO_RESOLVE_CONFLICTS || 'false' }}
conflict_test_command: ${{ vars.CONFLICT_TEST_COMMAND || '' }}
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
+10
View File
@@ -3,3 +3,13 @@ uploads/
*.log *.log
.DS_Store .DS_Store
.env .env
# Wrangler 本地状态
.wrangler/
# 构建产物
.open-next/
.vercel/
.next/
.wrangler/
+70 -23
View File
@@ -1,4 +1,6 @@
# Forumlify 🌊
# Forumlify LITE Edition 🌊
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。 > 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
@@ -11,20 +13,44 @@
- 🐳 Docker 一键部署 - 🐳 Docker 一键部署
- 🌓 暗色/亮色模式切换 - 🌓 暗色/亮色模式切换
## 🤔 如何选择版本
Forumlify 提供了两个不同架构的分支版本,以满足不同部署环境与开发需求的场景:
* **Lite 版 (`lite` 分支)**:轻量单体架构,零构建步骤,资源占用极低,主要由Furrium维护。
* **Next.js 版 (`next` 分支)**:现代全栈架构,组件化开发,支持云原生与 Serverless / 边缘部署,主要由lezi-fun维护。
你可以根据以下维度选择最适合你当前需求的版本:
| 对比维度 | Forumlify (Lite 版 / `lite`) | Forumlify-Next (Next.js 版 / `next`) | 选择建议 |
| :--- | :--- | :--- | :--- |
| **上手速度与部署** | **极快**(零编译步骤,直接 `node server.js` 或 Docker 启动) | **中等**(需要经过 `next build` 编译打包,或配置 OpenNext) | 希望 1 分钟快速跑起来选 `lite` |
| **VPS 最低配置要求** | **1 核 512MB RAM**(资源占用极低,适合低配小鸡) | **1 核 1GB RAM+**(主要在打包构建时需要较多内存) | 内存有限或低配 VPS 推荐 `lite` |
| **存储扩展性** | 本地磁盘存储(`uploads/` 目录) | 支持 **Cloudflare R2 / S3 兼容对象存储** + 本地回退 | 需要接云存储或海量图片存储选 `next` |
| **部署环境支持** | 传统 VPS / Docker 容器 | VPS / Docker / **Cloudflare Workers / Vercel** | 需要 Serverless / 边缘部署选 `next` |
| **技术栈与二次开发** | 原生 Vanilla JS + Express,无框架门槛 | React 19 + Next.js 16 + Tailwind,组件化程度高 | 熟悉 React 框架或需要团队协同选 `next` |
| **测试与工程化** | 基础配置,轻量化结构 | 内置自动化测试套件(Unit / Integration Tests) | 追求工程化与自动化测试选 `next` |
| **适合场景** | 个人轻量论坛、小圈子交流、低成本运行、快速原型验证 | 中大型社区、云原生部署、需要扩展对象存储或边缘加速 | 根据站点规模与长期规划选择 |
## 🚀 快速开始 ## 🚀 快速开始
### Docker 部署(推荐) ### Docker 部署(推荐)
```bash ```
git clone https://github.com/furrium/forumlify.git git clone https://github.com/forumlify/public.git
cd forumlify cd forumlify
docker-compose up -d printf 'JWT_SECRET=%s\n' "$(openssl rand -hex 32)" > .env
docker compose up -d
``` ```
应用默认运行在 `http://localhost:3003`。 旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
`JWT_SECRET` 会使现有登录令牌失效。
应用默认运行在 `http://localhost:3000`。
--- ---
以下内容添加自NodeLoc @Lezi-fun的PR
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
--- ---
@@ -34,42 +60,36 @@ docker-compose up -d
#### 环境要求 #### 环境要求
- Node.js 18+ - Node.js 20+
- PostgreSQL 13+(`schema.sql` 使用了内置的 `gen_random_uuid()`) - PostgreSQL 13+
#### 步骤 #### 步骤
1. **克隆并安装依赖** 1. **克隆并安装依赖**
```bash ```bash
git clone https://github.com/furrium/forumlify.git git clone https://github.com/public/tree/next.git
cd forumlify cd forumlify
npm install npm install
``` ```
2. **准备数据库**(以本机 PostgreSQL 为例) 2. **准备数据库**
```bash ```bash
# 创建数据库和用户(与 docker-compose.yml 默认一致)
psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '123456';" psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '123456';"
psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;" 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:123456@localhost:5432/forumlify` | PostgreSQL 连接串 | | `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
| `PORT` | `3000` | HTTP 监听端口 | | `PORT` | `3000` | HTTP 监听端口 |
| `JWT_SECRET` | `forumlify-secret-key-change-me-in-production` | JWT 签名密钥,**生产环境务必修改** | | `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 |
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
```bash | `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
# 例如:
export DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
export JWT_SECRET=your-own-secret-key
```
4. **启动** 4. **启动**
@@ -87,12 +107,39 @@ npm start
|--------|--------|------| |--------|--------|------|
| `FORUM_NAME` | `Forumlify` | 论坛名称(左上角显示) | | `FORUM_NAME` | `Forumlify` | 论坛名称(左上角显示) |
| `ENABLE_CAPTCHA` | `true` | 发帖/注册的人机验证(10 以内加减法) | | `ENABLE_CAPTCHA` | `true` | 发帖/注册的人机验证(10 以内加减法) |
| `SERVER_PORT` | `null` | 可选:服务端监听端口(仅服务端读取,浏览器端忽略)。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000`。设为 `null` 时使用环境变量或默认值 | | `SERVER_PORT` | `null` | 可选:服务端监听端口。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000` |
#### 上传目录 #### 上传目录
帖子图片默认保存在 `uploads/` 目录(Docker 部署时通过 volume 挂载到 `/app/uploads`),源码部署时请确保该目录有写入权限: 帖子图片默认保存在 `uploads/` 目录,请确保该目录有写入权限:
```bash ```bash
mkdir -p uploads && chmod 755 uploads mkdir -p uploads && chmod 755 uploads
``` ```
## 📁 项目结构
```
forumlify/
├── index.html # 前端页面
├── style.css # 全局样式
├── Dockerfile # Docker 镜像构建文件
├── package-lock.json # 依赖锁定文件
├── server.js # 后端服务(Express)
├── js/ # 前端 JS 模块
│ ├── app.js
│ ├── admin.js
│ ├── api.js
│ ├── auth.js
│ ├── feed.js
│ ├── post.js
│ └── user.js
├── schema.sql # 数据库表结构
├── config.js # 配置文件
└── docker-compose.yml # Docker 编排
```
## 📝 License
MIT
+10 -2
View File
@@ -11,17 +11,25 @@ services:
- db_data:/var/lib/postgresql/data - db_data:/var/lib/postgresql/data
ports: ports:
- "5432:5432" - "5432:5432"
restart: unless-stopped
app: app:
build: . # 从 GHCR 拉取镜像(每次 push Lite 自动重建),不再本地构建
image: ghcr.io/furrium/forumlify:lite
ports: ports:
- "3003:3000" - "3000:3000"
depends_on: depends_on:
- db - db
environment: environment:
DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify
PORT: 3000
ENABLE_CAPTCHA: "true"
JWT_SECRET: "${JWT_SECRET:?Set JWT_SECRET in .env before starting Forumlify}"
# 信任反向代理(Nginx / Docker 端口转发),修复限流警告
TRUST_PROXY: "true"
volumes: volumes:
- ./uploads:/app/uploads - ./uploads:/app/uploads
restart: unless-stopped
volumes: volumes:
db_data: db_data:
+141 -32
View File
@@ -4,10 +4,24 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title id="pageTitle">Forumlify</title> <title id="pageTitle">Forumlify</title>
<script>
(function() {
const theme = localStorage.getItem('forumlify-theme');
if (theme === 'dark') {
// 直接改背景色,不让白屏出现
document.documentElement.style.background = '#0f1117';
document.documentElement.style.color = '#e8edf5';
// 预置暗色属性,防止闪烁
document.documentElement.setAttribute('data-theme', 'dark');
}
})();
</script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="style.css" />
</head> </head>
<body> <body style="opacity:0;">
<!-- ===== 导航栏 ===== --> <!-- ===== 导航栏 ===== -->
<nav id="navbar"> <nav id="navbar">
@@ -69,7 +83,6 @@
<div class="stat-item"><span>主题</span><span id="statTopics">0</span></div> <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="statPosts">0</span></div>
<div class="stat-item"><span>用户</span><span id="statUsers">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>
<div class="links-box"> <div class="links-box">
<h4> <h4>
@@ -115,53 +128,116 @@
<!-- 设置页面 --> <!-- 设置页面 -->
<div id="pageSettings" class="page-slide"> <div id="pageSettings" class="page-slide">
<div class="page-header" style="max-width:500px;margin:0 auto;width:100%;"> <div class="page-header" style="max-width:1200px;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> <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> <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> </h2>
</div> </div>
<div id="settingsContent" style="max-width:500px;margin:0 auto;width:100%;">
<!-- 侧边栏布局 -->
<div class="settings-layout" style="max-width:1200px;margin:0 auto;width:100%;display:flex;gap:28px;align-items:flex-start;">
<!-- 左侧:侧边栏 -->
<aside class="settings-sidebar" style="width:200px;flex-shrink:0;background:var(--glass-bg);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid var(--glass-border);border-radius:var(--radius);padding:8px 0;box-shadow:var(--glass-shadow);position:sticky;top:84px;">
<nav class="settings-nav">
<a href="#" class="settings-nav-item active" data-settings-tab="profile">
<span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
</span>
个人资料
</a>
<a href="#" class="settings-nav-item" data-settings-tab="security">
<span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
</span>
安全设置
</a>
<a href="#" class="settings-nav-item" data-settings-tab="recovery">
<span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
</span>
恢复码
</a>
</nav>
</aside>
<!-- 右侧:内容区 -->
<main class="settings-content" style="flex:1;min-width:0;background:var(--glass-bg);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid var(--glass-border);border-radius:var(--radius);padding:20px 24px;box-shadow:var(--glass-shadow);">
<div id="settingsContent">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</div> </div>
</main>
</div>
</div> </div>
<!-- 管理后台 --> <!-- 管理后台 -->
<div id="pageAdmin" class="page-slide"> <div id="pageAdmin" class="page-slide">
<div class="page-header" style="max-width:900px;margin:0 auto;width:100%;"> <div class="page-header" style="max-width:1200px;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> <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> <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> </h2>
</div> </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> <div class="admin-layout" style="max-width:1200px;margin:0 auto;width:100%;">
<aside class="admin-sidebar">
<nav class="admin-nav">
<a href="#" class="admin-nav-item active" data-tab="reports">
<span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
</span>
举报 举报
</button> </a>
<button class="admin-tab" data-tab="users"> <a href="#" class="admin-nav-item" 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> <span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
</span>
用户 用户
</button> </a>
<button class="admin-tab" data-tab="logs"> <a href="#" class="admin-nav-item" 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> <span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
</span>
日志 日志
</button> </a>
<button class="admin-tab" data-tab="links"> <a href="#" class="admin-nav-item" 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> <span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
</span>
友链 友链
</button> </a>
<button class="admin-tab" data-tab="settings"> <a href="#" class="admin-nav-item" data-tab="custom-css">
<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> <span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
</span>
自定义 CSS
</a>
<a href="#" class="admin-nav-item" data-tab="settings">
<span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
</span>
论坛设置 论坛设置
</button> </a>
<button class="admin-tab" data-tab="custom"> <a href="#" class="admin-nav-item" 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> <span class="nav-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
</span>
自定义页面 自定义页面
</button> </a>
</div> </nav>
<div id="adminContent" style="max-width:900px;margin:0 auto;width:100%;"> </aside>
<main class="admin-content" id="adminContent">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</main>
</div> </div>
</div> </div>
@@ -195,24 +271,54 @@
<!-- 帖子详情页 --> <!-- 帖子详情页 -->
<div id="pagePost" class="page-slide"> <div id="pagePost" class="page-slide">
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;"> <div class="page-header" style="max-width:1200px;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="postDetailTitle">帖子详情</h2> <h2 id="postDetailTitle">帖子详情</h2>
</div> </div>
<div id="postDetailContent" style="max-width:700px;margin:0 auto;width:100%;">
<div class="post-detail-layout" style="max-width:1200px;margin:0 auto;width:100%;display:flex;gap:28px;align-items:flex-start;">
<aside id="postSidebar" style="width:240px;flex-shrink:0;">
<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="statTopics2">0</span></div>
<div class="stat-item"><span>帖子</span><span id="statPosts2">0</span></div>
<div class="stat-item"><span>用户</span><span id="statUsers2">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="friendlyLinks2">
<li style="color:#94a3b8;font-size:13px;">暂无链接</li>
</ul>
</div>
</aside>
<main style="flex:1;min-width:0;">
<div id="postDetailContent">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</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;"> <div id="replyArea" style="margin-top:24px;border-top:1px solid var(--glass-border);padding-top:20px;display:none;">
<h3 style="font-size:16px;margin-bottom:12px;"> <h3 style="font-size:16px;font-weight:600;margin-bottom:14px;color:var(--glass-text);">
<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> <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> </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> <textarea id="replyContent" rows="3" placeholder="写下你的回复..." style="width:100%;padding:12px 16px;background:rgba(255,255,255,0.1);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);border:1px solid var(--glass-border);border-radius:var(--radius-sm);font-size:14px;font-family:inherit;resize:vertical;color:var(--glass-text);transition:all var(--transition);"></textarea>
<div class="captcha-row" style="margin:10px 0;"> <div class="captcha-row" style="margin:10px 0;">
<span id="replyCaptchaQuestion">3 + 5 = ?</span> <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;" /> <input type="text" id="replyCaptchaInput" placeholder="答案" style="width:80px;padding:8px 12px;background:rgba(255,255,255,0.12);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);border:1px solid var(--glass-border);border-radius:var(--radius-sm);color:var(--glass-text);" />
</div> </div>
<button id="replySubmit" class="btn-primary" style="padding:8px 24px;">提交回复</button> <button id="replySubmit" class="btn-primary" style="padding:8px 24px;">提交回复</button>
</div> </div>
</main>
</div>
</div> </div>
<!-- 用户主页 --> <!-- 用户主页 -->
@@ -339,6 +445,9 @@
<!-- ⚙️ 引用 JS --> <!-- ⚙️ 引用 JS -->
<!-- ========================================================== --> <!-- ========================================================== -->
<script src="config.js"></script> <script src="config.js"></script>
<script src="js/icons.js"></script>
<script src="js/i18n.js"></script>
<script src="js/security.js"></script>
<script src="js/api.js"></script> <script src="js/api.js"></script>
<script src="js/theme.js"></script> <script src="js/theme.js"></script>
<script src="js/captcha.js"></script> <script src="js/captcha.js"></script>
+455 -56
View File
@@ -7,20 +7,24 @@ function renderAdminReports() {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getReports().then(reports => { API.getReports().then(reports => {
if (!reports || reports.length === 0) { if (!reports || reports.length === 0) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">✅ 暂无举报</div>'; container.innerHTML = `<div style="text-align:center;color:#94a3b8;padding:40px 0;">${getIcon('success')} 暂无举报</div>`;
return; return;
} }
let html = ''; let html = '';
const statusMap = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' }; const statusMap = {
pending: `${getIcon('pending')} 待处理`,
approved: `${getIcon('success')} 已删除`,
rejected: `${getIcon('error')} 已驳回`
};
reports.forEach(r => { reports.forEach(r => {
const postTitle = r.post_title || '无标题'; const postTitle = r.post_title || '无标题';
html += ` html += `
<div class="report-item"> <div class="report-item">
<div><strong>${r.reporter_name || '匿名'}</strong> 举报了帖子</div> <div><strong>${escapeHTML(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;">原因:${escapeHTML(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;color:#64748b;margin:4px 0;">帖子:${escapeHTML(postTitle)} — ${escapeHTML((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> <div style="font-size:13px;font-weight:600;">状态:${statusMap[r.status] || escapeHTML(r.status)}</div>
${r.handler_name ? `<div style="font-size:12px;color:#94a3b8;">处理人:${r.handler_name}${r.handler_note ? ' (' + r.handler_note + ')' : ''}</div>` : ''} ${r.handler_name ? `<div style="font-size:12px;color:#94a3b8;">处理人:${escapeHTML(r.handler_name)}${r.handler_note ? ' (' + escapeHTML(r.handler_note) + ')' : ''}</div>` : ''}
${r.status === 'pending' ? ` ${r.status === 'pending' ? `
<div class="report-actions"> <div class="report-actions">
<button class="btn-sm btn-danger" data-reportid="${r.id}" data-action="approve"> <button class="btn-sm btn-danger" data-reportid="${r.id}" data-action="approve">
@@ -36,7 +40,7 @@ function renderAdminReports() {
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('[data-action]').forEach(btn => { container.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
const id = this.dataset.reportid; const id = this.dataset.reportid;
@@ -45,12 +49,6 @@ function renderAdminReports() {
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立'; const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return; if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
API.updateReport(id, status, note).then(() => { 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(); renderAdminReports();
}).catch(err => alert('操作失败:' + err.message)); }).catch(err => alert('操作失败:' + err.message));
}); });
@@ -60,13 +58,35 @@ function renderAdminReports() {
}); });
} }
function renderAdminUsers() { // ============================================================
// 👥 用户列表(支持分页 + 搜索)
// ============================================================
let currentUsersPage = 1;
let usersTotalPages = 1;
let usersSearchKeyword = '';
function renderAdminUsers(page = 1, search = '') {
const container = document.getElementById('adminContent'); const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getUsers().then(users => {
currentUsersPage = page;
usersSearchKeyword = search;
API.getUsers(page, 20, search).then(result => {
const users = result.data || [];
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
usersTotalPages = pagination.totalPages || 1;
let html = ` let html = `
<div style="margin-bottom:12px;font-size:13px;color:#94a3b8;"> <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px;">
共 <strong>${users.length}</strong> 位用户 <span style="font-size:13px;color:#94a3b8;">共 <strong>${pagination.total}</strong> 位用户</span>
<div style="display:flex;gap:6px;">
<input type="text" id="userSearchInput" placeholder="搜索用户名..." value="${escapeHTML(search)}"
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;background:var(--bg);color:var(--text);" />
<button id="userSearchBtn" class="btn-sm btn-primary" style="padding:6px 14px;">搜索</button>
<button id="userClearSearchBtn" class="btn-sm btn-secondary" style="padding:6px 14px;">清空</button>
</div>
</div> </div>
<div style="overflow-x:auto;"> <div style="overflow-x:auto;">
<table style="width:100%;border-collapse:collapse;font-size:14px;"> <table style="width:100%;border-collapse:collapse;font-size:14px;">
@@ -80,6 +100,10 @@ function renderAdminUsers() {
</thead> </thead>
<tbody> <tbody>
`; `;
if (users.length === 0) {
html += `<tr><td colspan="4" style="text-align:center;padding:40px 0;color:#94a3b8;">暂无用户</td></tr>`;
} else {
users.forEach(u => { users.forEach(u => {
const isAdmin = u.role === 'admin'; const isAdmin = u.role === 'admin';
const isCurrentUser = currentUser && currentUser.id === u.id; const isCurrentUser = currentUser && currentUser.id === u.id;
@@ -87,9 +111,9 @@ function renderAdminUsers() {
<tr style="border-bottom:1px solid #f1f5f9;${isCurrentUser ? 'background:var(--primary-bg);' : ''}"> <tr style="border-bottom:1px solid #f1f5f9;${isCurrentUser ? 'background:var(--primary-bg);' : ''}">
<td style="padding:10px 12px;"> <td style="padding:10px 12px;">
<div style="display:flex;align-items:center;gap:8px;"> <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'}" <img src="${escapeHTML(safeURL(u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64', { image: true }))}"
style="width:28px;height:28px;border-radius:50%;object-fit:cover;" /> style="width:28px;height:28px;border-radius:50%;object-fit:cover;" />
<span style="font-weight:500;">${u.username}</span> <span style="font-weight:500;">${escapeHTML(u.username)}</span>
${isCurrentUser ? '<span style="font-size:11px;color:#94a3b8;background:#eef2ff;padding:1px 8px;border-radius:4px;">你</span>' : ''} ${isCurrentUser ? '<span style="font-size:11px;color:#94a3b8;background:#eef2ff;padding:1px 8px;border-radius:4px;">你</span>' : ''}
</div> </div>
</td> </td>
@@ -111,9 +135,71 @@ function renderAdminUsers() {
</tr> </tr>
`; `;
}); });
html += '</tbody></table></div>'; }
container.innerHTML = html;
html += '</tbody></table></div>';
// 分页控件
if (usersTotalPages > 1) {
html += `
<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="users-page-btn" data-page="${page - 1}" ${page <= 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;">
&laquo;
</button>
`;
let startPage = Math.max(1, page - 4);
let endPage = Math.min(usersTotalPages, page + 4);
if (page <= 4) endPage = Math.min(usersTotalPages, 9);
if (page > usersTotalPages - 4) startPage = Math.max(1, usersTotalPages - 8);
if (startPage > 1) {
html += `<button class="users-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) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
}
for (let i = startPage; i <= endPage; i++) {
const isActive = i === page;
html += `
<button class="users-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 < usersTotalPages) {
if (endPage < usersTotalPages - 1) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
html += `<button class="users-page-btn" data-page="${usersTotalPages}" style="padding:6px 10px;border:1px solid var(--border);border-radius:4px;background:var(--surface);color:var(--text);cursor:pointer;font-size:13px;">${usersTotalPages}</button>`;
}
html += `
<button class="users-page-btn" data-page="${page + 1}" ${page >= usersTotalPages ? '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;">
&raquo;
</button>
<span style="font-size:13px;color:var(--text-light);margin-left:8px;">
${pagination.total} 位用户
</span>
</div>
`;
}
container.innerHTML = sanitizeHTML(html);
// 绑定分页按钮事件
container.querySelectorAll('.users-page-btn:not([disabled])').forEach(btn => {
btn.addEventListener('click', function() {
const newPage = parseInt(this.dataset.page);
if (newPage >= 1 && newPage <= usersTotalPages) {
renderAdminUsers(newPage, usersSearchKeyword);
}
});
});
// 绑定角色切换事件
container.querySelectorAll('[data-role]').forEach(btn => { container.querySelectorAll('[data-role]').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
const userId = this.dataset.userid; const userId = this.dataset.userid;
@@ -121,41 +207,154 @@ function renderAdminUsers() {
const roleName = role === 'admin' ? '管理员' : '普通用户'; const roleName = role === 'admin' ? '管理员' : '普通用户';
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return; if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
API.updateUserRole(userId, role).then(() => { API.updateUserRole(userId, role).then(() => {
renderAdminUsers(); renderAdminUsers(currentUsersPage, usersSearchKeyword);
}).catch(err => alert('操作失败:' + err.message)); }).catch(err => alert('操作失败:' + err.message));
}); });
}); });
// 搜索按钮
const searchBtn = document.getElementById('userSearchBtn');
if (searchBtn) {
searchBtn.addEventListener('click', function() {
const input = document.getElementById('userSearchInput');
renderAdminUsers(1, input.value.trim());
});
}
// 清空搜索
const clearBtn = document.getElementById('userClearSearchBtn');
if (clearBtn) {
clearBtn.addEventListener('click', function() {
const input = document.getElementById('userSearchInput');
input.value = '';
renderAdminUsers(1, '');
});
}
// 回车搜索
const searchInput = document.getElementById('userSearchInput');
if (searchInput) {
searchInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
renderAdminUsers(1, this.value.trim());
}
});
}
}).catch(() => { }).catch(() => {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
}); });
} }
function renderAdminLogs() { // ============================================================
// 📜 操作日志(支持分页)
// ============================================================
function renderAdminLogs(page = 1) {
const container = document.getElementById('adminContent'); const container = document.getElementById('adminContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
API.getEventLogs().then(logs => {
API.getEventLogs(page, 20).then(result => {
const logs = result.data || [];
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
const totalPages = pagination.totalPages || 1;
if (!logs || logs.length === 0) { if (!logs || logs.length === 0) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">暂无日志</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">暂无日志</div>';
return; 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>'; 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 => { logs.forEach(l => {
html += ` html += `
<tr style="border-bottom:1px solid #f1f5f9;"> <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;">${new Date(l.created_at).toLocaleString('zh-CN')}</td>
<td style="padding:6px 0;">${l.username || '系统'}</td> <td style="padding:6px 0;">${escapeHTML(l.username || '系统')}</td>
<td style="padding:6px 0;">${l.action}</td> <td style="padding:6px 0;">${escapeHTML(l.action)}</td>
</tr> </tr>
`; `;
}); });
html += '</tbody></table>'; html += '</tbody></table>';
container.innerHTML = html;
// 分页控件
if (totalPages > 1) {
html += `
<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="logs-page-btn" data-page="${page - 1}" ${page <= 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;">
&laquo;
</button>
`;
let startPage = Math.max(1, page - 4);
let endPage = Math.min(totalPages, page + 4);
if (page <= 4) endPage = Math.min(totalPages, 9);
if (page > totalPages - 4) startPage = Math.max(1, totalPages - 8);
if (startPage > 1) {
html += `<button class="logs-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) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
}
for (let i = startPage; i <= endPage; i++) {
const isActive = i === page;
html += `
<button class="logs-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) html += `<span style="color:var(--text-light);padding:0 4px;">…</span>`;
html += `<button class="logs-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>`;
}
html += `
<button class="logs-page-btn" data-page="${page + 1}" ${page >= 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;">
&raquo;
</button>
<span style="font-size:13px;color:var(--text-light);margin-left:8px;">
${pagination.total} 条日志
</span>
</div>
`;
}
container.innerHTML = sanitizeHTML(html);
// 绑定分页按钮事件
container.querySelectorAll('.logs-page-btn:not([disabled])').forEach(btn => {
btn.addEventListener('click', function() {
const newPage = parseInt(this.dataset.page);
if (newPage >= 1 && newPage <= totalPages) {
renderAdminLogs(newPage);
}
});
});
}).catch(() => { }).catch(() => {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载失败</div>';
}); });
} }
// ============================================================
// 🔗 友情链接管理
// ============================================================
function renderAdminLinks() { function renderAdminLinks() {
const container = document.getElementById('adminContent'); const container = document.getElementById('adminContent');
container.innerHTML = ` container.innerHTML = `
@@ -178,15 +377,15 @@ function renderAdminLinks() {
links.forEach(l => { links.forEach(l => {
html += ` html += `
<div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;"> <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> <span><a href="${escapeHTML(safeURL(l.url, { allowRelative: false }))}" target="_blank" rel="noopener noreferrer" style="color:#6366f1;text-decoration:none;">${escapeHTML(l.title)}</a></span>
<button class="btn-sm btn-danger" data-linkid="${l.id}"> <button class="btn-sm btn-danger" data-linkid="${l.id}" style="background:rgba(239,68,68,0.08);border:1.5px solid #ef4444;color:#1a1a2e;padding:2px 10px;border-radius:6px;transition:all 0.2s;cursor:pointer;font-size:12px;font-weight:500;">
<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> <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>
</div> </div>
`; `;
}); });
ul.innerHTML = html; ul.innerHTML = sanitizeHTML(html);
ul.querySelectorAll('[data-linkid]').forEach(btn => { ul.querySelectorAll('[data-linkid]').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
if (!confirm('确定删除该链接吗?')) return; if (!confirm('确定删除该链接吗?')) return;
@@ -210,10 +409,15 @@ function renderAdminLinks() {
}); });
} }
// ============================================================
// ⚙️ 论坛设置(只改名称)
// ============================================================
function renderAdminSettings() { function renderAdminSettings() {
const container = document.getElementById('adminContent'); const container = document.getElementById('adminContent');
container.innerHTML = ` container.innerHTML = `
<h3 style="margin-bottom:16px;">⚙️ 论坛设置</h3> <h3 style="margin-bottom:16px;text-align:center;">${getIcon('settings')} 论坛名称</h3>
<div style="max-width:400px;margin:0 auto;width:100%;"> <div style="max-width:400px;margin:0 auto;width:100%;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;">论坛名称</label> <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);" /> <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);" />
@@ -231,19 +435,141 @@ function renderAdminSettings() {
if (!name) { alert('请输入论坛名称'); return; } if (!name) { alert('请输入论坛名称'); return; }
try { try {
await API.updateSettings(name); await API.updateSettings(name);
document.getElementById('settingsResult').textContent = '✅ 保存成功!'; document.getElementById('settingsResult').textContent = `${getIcon('success')} 保存成功!`;
document.getElementById('settingsResult').style.color = '#22c55e'; document.getElementById('settingsResult').style.color = '#22c55e';
document.getElementById('forumName').textContent = name; document.getElementById('forumName').textContent = name;
document.title = name; document.title = name;
const titleEl = document.getElementById('pageTitle'); const titleEl = document.getElementById('pageTitle');
if (titleEl) titleEl.textContent = name; if (titleEl) titleEl.textContent = name;
} catch (err) { } catch (err) {
document.getElementById('settingsResult').textContent = '❌ 保存失败'; document.getElementById('settingsResult').textContent = `${getIcon('error')} 保存失败`;
document.getElementById('settingsResult').style.color = '#ef4444'; document.getElementById('settingsResult').style.color = '#ef4444';
} }
}); });
} }
// ============================================================
// 🎨 自定义 CSS(独立标签页)- 已改用 Toast 提示
// ============================================================
function renderAdminCustomCSS() {
const container = document.getElementById('adminContent');
container.innerHTML = `
<h3 style="margin-bottom:8px;text-align:center;">${getIcon('paint')} 自定义 CSS</h3>
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px;text-align:center;">上传 style.css 覆盖默认样式,自定义论坛外观。</p>
<div style="max-width:500px;margin:0 auto;">
<div id="customCssDropZone" style="border:2px dashed var(--border);border-radius:8px;padding:32px;text-align:center;cursor:pointer;transition:all 0.3s;background:var(--bg);">
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block;margin:0 auto 8px;color:var(--text-secondary);"><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>
<p style="color:var(--text-secondary);font-size:14px;margin:0;">
<span id="customCssDropText">点击或拖拽上传 style.css</span>
</p>
<p style="color:var(--text-light);font-size:12px;margin:4px 0 0;">只能上传 style.css 文件</p>
<input type="file" id="customCssInput" accept=".css" style="display:none;" />
</div>
<div id="customCssStatus" style="font-size:13px;margin-top:8px;color:var(--text-light);"></div>
<div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;justify-content:center;">
<button id="customCssSaveBtn" class="btn-primary" style="padding:8px 20px;">${getIcon('save')} 保存 CSS</button>
<button id="customCssDeleteBtn" class="btn-secondary" style="padding:8px 20px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">${getIcon('delete')} 删除自定义 CSS</button>
</div>
</div>
`;
// 自定义 CSS 上传逻辑
const dropZone = document.getElementById('customCssDropZone');
const fileInput = document.getElementById('customCssInput');
const dropText = document.getElementById('customCssDropText');
const statusEl = document.getElementById('customCssStatus');
let selectedFile = null;
if (dropZone && fileInput) {
dropZone.addEventListener('click', function() {
fileInput.click();
});
fileInput.addEventListener('change', function() {
if (this.files.length > 0) {
handleCssFile(this.files[0]);
}
});
dropZone.addEventListener('dragover', function(e) {
e.preventDefault();
this.style.borderColor = 'var(--primary)';
this.style.background = 'var(--primary-bg)';
dropText.textContent = '松开上传';
});
dropZone.addEventListener('dragleave', function(e) {
e.preventDefault();
this.style.borderColor = 'var(--border)';
this.style.background = 'var(--bg)';
dropText.textContent = '点击或拖拽上传 style.css';
});
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
this.style.borderColor = 'var(--border)';
this.style.background = 'var(--bg)';
dropText.textContent = '点击或拖拽上传 style.css';
if (e.dataTransfer.files.length > 0) {
handleCssFile(e.dataTransfer.files[0]);
}
});
}
function handleCssFile(file) {
if (file.name !== 'style.css') {
showToast('文件名必须是 style.css', 'error');
selectedFile = null;
fileInput.value = '';
return;
}
if (!file.type.includes('text/css') && !file.name.endsWith('.css')) {
showToast('请上传 CSS 文件', 'error');
selectedFile = null;
fileInput.value = '';
return;
}
selectedFile = file;
showToast('已选择: ' + file.name + ' (' + (file.size / 1024).toFixed(1) + ' KB)', 'success');
}
document.getElementById('customCssSaveBtn').addEventListener('click', function() {
if (!selectedFile) {
showToast('请先选择 style.css 文件', 'warning');
return;
}
showCustomCssWarningModal(async function() {
try {
await API.uploadCustomCSS(selectedFile);
showToast('CSS 上传成功!刷新页面查看效果', 'success');
selectedFile = null;
fileInput.value = '';
dropText.textContent = '点击或拖拽上传 style.css';
loadCustomCSS();
} catch (err) {
showToast('上传失败:' + err.message, 'error');
}
});
});
document.getElementById('customCssDeleteBtn').addEventListener('click', async function() {
if (!confirm('确定要删除自定义 CSS 吗?将恢复默认样式。')) return;
try {
await API.deleteCustomCSS();
showToast('已删除自定义 CSS', 'success');
const link = document.getElementById('customCssLink');
if (link) link.remove();
} catch (err) {
showToast('删除失败:' + err.message, 'error');
}
});
}
// ============================================================ // ============================================================
// 📄 自定义页面管理 // 📄 自定义页面管理
// ============================================================ // ============================================================
@@ -254,8 +580,8 @@ function renderAdminCustomPages() {
const container = document.getElementById('adminContent'); const container = document.getElementById('adminContent');
container.innerHTML = ` container.innerHTML = `
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;"> <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
<h3 style="margin:0;">📄 自定义页面</h3> <h3 style="margin:0;">${getIcon('page')} 自定义页面</h3>
<button id="addCustomPageBtn" class="btn-primary" style="padding:8px 16px;">➕ 添加页面</button> <button id="addCustomPageBtn" class="btn-primary" style="padding:8px 16px;">${getIcon('add')} 添加页面</button>
</div> </div>
<div id="customPageList"></div> <div id="customPageList"></div>
`; `;
@@ -292,19 +618,19 @@ function loadCustomPageList() {
pages.forEach(p => { pages.forEach(p => {
html += ` html += `
<tr style="border-bottom:1px solid var(--border-light);"> <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;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">${escapeHTML(p.name)}</code></td>
<td style="padding:8px 12px;">${p.title}</td> <td style="padding:8px 12px;">${escapeHTML(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;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">?custom=${escapeHTML(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;"><span style="color:${p.enabled ? '#22c55e' : '#ef4444'};">${p.enabled ? `${getIcon('success')} 启用` : `${getIcon('error')} 禁用`}</span></td>
<td style="padding:8px 12px;text-align:center;display:flex;gap:6px;justify-content:center;"> <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-secondary" data-id="${p.id}" data-action="edit">${getIcon('edit')}</button>
<button class="btn-sm btn-danger" data-id="${p.id}" data-action="delete">🗑️</button> <button class="btn-sm btn-danger" data-id="${p.id}" data-action="delete">${getIcon('delete')}</button>
</td> </td>
</tr> </tr>
`; `;
}); });
html += '</tbody></table></div>'; html += '</tbody></table></div>';
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('[data-action="edit"]').forEach(btn => { container.querySelectorAll('[data-action="edit"]').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
@@ -338,16 +664,16 @@ function openCustomPageEditor(page) {
modal.innerHTML = ` modal.innerHTML = `
<div class="modal-content" style="max-width:600px;max-height:90vh;overflow-y:auto;"> <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);">&times;</span> <span class="close" style="position:absolute;top:12px;right:16px;font-size:24px;cursor:pointer;color:var(--text-light);">&times;</span>
<h2 style="margin-bottom:16px;">${isEdit ? '✏️ 编辑页面' : '📄 添加页面'}</h2> <h2 style="margin-bottom:16px;">${isEdit ? getIcon('edit') + ' 编辑页面' : getIcon('add') + ' 添加页面'}</h2>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面名称</label> <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);"' : ''} <input type="text" id="editorPageName" value="${isEdit ? escapeHTML(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);" /> 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>'} ${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>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">导航栏显示名称</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">导航栏显示名称</label>
<input type="text" id="editorPageTitle" value="${isEdit ? page.title : ''}" <input type="text" id="editorPageTitle" value="${isEdit ? escapeHTML(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);" /> 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>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
@@ -359,7 +685,7 @@ function openCustomPageEditor(page) {
</div> </div>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面内容(HTML + CSS + JS)</label> <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> <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 ? escapeHTML(page.content) : ''}</textarea>
<div style="font-size:12px;color:var(--text-light);margin-top:2px;">支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div> <div style="font-size:12px;color:var(--text-light);margin-top:2px;">支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div>
</div> </div>
<button id="editorSaveBtn" class="btn-primary" style="padding:10px 24px;width:100%;">保存</button> <button id="editorSaveBtn" class="btn-primary" style="padding:10px 24px;width:100%;">保存</button>
@@ -405,21 +731,94 @@ function openCustomPageEditor(page) {
} }
// ============================================================ // ============================================================
// 管理后台Tab切换 // 自定义 CSS 警告模态框
// ============================================================ // ============================================================
document.querySelectorAll('.admin-tab').forEach(tab => { function showCustomCssWarningModal(onConfirm) {
tab.addEventListener('click', function() { const modal = document.createElement('div');
document.querySelectorAll('.admin-tab').forEach(t => t.classList.remove('active')); modal.className = 'modal active';
this.classList.add('active'); modal.style.display = 'flex';
modal.innerHTML = `
<div class="modal-content" style="max-width:420px;">
<h2 style="margin-bottom:12px;">${getIcon('warning')} 警告</h2>
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">
若上传的 <strong>style.css</strong> 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。
</p>
<p style="font-size:13px;color:var(--text-light);margin-bottom:20px;">
请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。
</p>
<div style="display:flex;gap:8px;">
<button id="cssWarningConfirm" class="btn-primary" style="padding:8px 24px;">我了解,继续上传</button>
<button id="cssWarningCancel" class="btn-secondary" style="padding:8px 24px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">取消</button>
</div>
</div>
`;
document.body.appendChild(modal);
modal.querySelector('#cssWarningConfirm').addEventListener('click', function() {
modal.remove();
if (onConfirm) onConfirm();
});
modal.querySelector('#cssWarningCancel').addEventListener('click', function() {
modal.remove();
});
modal.addEventListener('click', function(e) {
if (e.target === this) modal.remove();
});
}
// ============================================================
// 加载自定义 CSS
// ============================================================
function loadCustomCSS() {
const existing = document.getElementById('customCssLink');
if (existing) existing.remove();
const link = document.createElement('link');
link.id = 'customCssLink';
link.rel = 'stylesheet';
link.href = CONFIG.API_BASE_URL + '/custom-css?v=' + Date.now();
link.onerror = function() {
// 如果自定义 CSS 不存在,静默失败
};
document.head.appendChild(link);
}
// ============================================================
// 管理后台Tab切换(侧边栏适配)
// ============================================================
// 使用事件委托监听 .admin-nav 下的点击
document.querySelector('.admin-nav')?.addEventListener('click', function(e) {
const tabLink = e.target.closest('.admin-nav-item');
if (!tabLink) return;
e.preventDefault();
const tab = tabLink.dataset.tab;
if (!tab) return;
// 切换高亮
document.querySelectorAll('.admin-nav-item').forEach(el => el.classList.remove('active'));
tabLink.classList.add('active');
// 渲染对应内容
const tabMap = { const tabMap = {
reports: renderAdminReports, reports: renderAdminReports,
users: renderAdminUsers, users: renderAdminUsers,
logs: renderAdminLogs, logs: renderAdminLogs,
links: renderAdminLinks, links: renderAdminLinks,
'custom-css': renderAdminCustomCSS,
settings: renderAdminSettings, settings: renderAdminSettings,
custom: renderAdminCustomPages custom: renderAdminCustomPages
}; };
if (tabMap[this.dataset.tab]) tabMap[this.dataset.tab](); if (tabMap[tab]) tabMap[tab]();
}); });
// 页面加载时尝试加载自定义 CSS
document.addEventListener('DOMContentLoaded', function() {
setTimeout(loadCustomCSS, 500);
}); });
+69 -16
View File
@@ -95,6 +95,14 @@ const API = {
return data; return data;
}, },
async togglePinPost(postId) {
const data = await apiFetch('/posts/' + postId + '/pin', {
method: 'PUT'
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================ // ============================================================
// 回复 // 回复
// ============================================================ // ============================================================
@@ -120,12 +128,12 @@ const API = {
}, },
// ============================================================ // ============================================================
// 用户管理 // 用户管理(支持分页和搜索)
// ============================================================ // ============================================================
async getUsers() { async getUsers(page = 1, limit = 20, search = '') {
const data = await apiFetch('/users'); const data = await apiFetch('/users?page=' + page + '&limit=' + limit + '&search=' + encodeURIComponent(search));
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data || []; return data;
}, },
async updateUserRole(userId, role) { async updateUserRole(userId, role) {
@@ -198,22 +206,14 @@ const API = {
}, },
// ============================================================ // ============================================================
// 事件日志 // 事件日志(支持分页)
// ============================================================ // ============================================================
async getEventLogs() { async getEventLogs(page = 1, limit = 20) {
const data = await apiFetch('/event-logs'); const data = await apiFetch('/event-logs?page=' + page + '&limit=' + limit);
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data || []; return data;
}, },
async logEvent(action) {
try {
await apiFetch('/event-logs', {
method: 'POST',
body: JSON.stringify({ action })
});
} catch (e) { /* 静默失败 */ }
},
// ============================================================ // ============================================================
// 论坛设置 // 论坛设置
@@ -376,5 +376,58 @@ const API = {
}); });
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data; return data;
},
// ============================================================
// 置顶
// ============================================================
async togglePinPost(postId) {
const data = await apiFetch('/posts/' + postId + '/pin', {
method: 'PUT'
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 更新用户资料(含签名)
// ============================================================
async updateProfile(userId, username, bio, signature) {
const data = await apiFetch('/users/' + userId, {
method: 'PUT',
body: JSON.stringify({ username, bio, signature })
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 自定义 CSS
// ============================================================
async uploadCustomCSS(file) {
const formData = new FormData();
formData.append('file', file);
const url = CONFIG.API_BASE_URL + '/admin/custom-css';
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('forumlify-token')
},
body: formData
});
const data = await response.json();
if (data.error) throw new Error(data.error);
return data;
},
async deleteCustomCSS() {
const data = await apiFetch('/admin/custom-css', {
method: 'DELETE'
});
if (data.error) throw new Error(data.error);
return data;
} }
}; };
+284 -110
View File
@@ -3,6 +3,36 @@
// ============================================================ // ============================================================
let currentUser = null; let currentUser = null;
function showToast(message, type = 'success', duration = 3000) {
// 移除已有 toast
const existing = document.querySelector('.toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = 'toast ' + type;
const icons = {
success: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>`,
error: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>`,
warning: `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/></svg>`
};
toast.innerHTML = `
<span class="toast-icon">${icons[type] || icons.success}</span>
${escapeHTML(message)}
`;
document.body.appendChild(toast);
requestAnimationFrame(() => {
toast.classList.add('show');
});
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 400);
}, duration);
}
let currentPage = 'feed'; let currentPage = 'feed';
let currentPageNum = 1; let currentPageNum = 1;
@@ -124,7 +154,7 @@ function switchPage(page, param) {
renderAdminReports(); renderAdminReports();
} }
if (page === 'settings') { if (page === 'settings') {
renderSettingsPage(); renderSettingsPage('profile');
} }
if (page === 'messages') { if (page === 'messages') {
renderMessagesPage(); renderMessagesPage();
@@ -194,25 +224,30 @@ async function renderMessageList() {
const unread = c.unread_count || 0; const unread = c.unread_count || 0;
const lastMsg = c.last_message || '暂无消息'; const lastMsg = c.last_message || '暂无消息';
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : ''; const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
const avatar = c.other_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(c.other_username) + '&background=6366f1&color=fff&size=64';
html += ` html += `
<div class="message-list-item" style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer;transition:background 0.15s;" <div class="message-list-item" data-conversation-id="${escapeHTML(c.id)}" data-user-id="${escapeHTML(c.other_user_id)}" data-username="${escapeHTML(c.other_username)}" style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer;transition:background 0.15s;">
onclick="openChat('${c.id}', '${c.other_user_id}', '${c.other_username}')"> <img src="${escapeHTML(safeURL(avatar, { image: true }))}"
<img src="${c.other_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(c.other_username) + '&background=6366f1&color=fff&size=64'}"
style="width:40px;height:40px;border-radius:50%;object-fit:cover;" /> style="width:40px;height:40px;border-radius:50%;object-fit:cover;" />
<div style="flex:1;min-width:0;"> <div style="flex:1;min-width:0;">
<div style="display:flex;justify-content:space-between;align-items:center;"> <div style="display:flex;justify-content:space-between;align-items:center;">
<span style="font-weight:600;">${c.other_username}</span> <span style="font-weight:600;">${escapeHTML(c.other_username)}</span>
<span style="font-size:12px;color:var(--text-light);">${time}</span> <span style="font-size:12px;color:var(--text-light);">${time}</span>
</div> </div>
<div style="display:flex;justify-content:space-between;align-items:center;"> <div style="display:flex;justify-content:space-between;align-items:center;">
<span style="font-size:13px;color:var(--text-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;">${lastMsg}</span> <span style="font-size:13px;color:var(--text-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;">${escapeHTML(lastMsg)}</span>
${unread > 0 ? `<span style="background:#ef4444;color:#fff;border-radius:50%;padding:2px 8px;font-size:11px;font-weight:600;">${unread}</span>` : ''} ${unread > 0 ? `<span style="background:#ef4444;color:#fff;border-radius:50%;padding:2px 8px;font-size:11px;font-weight:600;">${unread}</span>` : ''}
</div> </div>
</div> </div>
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('.message-list-item').forEach(item => {
item.addEventListener('click', function() {
openChat(this.dataset.conversationId, this.dataset.userId, this.dataset.username);
});
});
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
} }
@@ -257,19 +292,20 @@ async function renderMessages(conversationId, silent = false) {
try { try {
const messages = await API.getMessages(conversationId); const messages = await API.getMessages(conversationId);
if (messages.length === 0) { if (messages.length === 0) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">还没有消息,打个招呼吧 👋</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">还没有消息,打个招呼吧</div>';
return; return;
} }
let html = ''; let html = '';
messages.forEach(m => { messages.forEach(m => {
const isMine = m.sender_id === currentUser.id; const isMine = m.sender_id === currentUser.id;
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : ''; const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
const avatar = m.sender_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(m.sender_username) + '&background=6366f1&color=fff&size=64';
html += ` html += `
<div style="display:flex;${isMine ? 'justify-content:flex-end;' : 'justify-content:flex-start;'} margin-bottom:12px;"> <div style="display:flex;${isMine ? 'justify-content:flex-end;' : 'justify-content:flex-start;'} margin-bottom:12px;">
${!isMine ? `<img src="${m.sender_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(m.sender_username) + '&background=6366f1&color=fff&size=64'}" style="width:32px;height:32px;border-radius:50%;object-fit:cover;margin-right:8px;flex-shrink:0;" />` : ''} ${!isMine ? `<img src="${escapeHTML(safeURL(avatar, { image: true }))}" style="width:32px;height:32px;border-radius:50%;object-fit:cover;margin-right:8px;flex-shrink:0;" />` : ''}
<div style="max-width:70%;"> <div style="max-width:70%;">
<div style="background:${isMine ? 'var(--primary)' : 'var(--surface)'};color:${isMine ? '#fff' : 'var(--text)'};padding:10px 14px;border-radius:12px;border:${isMine ? 'none' : '1px solid var(--border)'};word-break:break-word;"> <div style="background:${isMine ? 'var(--primary)' : 'var(--surface)'};color:${isMine ? '#fff' : 'var(--text)'};padding:10px 14px;border-radius:12px;border:${isMine ? 'none' : '1px solid var(--border)'};word-break:break-word;">
${m.content} ${renderPlainText(m.content)}
</div> </div>
<div style="font-size:11px;color:var(--text-light);margin-top:4px;${isMine ? 'text-align:right;' : ''}"> <div style="font-size:11px;color:var(--text-light);margin-top:4px;${isMine ? 'text-align:right;' : ''}">
${time} ${isMine ? (m.is_read ? '✓✓' : '✓') : ''} ${time} ${isMine ? (m.is_read ? '✓✓' : '✓') : ''}
@@ -278,7 +314,7 @@ async function renderMessages(conversationId, silent = false) {
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.scrollTop = container.scrollHeight; container.scrollTop = container.scrollHeight;
} catch (err) { } catch (err) {
if (!silent) { if (!silent) {
@@ -422,7 +458,7 @@ function showCustomPage(pageName) {
API.getCustomPage(pageName).then(page => { API.getCustomPage(pageName).then(page => {
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');
iframe.style.cssText = 'width:100%;min-height:70vh;border:none;border-radius:8px;background:var(--surface);'; iframe.style.cssText = 'width:100%;min-height:70vh;border:none;border-radius:8px;background:var(--surface);';
iframe.sandbox = 'allow-scripts allow-modals allow-same-origin'; iframe.sandbox = 'allow-scripts allow-modals allow-top-navigation allow-same-origin allow-popups';
iframe.srcdoc = ` iframe.srcdoc = `
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -453,7 +489,7 @@ function showCustomPage(pageName) {
el.style.color = el.dataset.custom === pageName ? 'var(--primary)' : 'var(--text-secondary)'; el.style.color = el.dataset.custom === pageName ? 'var(--primary)' : 'var(--text-secondary)';
}); });
}).catch(err => { }).catch(err => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">页面加载失败:' + err.message + '</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">页面加载失败:' + escapeHTML(err.message) + '</div>';
}); });
} }
@@ -485,40 +521,107 @@ async function renderMessagesPage() {
let html = ''; let html = '';
const typeMap = { const typeMap = {
reply: '💬', reply: getIcon('message'),
post_deleted: '🗑️', post_deleted: getIcon('delete'),
report_handled: '🛡️', report_handled: getIcon('shield'),
system: '📢' system: getIcon('megaphone')
}; };
notifications.forEach(n => { notifications.forEach(n => {
const icon = typeMap[n.type] || '📌'; const icon = typeMap[n.type] || getIcon('pin');
const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : ''; const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : '';
html += ` html += `
<div style="display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-bottom:1px solid var(--border-light);background:var(--surface);border-radius:6px;margin-bottom:6px;"> <div style="display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-bottom:1px solid var(--border-light);background:var(--surface);border-radius:6px;margin-bottom:6px;">
<span style="font-size:20px;">${icon}</span> <span style="font-size:20px;display:inline-flex;align-items:center;">${icon}</span>
<div style="flex:1;min-width:0;"> <div style="flex:1;min-width:0;">
<div style="font-weight:600;font-size:14px;">${n.title}</div> <div style="font-weight:600;font-size:14px;">${escapeHTML(n.title)}</div>
<div style="color:var(--text-secondary);font-size:13px;margin-top:2px;">${n.content}</div> <div style="color:var(--text-secondary);font-size:13px;margin-top:2px;">${escapeHTML(n.content)}</div>
${n.link ? `<a href="${n.link}" style="color:var(--primary);font-size:13px;text-decoration:none;margin-top:4px;display:inline-block;">查看详情 →</a>` : ''} ${n.link ? `<a href="${escapeHTML(safeURL(n.link))}" style="color:var(--primary);font-size:13px;text-decoration:none;margin-top:4px;display:inline-block;">查看详情 →</a>` : ''}
<div style="font-size:12px;color:var(--text-light);margin-top:4px;">${time}</div> <div style="font-size:12px;color:var(--text-light);margin-top:4px;">${time}</div>
</div> </div>
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
} }
} }
// ============================================================ // ============================================================
// ⚙️ 设置页面(含头像上传、恢复码、修改密码和邮箱) // 📊 统计数据
// ============================================================ // ============================================================
async function renderSettingsPage() { function renderStats() {
API.getStats().then(stats => {
// 主页的统计
const topicsEl = document.getElementById('statTopics');
const postsEl = document.getElementById('statPosts');
const usersEl = document.getElementById('statUsers');
if (topicsEl) topicsEl.textContent = stats.topics || 0;
if (postsEl) postsEl.textContent = stats.posts || 0;
if (usersEl) usersEl.textContent = stats.users || 0;
// 帖子详情页的统计(ID 带 2)
const topics2El = document.getElementById('statTopics2');
const posts2El = document.getElementById('statPosts2');
const users2El = document.getElementById('statUsers2');
if (topics2El) topics2El.textContent = stats.topics || 0;
if (posts2El) posts2El.textContent = stats.posts || 0;
if (users2El) users2El.textContent = stats.users || 0;
}).catch(() => {});
}
// ============================================================
// 🔗 友情链接
// ============================================================
function renderLinks() {
API.getLinks().then(links => {
// 主页的友链
const ul = document.getElementById('friendlyLinks');
if (ul) {
if (!links || links.length === 0) {
ul.innerHTML = '<li style="color:#94a3b8;font-size:13px;">暂无链接</li>';
} else {
let html = '';
links.forEach(l => {
html += '<li><a href="' + escapeHTML(safeURL(l.url, { allowRelative: false })) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(l.title) + '</a></li>';
});
ul.innerHTML = sanitizeHTML(html);
}
}
// 帖子详情页的友链
const ul2 = document.getElementById('friendlyLinks2');
if (ul2) {
if (!links || links.length === 0) {
ul2.innerHTML = '<li style="color:#94a3b8;font-size:13px;">暂无链接</li>';
} else {
let html = '';
links.forEach(l => {
html += '<li><a href="' + escapeHTML(safeURL(l.url, { allowRelative: false })) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(l.title) + '</a></li>';
});
ul2.innerHTML = sanitizeHTML(html);
}
}
}).catch(() => {});
}
// ============================================================
// ⚙️ 设置页面(含侧边栏)
// ============================================================
let currentSettingsTab = 'profile';
async function renderSettingsPage(tab = 'profile') {
const container = document.getElementById('settingsContent'); const container = document.getElementById('settingsContent');
if (!container) return; if (!container) return;
// 更新侧边栏高亮
document.querySelectorAll('.settings-nav-item').forEach(el => el.classList.remove('active'));
document.querySelector(`.settings-nav-item[data-settings-tab="${tab}"]`)?.classList.add('active');
currentSettingsTab = tab;
if (!currentUser) { if (!currentUser) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">请先登录</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">请先登录</div>';
return; return;
@@ -536,24 +639,26 @@ async function renderSettingsPage() {
recoveryCount = countData.count || 0; recoveryCount = countData.count || 0;
} catch (e) {} } catch (e) {}
if (tab === 'profile') {
container.innerHTML = ` container.innerHTML = `
<div style="max-width:500px;margin:0 auto;padding:20px 0;"> <h3 style="margin-bottom:16px;text-align:center;">${getIcon('user')} 个人资料</h3>
<!-- 头像 --> <!-- 头像 -->
<div style="text-align:center;margin-bottom:24px;"> <div style="text-align:center;margin-bottom:24px;">
<div style="position:relative;display:inline-block;"> <div style="position:relative;display:inline-block;">
<img id="avatarPreview" src="${user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128'}" <img id="avatarPreview" src="${escapeHTML(safeURL(user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128', { image: true }))}"
style="width:100px;height:100px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" /> style="width:100px;height:100px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
<button id="avatarUploadBtn" style="position:absolute;bottom:0;right:0;background:var(--primary);color:#fff;border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(99,102,241,0.4);"> <button id="avatarUploadBtn" style="position:absolute;bottom:0;right:0;background:var(--primary);color:#fff;border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(99,102,241,0.4);">
📷 ${getIcon('camera')}
</button> </button>
</div> </div>
<input type="file" id="avatarFileInput" accept="image/*" style="display:none;" /> <input type="file" id="avatarFileInput" accept="image/*" style="display:none;" />
<h2 style="margin:12px 0 4px;">${user.username}</h2> <h2 style="margin:12px 0 4px;">${escapeHTML(user.username)}</h2>
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p> <p style="color:var(--text-secondary);font-size:14px;">${escapeHTML(user.bio || '这个人很懒,什么都没写')}</p>
<div style="display:flex;justify-content:center;gap:16px;margin-top:8px;font-size:13px;color:var(--text-secondary);flex-wrap:wrap;"> <div style="display:flex;justify-content:center;gap:16px;margin-top:8px;font-size:13px;color:var(--text-secondary);flex-wrap:wrap;">
<span>📅 加入 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span> <span>${getIcon('calendar')} 加入 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 ${postCount} 帖</span> <span>${getIcon('file')} ${postCount} 帖</span>
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''} ${user.role === 'admin' ? `<span style="color:var(--primary);font-weight:600;">${getIcon('shield')} 管理员</span>` : ''}
</div> </div>
<div id="avatarUploadStatus" style="font-size:13px;margin-top:8px;"></div> <div id="avatarUploadStatus" style="font-size:13px;margin-top:8px;"></div>
</div> </div>
@@ -562,57 +667,19 @@ async function renderSettingsPage() {
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;"> <div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;">
<div style="margin-bottom:16px;"> <div style="margin-bottom:16px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">用户名</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">用户名</label>
<input type="text" id="settingsUsername" value="${user.username}" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" /> <input type="text" id="settingsUsername" value="${escapeHTML(user.username)}" 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>
<div style="margin-bottom:16px;"> <div style="margin-bottom:16px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">个人简介</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">个人简介</label>
<textarea id="settingsBio" rows="3" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);resize:vertical;">${user.bio || ''}</textarea> <textarea id="settingsBio" rows="3" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);resize:vertical;">${escapeHTML(user.bio || '')}</textarea>
</div>
<div style="margin-bottom:16px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">帖子签名</label>
<textarea id="settingsSignature" rows="2" placeholder="显示在每篇帖子底部,支持 Markdown" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;background:var(--bg);color:var(--text);resize:vertical;font-family:inherit;">${escapeHTML(user.signature || '')}</textarea>
<div style="font-size:12px;color:var(--text-light);margin-top:2px;">用 --- 分隔,支持 Markdown</div>
</div> </div>
<button id="settingsSaveBtn" class="btn-primary" style="width:100%;padding:10px;">保存设置</button> <button id="settingsSaveBtn" class="btn-primary" style="width:100%;padding:10px;">保存设置</button>
</div> </div>
<!-- 账户安全 - 修改密码和邮箱 -->
<div style="margin-top:16px;background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;">
<h3 style="font-size:16px;margin-bottom:12px;">🔒 账户安全</h3>
<!-- 修改密码 -->
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:13px;display:block;margin-bottom:4px;">当前密码</label>
<input type="password" id="changeOldPassword" 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:13px;display:block;margin-bottom:4px;">新密码</label>
<input type="password" id="changeNewPassword" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
</div>
<button id="changePasswordBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">修改密码</button>
<div id="passwordChangeStatus" style="font-size:13px;margin-top:6px;color:var(--text-light);"></div>
<div style="border-top:1px solid var(--border);margin:16px 0;"></div>
<!-- 修改邮箱 -->
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:13px;display:block;margin-bottom:4px;">当前密码(验证身份)</label>
<input type="password" id="changeEmailPassword" 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:13px;display:block;margin-bottom:4px;">新邮箱</label>
<input type="email" id="changeNewEmail" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
</div>
<button id="changeEmailBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">修改邮箱</button>
<div id="emailChangeStatus" style="font-size:13px;margin-top:6px;color:var(--text-light);"></div>
</div>
<!-- 恢复码管理 -->
<div style="margin-top:16px;background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;">
<h3 style="font-size:16px;margin-bottom:8px;">🔑 恢复码</h3>
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px;">用于忘记密码时重置账户。每个恢复码只能使用一次。</p>
<div style="display:flex;gap:8px;flex-wrap:wrap;">
<button id="viewRecoveryCodesBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">📋 查看恢复码</button>
<button id="regenerateRecoveryCodesBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">🔄 重新生成</button>
</div>
<div id="recoveryCodesStatus" style="font-size:13px;color:var(--text-light);margin-top:8px;">剩余 ${recoveryCount} 个可用恢复码</div>
</div>
</div>
`; `;
// ===== 头像上传 ===== // ===== 头像上传 =====
@@ -630,18 +697,15 @@ async function renderSettingsPage() {
const file = this.files[0]; const file = this.files[0];
if (!file) return; if (!file) return;
if (!file.type.startsWith('image/')) { if (!file.type.startsWith('image/')) {
statusEl.textContent = '❌ 请选择图片文件'; showToast('请选择图片文件', 'error');
statusEl.style.color = '#ef4444';
return; return;
} }
if (file.size > 5 * 1024 * 1024) { if (file.size > 5 * 1024 * 1024) {
statusEl.textContent = '❌ 图片不能超过 5MB'; showToast('图片不能超过 5MB', 'error');
statusEl.style.color = '#ef4444';
return; return;
} }
statusEl.textContent = '⏳ 上传中...'; showToast('上传中...', 'warning');
statusEl.style.color = 'var(--text-secondary)';
try { try {
const formData = new FormData(); const formData = new FormData();
@@ -664,37 +728,67 @@ async function renderSettingsPage() {
currentUser.avatar_url = avatarUrl; currentUser.avatar_url = avatarUrl;
avatarPreview.src = avatarUrl; avatarPreview.src = avatarUrl;
statusEl.textContent = '✅ 头像更新成功!'; showToast('头像更新成功!', 'success');
statusEl.style.color = '#22c55e';
renderNav(); renderNav();
} catch (err) { } catch (err) {
statusEl.textContent = '❌ ' + err.message; showToast(err.message, 'error');
statusEl.style.color = '#ef4444';
} }
}); });
} }
// ===== 保存设置 ===== // ===== 保存设置(含签名) =====
document.getElementById('settingsSaveBtn').addEventListener('click', async function() { document.getElementById('settingsSaveBtn').addEventListener('click', async function() {
const username = document.getElementById('settingsUsername').value.trim(); const username = document.getElementById('settingsUsername').value.trim();
const bio = document.getElementById('settingsBio').value.trim(); const bio = document.getElementById('settingsBio').value.trim();
const signature = document.getElementById('settingsSignature').value.trim();
if (!username) { alert('用户名不能为空'); return; } if (!username) { alert('用户名不能为空'); return; }
try { try {
const data = await apiFetch('/users/' + user.id, { await API.updateProfile(user.id, username, bio, signature);
method: 'PUT',
body: JSON.stringify({ username, bio })
});
if (data.error) throw new Error(data.error);
currentUser.username = username; currentUser.username = username;
currentUser.bio = bio; currentUser.bio = bio;
currentUser.signature = signature;
alert('保存成功!'); alert('保存成功!');
renderNav(); renderNav();
renderSettingsPage(); renderSettingsPage('profile');
} catch (err) { } catch (err) {
alert('保存失败:' + err.message); alert('保存失败:' + err.message);
} }
}); });
}
else if (tab === 'security') {
container.innerHTML = `
<h3 style="margin-bottom:16px;text-align:center;">${getIcon('lock')} 安全设置</h3>
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;">
<h4 style="font-size:14px;margin-bottom:12px;">修改密码</h4>
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:13px;display:block;margin-bottom:4px;">当前密码</label>
<input type="password" id="changeOldPassword" 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:13px;display:block;margin-bottom:4px;">新密码</label>
<input type="password" id="changeNewPassword" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
</div>
<button id="changePasswordBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">修改密码</button>
<div id="passwordChangeStatus" style="font-size:13px;margin-top:6px;color:var(--text-light);"></div>
<div style="border-top:1px solid var(--border);margin:16px 0;"></div>
<h4 style="font-size:14px;margin-bottom:12px;">修改邮箱</h4>
<div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:13px;display:block;margin-bottom:4px;">当前密码(验证身份)</label>
<input type="password" id="changeEmailPassword" 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:13px;display:block;margin-bottom:4px;">新邮箱</label>
<input type="email" id="changeNewEmail" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
</div>
<button id="changeEmailBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">修改邮箱</button>
<div id="emailChangeStatus" style="font-size:13px;margin-top:6px;color:var(--text-light);"></div>
</div>
`;
// ===== 修改密码 ===== // ===== 修改密码 =====
document.getElementById('changePasswordBtn').addEventListener('click', async function() { document.getElementById('changePasswordBtn').addEventListener('click', async function() {
@@ -717,10 +811,10 @@ async function renderSettingsPage() {
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 = '✅ 密码修改成功!'; statusEl.textContent = getIcon('success') + ' 密码修改成功!';
statusEl.style.color = '#22c55e'; statusEl.style.color = '#22c55e';
} catch (err) { } catch (err) {
statusEl.textContent = '❌ ' + err.message; statusEl.textContent = getIcon('error') + ' ' + err.message;
statusEl.style.color = '#ef4444'; statusEl.style.color = '#ef4444';
} }
}); });
@@ -742,13 +836,28 @@ async function renderSettingsPage() {
document.getElementById('changeEmailPassword').value = ''; document.getElementById('changeEmailPassword').value = '';
document.getElementById('changeNewEmail').value = ''; document.getElementById('changeNewEmail').value = '';
currentUser.email = newEmail; currentUser.email = newEmail;
statusEl.textContent = '✅ 邮箱修改成功!'; statusEl.textContent = getIcon('success') + ' 邮箱修改成功!';
statusEl.style.color = '#22c55e'; statusEl.style.color = '#22c55e';
} catch (err) { } catch (err) {
statusEl.textContent = '❌ ' + err.message; statusEl.textContent = getIcon('error') + ' ' + err.message;
statusEl.style.color = '#ef4444'; statusEl.style.color = '#ef4444';
} }
}); });
}
else if (tab === 'recovery') {
container.innerHTML = `
<h3 style="margin-bottom:16px;text-align:center;">${getIcon('key')} 恢复码</h3>
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;">
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:12px;">用于忘记密码时重置账户。每个恢复码只能使用一次。</p>
<div style="display:flex;gap:8px;flex-wrap:wrap;">
<button id="viewRecoveryCodesBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">${getIcon('list')} 查看恢复码</button>
<button id="regenerateRecoveryCodesBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">${getIcon('refresh')} 重新生成</button>
</div>
<div id="recoveryCodesStatus" style="font-size:13px;color:var(--text-light);margin-top:8px;">剩余 ${recoveryCount} 个可用恢复码</div>
</div>
`;
// ===== 恢复码管理 ===== // ===== 恢复码管理 =====
const viewBtn = document.getElementById('viewRecoveryCodesBtn'); const viewBtn = document.getElementById('viewRecoveryCodesBtn');
@@ -781,12 +890,26 @@ async function renderSettingsPage() {
} }
}); });
} }
}
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
} }
} }
// ============================================================
// 设置页面侧边栏切换
// ============================================================
document.querySelector('.settings-nav')?.addEventListener('click', function(e) {
const tabLink = e.target.closest('.settings-nav-item');
if (!tabLink) return;
e.preventDefault();
const tab = tabLink.dataset.settingsTab;
if (!tab) return;
renderSettingsPage(tab);
});
// ============================================================ // ============================================================
// ✏️ 编辑帖子模态框 // ✏️ 编辑帖子模态框
// ============================================================ // ============================================================
@@ -798,9 +921,9 @@ function openEditModal(postId, currentTitle, currentContent) {
modal.innerHTML = ` modal.innerHTML = `
<div class="modal-content" style="max-width:600px;"> <div class="modal-content" style="max-width:600px;">
<span class="close" style="position:absolute;top:12px;right:16px;font-size:24px;cursor:pointer;color:var(--text-light);">&times;</span> <span class="close" style="position:absolute;top:12px;right:16px;font-size:24px;cursor:pointer;color:var(--text-light);">&times;</span>
<h2 style="margin-bottom:16px;">✏️ 编辑帖子</h2> <h2 style="margin-bottom:16px;">${getIcon('edit')} 编辑帖子</h2>
<input type="text" id="editPostTitle" value="${currentTitle || ''}" placeholder="标题" style="width:100%;padding:10px 14px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-weight:600;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" /> <input type="text" id="editPostTitle" value="${escapeHTML(currentTitle || '')}" placeholder="标题" style="width:100%;padding:10px 14px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-weight:600;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" />
<textarea id="editPostContent" rows="6" style="width:100%;padding:12px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-family:inherit;resize:vertical;background:var(--bg);color:var(--text);">${currentContent || ''}</textarea> <textarea id="editPostContent" rows="6" style="width:100%;padding:12px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-family:inherit;resize:vertical;background:var(--bg);color:var(--text);">${escapeHTML(currentContent || '')}</textarea>
<button id="editPostSaveBtn" class="btn-primary" style="padding:10px 24px;margin-top:12px;width:100%;">保存修改</button> <button id="editPostSaveBtn" class="btn-primary" style="padding:10px 24px;margin-top:12px;width:100%;">保存修改</button>
</div> </div>
`; `;
@@ -860,14 +983,14 @@ function showRecoveryCodesModal(codes) {
modal.innerHTML = ` modal.innerHTML = `
<div class="modal-content" style="max-width:480px;"> <div class="modal-content" style="max-width:480px;">
<h2 style="margin-bottom:8px;">🔑 恢复码</h2> <h2 style="margin-bottom:8px;">${getIcon('key')} 恢复码</h2>
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;"> <p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">
请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。 请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。
<strong style="color:#ef4444;">每个恢复码只能使用一次。</strong> <strong style="color:#ef4444;">每个恢复码只能使用一次。</strong>
</p> </p>
<div style="margin-bottom:16px;">${codesHtml}</div> <div style="margin-bottom:16px;">${codesHtml}</div>
<div style="display:flex;gap:8px;flex-wrap:wrap;"> <div style="display:flex;gap:8px;flex-wrap:wrap;">
<button id="copyRecoveryCodesBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">📋 复制全部</button> <button id="copyRecoveryCodesBtn" class="btn-secondary" style="padding:8px 16px;border:1px solid var(--border);border-radius:4px;background:var(--surface);cursor:pointer;color:var(--text);">${getIcon('list')} 复制全部</button>
<button id="closeRecoveryCodesBtn" class="btn-primary" style="padding:8px 16px;">我已保存</button> <button id="closeRecoveryCodesBtn" class="btn-primary" style="padding:8px 16px;">我已保存</button>
</div> </div>
<div id="copyStatus" style="font-size:13px;margin-top:8px;color:var(--text-light);"></div> <div id="copyStatus" style="font-size:13px;margin-top:8px;color:var(--text-light);"></div>
@@ -884,7 +1007,7 @@ function showRecoveryCodesModal(codes) {
document.getElementById('copyRecoveryCodesBtn').addEventListener('click', function() { document.getElementById('copyRecoveryCodesBtn').addEventListener('click', function() {
const text = codes.join('\n'); const text = codes.join('\n');
navigator.clipboard.writeText(text).then(() => { navigator.clipboard.writeText(text).then(() => {
document.getElementById('copyStatus').textContent = '✅ 已复制到剪贴板'; document.getElementById('copyStatus').textContent = getIcon('success') + ' 已复制到剪贴板';
}).catch(() => { }).catch(() => {
const textarea = document.createElement('textarea'); const textarea = document.createElement('textarea');
textarea.value = text; textarea.value = text;
@@ -892,7 +1015,7 @@ function showRecoveryCodesModal(codes) {
textarea.select(); textarea.select();
document.execCommand('copy'); document.execCommand('copy');
textarea.remove(); textarea.remove();
document.getElementById('copyStatus').textContent = '✅ 已复制到剪贴板'; document.getElementById('copyStatus').textContent = getIcon('success') + ' 已复制到剪贴板';
}); });
}); });
@@ -901,6 +1024,57 @@ function showRecoveryCodesModal(codes) {
}); });
} }
// ============================================================
// 🖼️ 图片查看器
// ============================================================
function openImageViewer(imageUrl) {
const existing = document.getElementById('imageViewerModal');
if (existing) existing.remove();
const modal = document.createElement('div');
modal.id = 'imageViewerModal';
modal.style.cssText = `
position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:9999;
display:flex;align-items:center;justify-content:center;
cursor:pointer;animation:fadeIn 0.2s ease-out;
`;
const img = document.createElement('img');
img.src = imageUrl;
img.style.cssText = `
max-width:90vw;max-height:90vh;object-fit:contain;
border-radius:8px;box-shadow:0 8px 32px rgba(0,0,0,0.5);
cursor:default;user-select:none;
`;
modal.addEventListener('click', function(e) {
if (e.target === this) {
this.remove();
}
});
modal.addEventListener('keydown', function(e) {
if (e.key === 'Escape') this.remove();
});
modal.appendChild(img);
document.body.appendChild(modal);
modal.focus();
}
// 添加淡入动画
(function() {
const style = document.createElement('style');
style.textContent = `
@keyframes fadeIn {
from { opacity: 0; transform: scale(0.95); }
to { opacity: 1; transform: scale(1); }
}
`;
document.head.appendChild(style);
})();
// ============================================================ // ============================================================
// 🚀 初始化 // 🚀 初始化
// ============================================================ // ============================================================
@@ -917,7 +1091,7 @@ async function init() {
try { try {
const user = await API.getMe(); const user = await API.getMe();
currentUser = user; currentUser = user;
API.logEvent('login').catch(() => {});
} catch (e) { } catch (e) {
token = null; token = null;
localStorage.removeItem('forumlify-token'); localStorage.removeItem('forumlify-token');
@@ -1030,7 +1204,7 @@ async function init() {
try { try {
await API.resetPassword(email, code, newPassword); await API.resetPassword(email, code, newPassword);
statusEl.textContent = '✅ 重置成功!请登录'; statusEl.textContent = getIcon('success') + ' 重置成功!请登录';
statusEl.style.color = '#22c55e'; statusEl.style.color = '#22c55e';
setTimeout(() => { setTimeout(() => {
document.getElementById('forgotPasswordModal').classList.remove('active'); document.getElementById('forgotPasswordModal').classList.remove('active');
@@ -1039,7 +1213,7 @@ async function init() {
document.getElementById('resetNewPassword').value = ''; document.getElementById('resetNewPassword').value = '';
}, 1500); }, 1500);
} catch (err) { } catch (err) {
statusEl.textContent = '❌ ' + err.message; statusEl.textContent = getIcon('error') + ' ' + err.message;
statusEl.style.color = '#ef4444'; statusEl.style.color = '#ef4444';
} }
}); });
@@ -1068,7 +1242,7 @@ async function init() {
}); });
try { try {
await API.createPost(title, content, images); await API.createPost(title, content, images);
API.logEvent('create_post').catch(() => {});
alert('发布成功!'); alert('发布成功!');
switchPage('feed'); switchPage('feed');
renderFeed(); renderFeed();
+20 -30
View File
@@ -1,15 +1,3 @@
// ============================================================
// AUTH 对象(供其他模块使用)
// ============================================================
const AUTH = {
async getUserProfile(userId) {
const data = await apiFetch('/users/' + userId);
if (data.error) throw new Error(data.error);
return data;
}
};
// ============================================================ // ============================================================
// 🔐 认证 // 🔐 认证
// ============================================================ // ============================================================
@@ -30,7 +18,6 @@ document.getElementById('loginSubmit').addEventListener('click', async () => {
document.getElementById('loginPassword').value = ''; document.getElementById('loginPassword').value = '';
if (result.user) { if (result.user) {
currentUser = result.user; currentUser = result.user;
API.logEvent('login').catch(() => {});
renderNav(); renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') { if (currentPage === 'admin' && currentUser.role !== 'admin') {
switchPage('feed'); switchPage('feed');
@@ -60,39 +47,42 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
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 {
const result = await API.register(email, password, username); await API.register(email, password, username);
} catch (err) {
alert('注册失败:' + err.message);
return;
}
document.getElementById('registerModal').classList.remove('active'); document.getElementById('registerModal').classList.remove('active');
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('regCaptchaInput').value = ''; document.getElementById('regCaptchaInput').value = '';
alert('注册成功!请登录');
// 生成恢复码
try { try {
const recoveryData = await API.generateRecoveryCodes(); await API.login(email, password);
if (recoveryData.codes) { currentUser = await API.getMe();
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(); renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') { if (currentPage === 'admin' && currentUser.role !== 'admin') {
switchPage('feed'); switchPage('feed');
} else if (currentPage === 'feed') { } else if (currentPage === 'feed') {
renderFeed(); renderFeed();
renderStats(); renderStats();
} }
} catch (err) {
alert('注册成功,但自动登录失败,请手动登录:' + err.message);
return;
}
try {
const recoveryData = await API.generateRecoveryCodes();
if (recoveryData.codes?.length) {
showRecoveryCodesModal(recoveryData.codes);
} }
} catch (err) { } catch (err) {
alert('注册失败:' + err.message); console.warn('恢复码生成失败:', err);
alert('注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。');
} }
}); });
+37 -11
View File
@@ -38,24 +38,35 @@ function renderFeed() {
if (p.images && p.images.length > 0) { if (p.images && p.images.length > 0) {
imagesHtml = '<div class="post-images">'; imagesHtml = '<div class="post-images">';
p.images.forEach(img => { p.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" />'; imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) + '" class="post-image" style="cursor:pointer;" />';
}); });
imagesHtml += '</div>'; imagesHtml += '</div>';
} }
const replyCount = p.reply_count || 0; const replyCount = p.reply_count || 0;
// Markdown 渲染 const renderedContent = renderMarkdown(p.content || '');
const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, '<br>');
// 签名渲染
let signatureHtml = '';
if (p.signature) {
const sigContent = renderMarkdown(p.signature);
signatureHtml = `
<div style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
${sigContent}
</div>
`;
}
html += ` html += `
<div class="post-card" data-postid="${p.id}" style="cursor:pointer;"> <div class="post-card" data-postid="${p.id}" style="cursor:pointer;">
${p.is_pinned ? '<div style="font-size:12px;color:var(--primary);font-weight:600;margin-bottom:4px;">📌 置顶</div>' : ''}
<div class="post-header"> <div class="post-header">
<img src="${avatar}" class="post-avatar" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="event.stopPropagation();switchPage('user','${username}')">${username}</span> <span class="post-username" data-username="${escapeHTML(username)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(username)}</span>
<span class="post-time">${time}</span> <span class="post-time">${time}</span>
${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''} ${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''}
</div> </div>
<div class="post-title">${p.title || '无标题'}</div> <div class="post-title">${escapeHTML(p.title || '无标题')}</div>
<div class="post-content">${renderedContent}</div> <div class="post-content">${renderedContent}</div>
${imagesHtml} ${imagesHtml}
<div class="post-actions"> <div class="post-actions">
@@ -72,10 +83,11 @@ function renderFeed() {
删除 删除
</button>` : ''} </button>` : ''}
</div> </div>
${signatureHtml}
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
// 分页控件 // 分页控件
if (totalPages > 1) { if (totalPages > 1) {
@@ -155,6 +167,20 @@ function renderFeed() {
}); });
}); });
container.querySelectorAll('.post-username').forEach(username => {
username.addEventListener('click', function(e) {
e.stopPropagation();
switchPage('user', this.dataset.username);
});
});
container.querySelectorAll('.post-image').forEach(image => {
image.addEventListener('click', function(e) {
e.stopPropagation();
openImageViewer(this.src);
});
});
container.querySelectorAll('.action-report').forEach(btn => { container.querySelectorAll('.action-report').forEach(btn => {
btn.addEventListener('click', function(e) { btn.addEventListener('click', function(e) {
e.stopPropagation(); e.stopPropagation();
@@ -175,7 +201,7 @@ function renderFeed() {
}); });
}); });
}).catch(err => { }).catch(err => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
'</div>'; '</div>';
}); });
} }
@@ -185,7 +211,7 @@ function renderStats() {
document.getElementById('statTopics').textContent = stats.topics || 0; document.getElementById('statTopics').textContent = stats.topics || 0;
document.getElementById('statPosts').textContent = stats.posts || 0; document.getElementById('statPosts').textContent = stats.posts || 0;
document.getElementById('statUsers').textContent = stats.users || 0; document.getElementById('statUsers').textContent = stats.users || 0;
document.getElementById('statOnline').textContent = stats.online || 0; // 在线人数已移除
}).catch(() => {}); }).catch(() => {});
} }
@@ -198,9 +224,9 @@ function renderLinks() {
} }
let html = ''; let html = '';
links.forEach(l => { links.forEach(l => {
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>'; html += '<li><a href="' + escapeHTML(safeURL(l.url, { allowRelative: false })) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(l.title) + '</a></li>';
}); });
ul.innerHTML = html; ul.innerHTML = sanitizeHTML(html);
}).catch(() => {}); }).catch(() => {});
} }
+655
View File
@@ -0,0 +1,655 @@
// ============================================================
// 🌍 国际化外挂脚本(不修改任何源文件)
// 默认英文,支持 URL 参数 ?lang=zh / ?lang=en
// ============================================================
const TRANSLATIONS = {
'zh': {
// ===== 导航 =====
'登录': '登录',
'注册': '注册',
'消息': '消息',
'设置': '设置',
'管理后台': '管理后台',
'暗色模式': '暗色模式',
'亮色模式': '亮色模式',
'退出': '退出',
'暂无链接': '暂无链接',
'举报': '举报',
'用户': '用户',
'日志': '日志',
'友链': '友链',
'自定义 CSS': '自定义 CSS',
'论坛设置': '论坛设置',
'自定义页面': '自定义页面',
'✉️ 私信': '✉️ 私信',
// ===== 帖子 =====
'最新发布': '最新发布',
'最新回复': '最新回复',
'发布新帖': '发布新帖',
'标题': '标题',
'说点什么...': '说点什么...',
'发布帖子': '发布帖子',
'加载中...': '加载中...',
'还没有帖子,快来发布第一条吧!': '还没有帖子,快来发布第一条吧!',
'暂无帖子': '暂无帖子',
'删除': '删除',
'编辑': '编辑',
'置顶': '置顶',
'取消置顶': '取消置顶',
'已编辑': '已编辑',
'匿名': '匿名',
'无标题': '无标题',
'回复': '回复',
'📌 置顶': '📌 置顶',
'✏️ 编辑': '✏️ 编辑',
// ===== 帖子详情 =====
'帖子详情': '帖子详情',
'发表回复': '发表回复',
'提交回复': '提交回复',
'还没有回复,快来抢沙发吧 🛋️': '还没有回复,快来抢沙发吧 🛋️',
'写下你的回复...': '写下你的回复...',
'条回复': '条回复',
// ===== 统计 =====
'社区统计': '社区统计',
'主题': '主题',
'帖子': '帖子',
'用户': '用户',
'友情链接': '友情链接',
// ===== 登录/注册 =====
'邮箱': '邮箱',
'密码': '密码',
'忘记密码?': '忘记密码?',
'用户名': '用户名',
'密码(至少6位)': '密码(至少6位)',
'请先登录': '请先登录',
// ===== 管理后台 =====
'举报记录': '举报记录',
'用户列表': '用户列表',
'操作日志': '操作日志',
'自定义CSS': '自定义CSS',
'论坛名称设置': '论坛名称设置',
'暂无举报': '暂无举报',
'待处理': '待处理',
'已删除': '已删除',
'已驳回': '已驳回',
'角色': '角色',
'注册时间': '注册时间',
// ===== 设置页面 =====
'个人资料': '个人资料',
'安全设置': '安全设置',
'恢复码': '恢复码',
'保存设置': '保存设置',
'修改密码': '修改密码',
'当前密码': '当前密码',
'新密码': '新密码',
'修改邮箱': '修改邮箱',
'新邮箱': '新邮箱',
'查看恢复码': '查看恢复码',
'重新生成': '重新生成',
'个人简介': '个人简介',
'帖子签名': '帖子签名',
'显示在每篇帖子底部,支持 Markdown': '显示在每篇帖子底部,支持 Markdown',
'用 --- 分隔,支持 Markdown': '用 --- 分隔,支持 Markdown',
'当前密码(验证身份)': '当前密码(验证身份)',
// ===== 恢复码 =====
'用于忘记密码时重置账户。每个恢复码只能使用一次。': '用于忘记密码时重置账户。每个恢复码只能使用一次。',
'请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。': '请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。',
'每个恢复码只能使用一次。': '每个恢复码只能使用一次。',
'剩余 0 个可用恢复码': '剩余 0 个可用恢复码',
'剩余 1 个可用恢复码': '剩余 1 个可用恢复码',
'剩余 2 个可用恢复码': '剩余 2 个可用恢复码',
'剩余 3 个可用恢复码': '剩余 3 个可用恢复码',
'剩余 4 个可用恢复码': '剩余 4 个可用恢复码',
'剩余 5 个可用恢复码': '剩余 5 个可用恢复码',
'剩余 6 个可用恢复码': '剩余 6 个可用恢复码',
'剩余 7 个可用恢复码': '剩余 7 个可用恢复码',
'剩余 8 个可用恢复码': '剩余 8 个可用恢复码',
'剩余 9 个可用恢复码': '剩余 9 个可用恢复码',
'剩余 10 个可用恢复码': '剩余 10 个可用恢复码',
'复制全部': '复制全部',
'我已保存': '我已保存',
// ===== 自定义页面 =====
'添加页面': '添加页面',
'页面名称': '页面名称',
'导航栏显示名称': '导航栏显示名称',
'关于我们': '关于我们',
'状态': '状态',
'启用': '启用',
'禁用': '禁用',
'页面内容': '页面内容',
'保存': '保存',
'编辑页面': '编辑页面',
'只允许字母、数字、短横线和下划线': '只允许字母、数字、短横线和下划线',
'用于 URL: ?custom=': '用于 URL: ?custom=',
'页面内容(HTML + CSS + JS)': '页面内容(HTML + CSS + JS)',
'支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染': '支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染',
'暂无自定义页面': '暂无自定义页面',
// ===== 自定义 CSS =====
'自定义 CSS': '自定义 CSS',
'上传 style.css 覆盖默认样式,自定义论坛外观。': '上传 style.css 覆盖默认样式,自定义论坛外观。',
'点击或拖拽上传 style.css': '点击或拖拽上传 style.css',
'只能上传 style.css 文件': '只能上传 style.css 文件',
'保存 CSS': '保存 CSS',
'删除自定义 CSS': '删除自定义 CSS',
// ===== 自定义 CSS 警告模态框 =====
'警告': '警告',
'若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。': '若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。',
'请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。': '请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。',
'我了解,继续上传': '我了解,继续上传',
'取消': '取消',
// ===== 友情链接 =====
'链接名称': '链接名称',
'链接地址': '链接地址',
'添加': '添加',
// ===== 通知 =====
'有人回复了你的帖子': '有人回复了你的帖子',
'查看详情 →': '查看详情 →',
'你的帖子已被删除': '你的帖子已被删除',
'你的举报已被处理': '你的举报已被处理',
'你的帖子已被置顶': '你的帖子已被置顶',
'管理员取消了你的帖子置顶': '管理员取消了你的帖子置顶',
'管理员删除了你的帖子': '管理员删除了你的帖子',
'你举报的帖子已被管理员删除': '你举报的帖子已被管理员删除',
'你举报的帖子已被管理员驳回': '你举报的帖子已被管理员驳回',
'管理员把你的帖子置顶了': '管理员把你的帖子置顶了',
// ===== Toast =====
'已复制到剪贴板': '已复制到剪贴板',
// ===== 发帖/上传 =====
'点击或拖拽上传图片': '点击或拖拽上传图片',
'支持 JPG、PNG、GIF、WebP,单张最大 5MB': '支持 JPG、PNG、GIF、WebP,单张最大 5MB',
// ===== 提示 =====
'保存成功!': '保存成功!',
'保存失败': '保存失败',
'操作失败': '操作失败',
'删除成功': '删除成功',
'删除失败': '删除失败',
'确定删除吗?': '确定删除吗?',
'确定要删除该帖子吗?': '确定要删除该帖子吗?',
'举报已提交': '举报已提交',
'修改成功': '修改成功',
'加载失败': '加载失败',
'加载失败:': '加载失败:',
'请填写完整信息': '请填写完整信息',
'请输入页面名称': '请输入页面名称',
'请输入导航栏显示名称': '请输入导航栏显示名称',
'请输入页面内容': '请输入页面内容',
// ===== 举报 =====
'举报了帖子': '举报了帖子',
'原因:': '原因:',
'帖子:': '帖子:',
'状态:': '状态:',
'处理人:': '处理人:',
'删除帖子': '删除帖子',
'驳回举报': '驳回举报',
// ===== 用户 =====
'共': '共',
'位用户': '位用户',
'搜索用户名...': '搜索用户名...',
'搜索': '搜索',
'清空': '清空',
'管理员': '管理员',
'普通用户': '普通用户',
'不可操作自己': '不可操作自己',
'设为普通用户': '设为普通用户',
'设为管理员': '设为管理员',
// ===== 日志 =====
'暂无日志': '暂无日志',
'时间': '时间',
'操作': '操作',
'条日志': '条日志',
// ===== 重置密码 =====
'重置密码': '重置密码',
'输入你的邮箱和一个未使用的恢复码': '输入你的邮箱和一个未使用的恢复码',
'恢复码(格式:ABCD-1234-EFGH-5678)': '恢复码(格式:ABCD-1234-EFGH-5678)',
'新密码(至少6位)': '新密码(至少6位)',
// ===== 用户主页 =====
'用户主页': '用户主页',
'用户不存在': '用户不存在',
'这个人很懒,什么都没写': '这个人很懒,什么都没写',
'加入': '加入',
'于': '于',
'发了': '发了',
'个帖子': '个帖子',
'帖': '帖',
'发私信': '发私信',
'还没有发帖': '还没有发帖',
'加入 ': '加入 ',
// ===== 私信 =====
'私信': '私信',
'暂无私信': '暂无私信',
'还没有消息,打个招呼吧': '还没有消息,打个招呼吧',
'输入消息...': '输入消息...',
'发送': '发送',
// ===== Toast 通用 =====
'请选择图片文件': '请选择图片文件',
'图片不能超过 5MB': '图片不能超过 5MB',
'上传中...': '上传中...',
'头像更新成功!': '头像更新成功!',
'文件名必须是 style.css': '文件名必须是 style.css',
'请上传 CSS 文件': '请上传 CSS 文件',
'已选择: ': '已选择: ',
'请先选择 style.css 文件': '请先选择 style.css 文件',
'CSS 上传成功!刷新页面查看效果': 'CSS 上传成功!刷新页面查看效果',
'上传失败': '上传失败',
'已删除自定义 CSS': '已删除自定义 CSS',
'删除失败': '删除失败',
'密码修改成功!': '密码修改成功!',
'邮箱修改成功!': '邮箱修改成功!',
'重置成功!请登录': '重置成功!请登录',
// ===== 其他 =====
'返回': '返回',
'答案': '答案',
'请填写内容': '请填写内容',
'发布成功!': '发布成功!',
'发布失败': '发布失败',
// ===== 举报原因 =====
'垃圾广告': '垃圾广告',
'人身攻击': '人身攻击',
'违法内容': '违法内容',
'不适当内容': '不适当内容',
'其他': '其他',
'请选择举报原因:': '请选择举报原因:',
'提交举报': '提交举报',
// ===== 论坛名称 =====
'论坛名称': '论坛名称',
},
'en': {
// ===== 导航 =====
'登录': 'Login',
'注册': 'Register',
'消息': 'Messages',
'设置': 'Settings',
'管理后台': 'Admin',
'暗色模式': 'Dark Mode',
'亮色模式': 'Light Mode',
'退出': 'Logout',
'暂无链接': 'No links',
'举报': 'Reports',
'用户': 'Users',
'日志': 'Logs',
'友链': 'Links',
'自定义 CSS': 'Custom CSS',
'论坛设置': 'Forum Settings',
'自定义页面': 'Custom Pages',
'✉️ 私信': '✉️ Messages',
// ===== 帖子 =====
'最新发布': 'Latest',
'最新回复': 'Recent',
'发布新帖': 'New Post',
'标题': 'Title',
'说点什么...': 'Say something...',
'发布帖子': 'Publish',
'加载中...': 'Loading...',
'还没有帖子,快来发布第一条吧!': 'No posts yet. Be the first!',
'暂无帖子': 'No posts',
'删除': 'Delete',
'编辑': 'Edit',
'置顶': 'Pin',
'取消置顶': 'Unpin',
'已编辑': 'Edited',
'匿名': 'Anonymous',
'无标题': 'Untitled',
'回复': 'Reply',
'📌 置顶': '📌 Pinned',
'✏️ 编辑': '✏️ Edit',
// ===== 帖子详情 =====
'帖子详情': 'Post Details',
'发表回复': 'Reply',
'提交回复': 'Submit Reply',
'还没有回复,快来抢沙发吧 🛋️': 'No replies yet. Be the first!',
'写下你的回复...': 'Write your reply...',
'条回复': ' replies',
// ===== 统计 =====
'社区统计': 'Community Stats',
'主题': 'Topics',
'帖子': 'Posts',
'用户': 'Users',
'友情链接': 'Links',
// ===== 登录/注册 =====
'邮箱': 'Email',
'密码': 'Password',
'忘记密码?': 'Forgot Password?',
'用户名': 'Username',
'密码(至少6位)': 'Password (min 6 chars)',
'请先登录': 'Please login first',
// ===== 管理后台 =====
'举报记录': 'Reports',
'用户列表': 'Users',
'操作日志': 'Logs',
'自定义CSS': 'Custom CSS',
'论坛名称设置': 'Forum Settings',
'暂无举报': 'No reports',
'待处理': 'Pending',
'已删除': 'Approved',
'已驳回': 'Rejected',
'角色': 'Role',
'注册时间': 'Registered',
// ===== 设置页面 =====
'个人资料': 'Profile',
'安全设置': 'Security',
'恢复码': 'Recovery Codes',
'保存设置': 'Save Settings',
'修改密码': 'Change Password',
'当前密码': 'Current Password',
'新密码': 'New Password',
'修改邮箱': 'Change Email',
'新邮箱': 'New Email',
'查看恢复码': 'View Recovery Codes',
'重新生成': 'Regenerate',
'个人简介': 'Bio',
'帖子签名': 'Post Signature',
'显示在每篇帖子底部,支持 Markdown': 'Displayed at the bottom of each post. Supports Markdown.',
'用 --- 分隔,支持 Markdown': 'Use --- as separator. Supports Markdown.',
'当前密码(验证身份)': 'Current password (verify identity)',
// ===== 恢复码 =====
'用于忘记密码时重置账户。每个恢复码只能使用一次。': 'Used to reset your password if you forget it. Each recovery code can only be used once.',
'请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。': 'Please save these recovery codes. You can use them to reset your password if you forget it.',
'每个恢复码只能使用一次。': 'Each recovery code can only be used once.',
'剩余 0 个可用恢复码': '0 recovery codes available',
'剩余 1 个可用恢复码': '1 recovery code available',
'剩余 2 个可用恢复码': '2 recovery codes available',
'剩余 3 个可用恢复码': '3 recovery codes available',
'剩余 4 个可用恢复码': '4 recovery codes available',
'剩余 5 个可用恢复码': '5 recovery codes available',
'剩余 6 个可用恢复码': '6 recovery codes available',
'剩余 7 个可用恢复码': '7 recovery codes available',
'剩余 8 个可用恢复码': '8 recovery codes available',
'剩余 9 个可用恢复码': '9 recovery codes available',
'剩余 10 个可用恢复码': '10 recovery codes available',
'复制全部': 'Copy All',
'我已保存': 'Saved',
// ===== 自定义页面 =====
'添加页面': 'Add Page',
'页面名称': 'Page Name',
'导航栏显示名称': 'Display Name',
'关于我们': 'About Us',
'状态': 'Status',
'启用': 'Enabled',
'禁用': 'Disabled',
'页面内容': 'Page Content',
'保存': 'Save',
'编辑页面': 'Edit Page',
'只允许字母、数字、短横线和下划线': 'Only letters, numbers, hyphens and underscores allowed',
'用于 URL: ?custom=': 'Used in URL: ?custom=',
'页面内容(HTML + CSS + JS)': 'Page Content (HTML + CSS + JS)',
'支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染': 'Supports HTML, CSS (<style>), JS (<script>). Rendered in an isolated sandbox.',
'暂无自定义页面': 'No custom pages',
// ===== 自定义 CSS =====
'自定义 CSS': 'Custom CSS',
'上传 style.css 覆盖默认样式,自定义论坛外观。': 'Upload style.css to override default styles and customize the forum appearance.',
'点击或拖拽上传 style.css': 'Click or drag to upload style.css',
'只能上传 style.css 文件': 'Only style.css files are allowed',
'保存 CSS': 'Save CSS',
'删除自定义 CSS': 'Delete Custom CSS',
// ===== 自定义 CSS 警告模态框 =====
'警告': 'Warning',
'若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。': 'If the uploaded style.css has issues, it may break the entire forum layout.',
'请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。': 'Please ensure the CSS file is complete and tested. If problems occur, click "Delete Custom CSS" to restore default styles.',
'我了解,继续上传': 'I understand, continue upload',
'取消': 'Cancel',
// ===== 友情链接 =====
'链接名称': 'Link Name',
'链接地址': 'Link URL',
'添加': 'Add',
// ===== 通知 =====
'有人回复了你的帖子': 'Someone replied to your post',
'查看详情 →': 'View details →',
'你的帖子已被删除': 'Your post has been deleted',
'你的举报已被处理': 'Your report has been processed',
'你的帖子已被置顶': 'Your post has been pinned',
'管理员取消了你的帖子置顶': 'An admin has unpinned your post',
'管理员删除了你的帖子': 'An admin deleted your post',
'你举报的帖子已被管理员删除': 'The post you reported has been deleted',
'你举报的帖子已被管理员驳回': 'The post you reported has been rejected',
'管理员把你的帖子置顶了': 'An admin pinned your post',
// ===== Toast =====
'已复制到剪贴板': 'Copied to clipboard',
// ===== 发帖/上传 =====
'点击或拖拽上传图片': 'Click or drag to upload image',
'支持 JPG、PNG、GIF、WebP,单张最大 5MB': 'Supports JPG, PNG, GIF, WebP, max 5MB',
// ===== 提示 =====
'保存成功!': 'Saved!',
'保存失败': 'Save failed',
'操作失败': 'Operation failed',
'删除成功': 'Deleted',
'删除失败': 'Delete failed',
'确定删除吗?': 'Are you sure?',
'确定要删除该帖子吗?': 'Delete this post?',
'举报已提交': 'Report submitted',
'修改成功': 'Updated',
'加载失败': 'Load failed',
'加载失败:': 'Load failed: ',
'请填写完整信息': 'Please fill in all fields',
'请输入页面名称': 'Please enter a page name',
'请输入导航栏显示名称': 'Please enter a display name',
'请输入页面内容': 'Please enter page content',
// ===== 举报 =====
'举报了帖子': 'reported a post',
'原因:': 'Reason: ',
'帖子:': 'Post: ',
'状态:': 'Status: ',
'处理人:': 'Handler: ',
'删除帖子': 'Delete Post',
'驳回举报': 'Reject',
// ===== 用户 =====
'共': 'Total',
'位用户': ' users',
'搜索用户名...': 'Search username...',
'搜索': 'Search',
'清空': 'Clear',
'管理员': 'Admin',
'普通用户': 'User',
'不可操作自己': 'Cannot modify yourself',
'设为普通用户': 'Set as User',
'设为管理员': 'Set as Admin',
// ===== 日志 =====
'暂无日志': 'No logs',
'时间': 'Time',
'操作': 'Action',
'条日志': ' logs',
// ===== 重置密码 =====
'重置密码': 'Reset Password',
'输入你的邮箱和一个未使用的恢复码': 'Enter your email and an unused recovery code',
'恢复码(格式:ABCD-1234-EFGH-5678)': 'Recovery code (format: ABCD-1234-EFGH-5678)',
'新密码(至少6位)': 'New password (min 6 chars)',
// ===== 用户主页 =====
'用户主页': 'User Profile',
'用户不存在': 'User not found',
'这个人很懒,什么都没写': 'This user is lazy, nothing written',
'加入': 'Joined',
'于': '',
'发了': 'Posted',
'个帖子': ' posts',
'帖': ' posts',
'发私信': 'Send Message',
'还没有发帖': 'No posts yet',
'加入 ': 'Joined ',
// ===== 私信 =====
'私信': 'Messages',
'暂无私信': 'No messages',
'还没有消息,打个招呼吧': 'No messages yet. Say hi!',
'输入消息...': 'Type a message...',
'发送': 'Send',
// ===== Toast 通用 =====
'请选择图片文件': 'Please select an image',
'图片不能超过 5MB': 'Image must be under 5MB',
'上传中...': 'Uploading...',
'头像更新成功!': 'Avatar updated!',
'文件名必须是 style.css': 'File name must be style.css',
'请上传 CSS 文件': 'Please upload a CSS file',
'已选择: ': 'Selected: ',
'请先选择 style.css 文件': 'Please select style.css first',
'CSS 上传成功!刷新页面查看效果': 'CSS uploaded! Refresh to see changes',
'上传失败': 'Upload failed',
'已删除自定义 CSS': 'Custom CSS deleted',
'删除失败': 'Delete failed',
'密码修改成功!': 'Password updated!',
'邮箱修改成功!': 'Email updated!',
'重置成功!请登录': 'Reset successful! Please login',
// ===== 其他 =====
'返回': 'Back',
'答案': 'Answer',
'请填写内容': 'Please enter content',
'发布成功!': 'Posted!',
'发布失败': 'Post failed',
// ===== 举报原因 =====
'垃圾广告': 'Spam',
'人身攻击': 'Abuse',
'违法内容': 'Illegal',
'不适当内容': 'NSFW',
'其他': 'Other',
'请选择举报原因:': 'Select a reason:',
'提交举报': 'Submit Report',
// ===== 论坛名称 =====
'论坛名称': 'Forum Name',
}
};
// ============================================================
// 核心逻辑
// ============================================================
function detectLanguage() {
// URL 参数优先
const urlParams = new URLSearchParams(window.location.search);
const langParam = urlParams.get('lang');
if (langParam && TRANSLATIONS[langParam]) return langParam;
const stored = localStorage.getItem('forumlify-lang');
if (stored && TRANSLATIONS[stored]) return stored;
const browserLang = navigator.language.slice(0, 2);
if (TRANSLATIONS[browserLang]) return browserLang;
return 'en';
}
let currentLang = detectLanguage();
function setLanguage(lang) {
if (!TRANSLATIONS[lang]) return;
currentLang = lang;
localStorage.setItem('forumlify-lang', lang);
applyTranslation();
}
function t(key) {
const dict = TRANSLATIONS[currentLang] || TRANSLATIONS['zh'];
return dict[key] || key;
}
function applyTranslation() {
function walk(node) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent;
const trimmed = text.trim();
if (trimmed && TRANSLATIONS['zh'][trimmed]) {
const translated = t(trimmed);
if (translated !== trimmed) {
node.textContent = text.replace(trimmed, translated);
}
}
return;
}
if (node.nodeType === Node.ELEMENT_NODE) {
if (['IFRAME', 'SCRIPT', 'STYLE'].includes(node.tagName)) return;
if (node.placeholder && TRANSLATIONS['zh'][node.placeholder]) {
node.placeholder = t(node.placeholder);
}
if (node.tagName === 'INPUT' && node.value && TRANSLATIONS['zh'][node.value]) {
if (node.type !== 'password') {
node.value = t(node.value);
}
}
for (const child of node.childNodes) {
walk(child);
}
}
}
walk(document.body);
// 监听动态内容
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
walk(node);
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
// ============================================================
// 初始化
// ============================================================
document.addEventListener('DOMContentLoaded', function() {
document.body.style.opacity = '0';
setTimeout(function() {
if (typeof loadForumName === 'function') {
loadForumName();
}
applyTranslation();
document.body.style.transition = 'opacity 0.2s ease';
document.body.style.opacity = '1';
}, 200);
});
+47
View File
@@ -0,0 +1,47 @@
// ============================================================
// 🎨 图标工具 - 用 SVG 替代 Emoji
// ============================================================
function getIcon(type, size = 16) {
const icons = {
// 通用
success: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>`,
error: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>`,
warning: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/></svg>`,
pending: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`,
// 操作
delete: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><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>`,
edit: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,
add: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
close: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
// 导航
home: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>`,
user: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>`,
lock: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`,
key: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>`,
message: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
// 内容
pin: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8.5"/><polyline points="16 2 22 8 16 8"/><line x1="10" y1="14" x2="18" y2="14"/><line x1="10" y1="18" x2="14" y2="18"/></svg>`,
link: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
settings: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
page: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
shield: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
// 其他
camera: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,
star: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>`,
paint: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><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>`,
calendar: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>`,
file: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>`,
refresh: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>`,
list: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>`,
megaphone: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M17 18.5c0 1.5-1.5 3-3.5 3s-3.5-1.5-3.5-3c0-.5.5-1 1-1h5c.5 0 1 .5 1 1z"/><path d="M4 11h16v6H4z"/><path d="M8 17v3"/><path d="M16 17v3"/><path d="M9 11v-4a3 3 0 0 1 6 0v4"/></svg>`,
sofa: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="10" width="18" height="8" rx="2"/><path d="M6 10V6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v4"/><line x1="3" y1="18" x2="3" y2="20"/><line x1="21" y1="18" x2="21" y2="20"/></svg>`,
clock: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`
};
return icons[type] || '';
}
-1
View File
@@ -1 +0,0 @@
+53 -20
View File
@@ -49,31 +49,38 @@ async function renderPostDetail(postId) {
if (post.images && post.images.length > 0) { if (post.images && post.images.length > 0) {
imagesHtml = '<div class="post-images">'; imagesHtml = '<div class="post-images">';
post.images.forEach(img => { post.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" />'; imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) + '" class="post-image" style="cursor:pointer;" />';
}); });
imagesHtml += '</div>'; imagesHtml += '</div>';
} }
// Markdown 渲染(安全处理) const renderedContent = renderMarkdown(post.content || '');
let renderedContent = post.content || '';
try { // 签名渲染
if (typeof marked !== 'undefined' && marked.parse) { let signatureHtml = '';
renderedContent = marked.parse(renderedContent); if (post.signature) {
} else { const sigContent = renderMarkdown(post.signature);
renderedContent = renderedContent.replace(/\n/g, '<br>'); signatureHtml = `
} <div style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
} catch (e) { ${sigContent}
renderedContent = renderedContent.replace(/\n/g, '<br>'); </div>
`;
} }
let html = ` let html = `
<div class="post-detail-card"> <div class="post-detail-card">
<div class="post-header"> <div class="post-header">
<img src="${avatar}" class="post-avatar" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${username}')">${username}</span> <span class="post-username" data-username="${escapeHTML(username)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(username)}</span>
<span class="post-time">${time}</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>` : ''} ${post.edited_at ? `<span style="font-size:12px;color:var(--text-light);margin-left:8px;">(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})</span>` : ''}
${post.is_pinned ? '<span style="font-size:12px;color:var(--primary);margin-left:8px;">📌 置顶</span>' : ''}
<div style="display:flex;gap:4px;margin-left:auto;"> <div style="display:flex;gap:4px;margin-left:auto;">
${currentUser && currentUser.role === 'admin' ? `
<button class="btn-sm btn-secondary" id="pinPostBtn" data-postid="${post.id}" style="padding:4px 10px;">
${post.is_pinned ? '📌 取消置顶' : '📌 置顶'}
</button>
` : ''}
${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-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;"> ${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> <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>
@@ -83,6 +90,7 @@ async function renderPostDetail(postId) {
</div> </div>
<div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div> <div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div>
${imagesHtml} ${imagesHtml}
${signatureHtml}
</div> </div>
<div style="margin-top:20px;font-size:14px;color:#64748b;"> <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> <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>
@@ -103,28 +111,53 @@ async function renderPostDetail(postId) {
html += ` html += `
<div class="reply-item" data-replyid="${r.id}"> <div class="reply-item" data-replyid="${r.id}">
<div class="reply-header"> <div class="reply-header">
<img src="${rAvatar}" class="reply-avatar" /> <img src="${escapeHTML(safeURL(rAvatar, { image: true }))}" class="reply-avatar" />
<span class="reply-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${rUsername}')">${rUsername}</span> <span class="reply-username" data-username="${escapeHTML(rUsername)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(rUsername)}</span>
<span class="reply-time">${rTime}</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}"> ${currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') ? `<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> <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>` : ''}
</div> </div>
<div class="reply-content">${(r.content || '').replace(/\n/g, '<br>')}</div> <div class="reply-content">${renderPlainText(r.content || '')}</div>
</div> </div>
`; `;
}); });
} }
html += '</div>'; html += '</div>';
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
replyArea.style.display = 'block'; replyArea.style.display = 'block';
document.getElementById('replyContent').value = ''; document.getElementById('replyContent').value = '';
document.getElementById('replyCaptchaInput').value = ''; document.getElementById('replyCaptchaInput').value = '';
refreshCaptcha('reply'); refreshCaptcha('reply');
container.querySelectorAll('.post-username, .reply-username').forEach(usernameEl => {
usernameEl.addEventListener('click', function() {
switchPage('user', this.dataset.username);
});
});
container.querySelectorAll('.post-image').forEach(image => {
image.addEventListener('click', function() {
openImageViewer(this.src);
});
});
// 置顶按钮
const pinBtn = document.getElementById('pinPostBtn');
if (pinBtn) {
pinBtn.addEventListener('click', function() {
const postId = this.dataset.postid;
if (!confirm('确定要' + (this.textContent.includes('取消') ? '取消' : '') + '置顶吗?')) return;
API.togglePinPost(postId).then(() => {
renderPostDetail(postId);
renderFeed();
}).catch(err => alert('操作失败:' + err.message));
});
}
// 编辑按钮 // 编辑按钮
const editBtn = document.getElementById('editPostBtn'); const editBtn = document.getElementById('editPostBtn');
if (editBtn) { if (editBtn) {
@@ -180,7 +213,7 @@ async function renderPostDetail(postId) {
currentPostId = postId; currentPostId = postId;
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
'</div>'; '</div>';
replyArea.style.display = 'none'; replyArea.style.display = 'none';
} }
@@ -195,7 +228,7 @@ async function handleReplySubmit(postId) {
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; } if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; }
try { try {
await API.createReply(postId, content); await API.createReply(postId, content);
API.logEvent('create_reply').catch(() => {});
renderPostDetail(postId); renderPostDetail(postId);
if (currentPage === 'feed') { if (currentPage === 'feed') {
renderFeed(); renderFeed();
+77
View File
@@ -0,0 +1,77 @@
// ============================================================
// Safe rendering helpers
// ============================================================
function escapeHTML(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function safeURL(value, { allowRelative = true, image = false } = {}) {
if (!value) return image ? '' : '#';
try {
const raw = String(value).trim();
const parsed = new URL(raw, window.location.origin);
const isRelative = parsed.origin === window.location.origin && !/^[a-z][a-z0-9+.-]*:/i.test(raw);
const allowedProtocol = parsed.protocol === 'http:' || parsed.protocol === 'https:';
if (!allowedProtocol || (!allowRelative && isRelative)) return image ? '' : '#';
return isRelative ? parsed.pathname + parsed.search + parsed.hash : parsed.href;
} catch (error) {
return image ? '' : '#';
}
}
function sanitizeHTML(html) {
const template = document.createElement('template');
template.innerHTML = String(html ?? '');
// Application templates contain legitimate controls. Raw user HTML is escaped
// before Markdown parsing, while this pass removes executable/embed elements.
const forbidden = 'script,iframe,object,embed,link,meta,base,style';
template.content.querySelectorAll(forbidden).forEach(node => node.remove());
template.content.querySelectorAll('*').forEach(node => {
for (const attribute of Array.from(node.attributes)) {
const name = attribute.name.toLowerCase();
if (name.startsWith('on') || name === 'srcdoc') {
node.removeAttribute(attribute.name);
}
}
if (node.hasAttribute('href')) {
const href = safeURL(node.getAttribute('href'));
if (href === '#') node.removeAttribute('href');
else node.setAttribute('href', href);
}
if (node.hasAttribute('src')) {
const src = safeURL(node.getAttribute('src'), { image: true });
if (!src) node.removeAttribute('src');
else node.setAttribute('src', src);
}
if (node.tagName === 'A' && node.getAttribute('target') === '_blank') {
node.setAttribute('rel', 'noopener noreferrer');
}
});
return template.innerHTML;
}
function renderMarkdown(value) {
const escaped = escapeHTML(value);
if (typeof marked !== 'undefined' && marked.parse) {
return sanitizeHTML(marked.parse(escaped));
}
return escaped.replace(/\r?\n/g, '<br>');
}
function renderPlainText(value) {
return escapeHTML(value).replace(/\r?\n/g, '<br>');
}
+6 -2
View File
@@ -24,13 +24,17 @@ function updateThemeUI(theme) {
const icon = document.getElementById('themeIcon'); const icon = document.getElementById('themeIcon');
const label = document.getElementById('themeLabel'); const label = document.getElementById('themeLabel');
if (!icon) return; if (!icon) return;
// 确保 t 函数存在,否则用默认文字
const translate = typeof t === 'function' ? t : function(key) { return key; };
if (theme === 'dark') { if (theme === 'dark') {
icon.innerHTML = 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"/>`; `<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 = '☀️ 亮色模式'; if (label) label.textContent = translate('亮色模式');
} else { } else {
icon.innerHTML = `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`; 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 = '🌙 暗色模式'; if (label) label.textContent = translate('暗色模式');
} }
} }
+17 -11
View File
@@ -7,10 +7,10 @@ async function renderUserProfile(username) {
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>'; container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
try { try {
const users = await apiFetch('/users?username=' + encodeURIComponent(username)); // 使用公开接口 /users/profile/:username
const user = users && users.length > 0 ? users[0] : null; const user = await apiFetch('/users/profile/' + encodeURIComponent(username));
if (!user) { if (user.error || !user.id) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">用户不存在</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">用户不存在</div>';
return; return;
} }
@@ -24,9 +24,9 @@ async function renderUserProfile(username) {
let html = ` let html = `
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;"> <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);" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" 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> <h2 style="margin:16px 0 4px;font-size:24px;">${escapeHTML(user.username)}</h2>
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p> <p style="color:var(--text-secondary);font-size:14px;">${escapeHTML(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;"> <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>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 发了 ${posts.length} 个帖子</span> <span>📝 发了 ${posts.length} 个帖子</span>
@@ -48,16 +48,22 @@ async function renderUserProfile(username) {
posts.forEach(p => { posts.forEach(p => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : ''; const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
html += ` html += `
<div class="post-card" style="cursor:pointer;" onclick="switchToPost('${p.id}')"> <div class="post-card" data-postid="${escapeHTML(p.id)}" style="cursor:pointer;">
<div class="post-title" style="font-size:16px;font-weight:600;">${p.title || '无标题'}</div> <div class="post-title" style="font-size:16px;font-weight:600;">${escapeHTML(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 class="post-content" style="font-size:14px;color:var(--text-secondary);">${escapeHTML((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 style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div>
</div> </div>
`; `;
}); });
} }
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('.post-card[data-postid]').forEach(card => {
card.addEventListener('click', function() {
switchToPost(this.dataset.postid);
});
});
const dmBtn = document.getElementById('dmBtn'); const dmBtn = document.getElementById('dmBtn');
if (dmBtn) { if (dmBtn) {
@@ -67,7 +73,7 @@ async function renderUserProfile(username) {
} }
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + '</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) + '</div>';
} }
} }
+314 -617
View File
File diff suppressed because it is too large. Load diff
+13 -3
View File
@@ -3,16 +3,26 @@
"version": "1.0.0", "version": "1.0.0",
"description": "Forumlify - 简洁优雅的现代社区系统", "description": "Forumlify - 简洁优雅的现代社区系统",
"main": "server.js", "main": "server.js",
"engines": {
"node": ">=20"
},
"scripts": { "scripts": {
"start": "node server.js", "start": "node server.js",
"dev": "node server.js" "dev": "node server.js",
"check": "node scripts/check-syntax.js",
"test": "node --test"
}, },
"dependencies": { "dependencies": {
"bcrypt": "^5.1.1", "bcryptjs": "3.0.3",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"express-rate-limit": "8.6.2",
"helmet": "8.1.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1", "multer": "2.2.0",
"pg": "^8.11.3" "pg": "^8.11.3"
},
"devDependencies": {
"supertest": "7.2.2"
} }
} }
+52 -1
View File
@@ -45,7 +45,7 @@ CREATE TABLE IF NOT EXISTS friendly_links (
-- 举报表 -- 举报表
CREATE TABLE IF NOT EXISTS reports ( CREATE TABLE IF NOT EXISTS reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE, post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
reason VARCHAR(100) NOT NULL, reason VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')), status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
@@ -55,15 +55,51 @@ CREATE TABLE IF NOT EXISTS reports (
handler_note TEXT 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 ( CREATE TABLE IF NOT EXISTS event_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE SET NULL, user_id UUID REFERENCES users(id) ON DELETE SET NULL,
action VARCHAR(50) NOT NULL, action VARCHAR(50) NOT NULL,
ip VARCHAR(45), ip VARCHAR(45),
method VARCHAR(10),
path TEXT,
user_agent TEXT,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT now() created_at TIMESTAMPTZ DEFAULT now()
); );
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);
-- ============================================================ -- ============================================================
-- 论坛设置表 -- 论坛设置表
-- ============================================================ -- ============================================================
@@ -167,3 +203,18 @@ CREATE TABLE IF NOT EXISTS recovery_codes (
); );
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id); 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;
+12
View File
@@ -0,0 +1,12 @@
const { execFileSync } = require('node:child_process');
const path = require('node:path');
const files = execFileSync('git', ['ls-files', '*.js'], { encoding: 'utf8' })
.split(/\r?\n/)
.filter(Boolean);
for (const file of files) {
execFileSync(process.execPath, ['--check', path.resolve(file)], { stdio: 'inherit' });
}
console.log(`Syntax check passed for ${files.length} JavaScript files.`);
+394 -64
View File
@@ -5,7 +5,9 @@
const express = require('express'); const express = require('express');
const cors = require('cors'); const cors = require('cors');
const bcrypt = require('bcrypt'); const helmet = require('helmet');
const { rateLimit } = require('express-rate-limit');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { Pool } = require('pg'); const { Pool } = require('pg');
const multer = require('multer'); const multer = require('multer');
@@ -19,7 +21,12 @@ const CONFIG = require('./config');
// 监听端口:环境变量 PORT 优先,其次 config.js 的 SERVER_PORT,最后默认 3000 // 监听端口:环境变量 PORT 优先,其次 config.js 的 SERVER_PORT,最后默认 3000
const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000; const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'forumlify-secret-key-change-me-in-production'; const DEFAULT_JWT_SECRET = 'forumlify-secret-key-change-me-in-production';
const JWT_SECRET = process.env.JWT_SECRET || DEFAULT_JWT_SECRET;
if (process.env.NODE_ENV === 'production' && JWT_SECRET === DEFAULT_JWT_SECRET) {
throw new Error('JWT_SECRET must be set to a unique value in production');
}
// ============================================================ // ============================================================
// 数据库 // 数据库
@@ -31,13 +38,118 @@ const pool = new Pool({
// ============================================================ // ============================================================
// 中间件 // 中间件
// ============================================================ // ============================================================
app.use(cors()); app.disable('x-powered-by');
app.use(express.json()); if (process.env.TRUST_PROXY === 'true') app.set('trust proxy', 1);
app.use(express.urlencoded({ extended: true }));
// The existing UI relies on inline styles/scripts and a CDN-hosted Markdown
// parser, so CSP is left for a dedicated frontend migration.
app.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
}));
const allowedOrigins = (process.env.ALLOWED_ORIGINS || '')
.split(',')
.map(origin => origin.trim())
.filter(Boolean);
if (allowedOrigins.length > 0) {
app.use(cors({
origin(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) return callback(null, true);
return callback(new Error('Origin is not allowed by CORS'));
},
}));
}
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
standardHeaders: 'draft-8',
legacyHeaders: false,
handler: (req, res) => res.status(429).json({ error: '请求过于频繁,请稍后重试' }),
});
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 20,
standardHeaders: 'draft-8',
legacyHeaders: false,
handler: (req, res) => res.status(429).json({ error: '尝试次数过多,请稍后重试' }),
});
app.use('/api', apiLimiter);
app.use(['/api/auth/login', '/api/auth/register', '/api/auth/reset-password'], authLimiter);
app.use(express.json({ limit: '100kb' }));
app.use(express.urlencoded({ extended: true, limit: '100kb' }));
const AUDIT_ACTIONS = new Map([
['POST /api/auth/register', 'register'],
['POST /api/auth/login', 'login'],
['PUT /api/settings', 'update_settings'],
['PUT /api/users/:id/role', 'update_user_role'],
['PUT /api/users/:id', 'update_profile'],
['PUT /api/users/:id/avatar', 'update_avatar'],
['PUT /api/users/:id/password', 'change_password'],
['PUT /api/users/:id/email', 'change_email'],
['POST /api/posts', 'create_post'],
['PUT /api/posts/:id', 'update_post'],
['DELETE /api/posts/:id', 'delete_post'],
['PUT /api/posts/:id/pin', 'toggle_post_pin'],
['POST /api/posts/:id/replies', 'create_reply'],
['DELETE /api/replies/:id', 'delete_reply'],
['POST /api/reports', 'create_report'],
['PUT /api/reports/:id', 'handle_report'],
['POST /api/links', 'create_link'],
['DELETE /api/links/:id', 'delete_link'],
['POST /api/upload', 'upload_image'],
['POST /api/admin/custom-css', 'upload_custom_css'],
['DELETE /api/admin/custom-css', 'delete_custom_css'],
['POST /api/conversations', 'create_conversation'],
['POST /api/conversations/:id/messages', 'send_message'],
['POST /api/admin/custom-pages', 'create_custom_page'],
['PUT /api/admin/custom-pages/:id', 'update_custom_page'],
['DELETE /api/admin/custom-pages/:id', 'delete_custom_page'],
['POST /api/auth/recovery-codes/generate', 'rotate_recovery_codes'],
['POST /api/auth/reset-password', 'reset_password'],
]);
function auditMetadata(req) {
const metadata = {};
for (const [key, value] of Object.entries(req.params || {})) {
if (typeof value === 'string' && value.length <= 100) metadata[key] = value;
}
for (const key of ['post_id', 'other_user_id', 'role', 'status']) {
const value = req.body?.[key];
if (typeof value === 'string' && value.length <= 100) metadata[key] = value;
}
return { ...metadata, ...(req.auditMetadata || {}) };
}
app.use((req, res, next) => {
res.on('finish', () => {
if (res.statusCode < 200 || res.statusCode >= 300 || !req.route?.path) return;
const routePath = Array.isArray(req.route.path) ? req.route.path[0] : req.route.path;
const action = AUDIT_ACTIONS.get(`${req.method} ${routePath}`);
if (!action) return;
const userId = req.auditUserId || req.user?.id || null;
const ip = String(req.ip || req.socket?.remoteAddress || '').slice(0, 45);
const userAgent = String(req.get('user-agent') || '').slice(0, 1000);
pool.query(
`INSERT INTO event_logs (user_id, action, ip, method, path, user_agent, metadata)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)`,
[userId, action, ip, req.method, req.originalUrl.slice(0, 2000), userAgent, JSON.stringify(auditMetadata(req))]
).catch(error => console.error('Failed to write audit log:', error));
});
next();
});
// 确保上传目录存在 // 确保上传目录存在
if (!fs.existsSync('uploads')) fs.mkdirSync('uploads'); if (!fs.existsSync('uploads')) fs.mkdirSync('uploads');
app.use('/uploads', express.static('uploads')); app.use('/uploads', express.static(path.join(__dirname, 'uploads'), {
dotfiles: 'deny',
fallthrough: false,
index: false,
}));
// ============================================================ // ============================================================
// 认证中间件 // 认证中间件
@@ -140,12 +252,15 @@ app.post('/api/auth/register', async (req, res) => {
const role = isFirstUser ? 'admin' : 'user'; const role = isFirstUser ? 'admin' : 'user';
const r = await pool.query( const r = await pool.query(
`INSERT INTO users (email, password_hash, username, avatar_url, role) `INSERT INTO users (email, password_hash, username, avatar_url, role, signature)
VALUES ($1, $2, $3, $4, $5) VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, username, avatar_url, role, created_at`, RETURNING id, username, avatar_url, role, signature, created_at`,
[email, hash, username, avatar, role] [email, hash, username, avatar, role, '']
); );
req.auditUserId = r.rows[0].id;
req.auditMetadata = { role: r.rows[0].role };
res.json({ res.json({
user: r.rows[0], user: r.rows[0],
message: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功' message: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功'
@@ -180,6 +295,8 @@ app.post('/api/auth/login', async (req, res) => {
return res.status(401).json({ error: '邮箱或密码错误' }); return res.status(401).json({ error: '邮箱或密码错误' });
} }
req.auditUserId = user.id;
const token = jwt.sign( const token = jwt.sign(
{ id: user.id, email: user.email, role: user.role }, { id: user.id, email: user.email, role: user.role },
JWT_SECRET, JWT_SECRET,
@@ -194,6 +311,7 @@ app.post('/api/auth/login', async (req, res) => {
avatar_url: user.avatar_url, avatar_url: user.avatar_url,
bio: user.bio, bio: user.bio,
role: user.role, role: user.role,
signature: user.signature || '',
} }
}); });
} catch (err) { } catch (err) {
@@ -205,7 +323,7 @@ app.post('/api/auth/login', async (req, res) => {
app.get('/api/auth/me', auth, async (req, res) => { app.get('/api/auth/me', auth, async (req, res) => {
try { try {
const r = await pool.query( const r = await pool.query(
'SELECT id, username, avatar_url, bio, role, created_at FROM users WHERE id = $1', 'SELECT id, username, avatar_url, bio, role, signature, created_at FROM users WHERE id = $1',
[req.user.id] [req.user.id]
); );
if (!r.rows[0]) { if (!r.rows[0]) {
@@ -218,23 +336,72 @@ app.get('/api/auth/me', auth, async (req, res) => {
}); });
// ============================================================ // ============================================================
// 用户管理 // 用户管理(支持分页和搜索)
// ============================================================ // ============================================================
// 获取用户信息(支持按用户名查询) // 获取用户列表(支持分页和按用户名搜索)- 管理员专用
app.get('/api/users', auth, admin, async (req, res) => { app.get('/api/users', auth, admin, async (req, res) => {
try { try {
let query = 'SELECT id, username, avatar_url, bio, role, created_at FROM users'; const page = parseInt(req.query.page) || 1;
const params = []; const limit = parseInt(req.query.limit) || 20;
const offset = (page - 1) * limit;
const search = req.query.search || '';
if (req.query.username) { let whereClause = '';
query += ' WHERE username = $1'; const params = [];
params.push(req.query.username); let paramIndex = 1;
if (search.trim()) {
whereClause = ' WHERE username ILIKE $' + paramIndex;
params.push('%' + search.trim() + '%');
paramIndex++;
} }
query += ' ORDER BY created_at DESC'; // 查询总数
const countQuery = 'SELECT COUNT(*) FROM users' + whereClause;
const countResult = await pool.query(countQuery, params);
const total = parseInt(countResult.rows[0].count);
const query = `
SELECT id, username, avatar_url, bio, role, signature, created_at
FROM users
${whereClause}
ORDER BY created_at DESC
LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
`;
params.push(limit, offset);
const r = await pool.query(query, params); const r = await pool.query(query, params);
res.json(r.rows);
res.json({
data: r.rows,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit)
}
});
} catch (err) {
res.status(500).json({ error: '服务器错误' });
}
});
// ============================================================
// 用户公开接口(无需登录)- 用于用户主页
// ============================================================
// 获取单个用户公开信息(无需登录)
app.get('/api/users/profile/:username', async (req, res) => {
try {
const r = await pool.query(
'SELECT id, username, avatar_url, bio, role, signature, created_at FROM users WHERE username = $1',
[req.params.username]
);
if (r.rows.length === 0) {
return res.status(404).json({ error: '用户不存在' });
}
res.json(r.rows[0]);
} catch (err) { } catch (err) {
res.status(500).json({ error: '服务器错误' }); res.status(500).json({ error: '服务器错误' });
} }
@@ -261,9 +428,9 @@ app.put('/api/users/:id/role', auth, admin, async (req, res) => {
} }
}); });
// 更新用户资料 // 更新用户资料(含签名)
app.put('/api/users/:id', auth, async (req, res) => { app.put('/api/users/:id', auth, async (req, res) => {
const { username, bio } = req.body; const { username, bio, signature } = req.body;
const userId = req.params.id; const userId = req.params.id;
if (userId !== req.user.id) { if (userId !== req.user.id) {
@@ -271,7 +438,10 @@ app.put('/api/users/:id', auth, async (req, res) => {
} }
try { try {
await pool.query('UPDATE users SET username = $1, bio = $2 WHERE id = $3', [username, bio || '', userId]); await pool.query(
'UPDATE users SET username = $1, bio = $2, signature = $3 WHERE id = $4',
[username, bio || '', signature || '', userId]
);
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
if (err.code === '23505') { if (err.code === '23505') {
@@ -379,10 +549,10 @@ app.put('/api/users/:id/email', auth, async (req, res) => {
}); });
// ============================================================ // ============================================================
// 帖子接口(含分页) // 帖子接口(含分页和置顶)
// ============================================================ // ============================================================
// 获取帖子列表(支持分页和用户筛选) // 获取帖子列表(支持分页和用户筛选,置顶优先)
app.get('/api/posts', async (req, res) => { app.get('/api/posts', async (req, res) => {
const sort = req.query.sort === 'hot' ? 'updated_at' : 'created_at'; const sort = req.query.sort === 'hot' ? 'updated_at' : 'created_at';
const page = parseInt(req.query.page) || 1; const page = parseInt(req.query.page) || 1;
@@ -395,6 +565,7 @@ app.get('/api/posts', async (req, res) => {
p.*, p.*,
u.username, u.username,
u.avatar_url, u.avatar_url,
u.signature,
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count (SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
FROM posts p FROM posts p
JOIN users u ON p.user_id = u.id JOIN users u ON p.user_id = u.id
@@ -415,7 +586,7 @@ app.get('/api/posts', async (req, res) => {
const countResult = await pool.query(countQuery, req.query.user_id ? [req.query.user_id] : []); const countResult = await pool.query(countQuery, req.query.user_id ? [req.query.user_id] : []);
const total = parseInt(countResult.rows[0]?.total || 0); const total = parseInt(countResult.rows[0]?.total || 0);
query += ` ORDER BY ${sort} DESC LIMIT $${params.length + 1} OFFSET $${params.length + 2}`; query += ` ORDER BY p.is_pinned DESC, p.pinned_at DESC NULLS LAST, ${sort} DESC LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
params.push(limit, offset); params.push(limit, offset);
const r = await pool.query(query, params); const r = await pool.query(query, params);
@@ -437,7 +608,7 @@ app.get('/api/posts', async (req, res) => {
app.get('/api/posts/:id', async (req, res) => { app.get('/api/posts/:id', async (req, res) => {
try { try {
const r = await pool.query( const r = await pool.query(
`SELECT p.*, u.username, u.avatar_url `SELECT p.*, u.username, u.avatar_url, u.signature
FROM posts p FROM posts p
JOIN users u ON p.user_id = u.id JOIN users u ON p.user_id = u.id
WHERE p.id = $1`, WHERE p.id = $1`,
@@ -533,6 +704,38 @@ app.delete('/api/posts/:id', auth, async (req, res) => {
} }
}); });
// 置顶/取消置顶帖子(管理员)
app.put('/api/posts/:id/pin', auth, admin, async (req, res) => {
const postId = req.params.id;
try {
const post = await pool.query('SELECT id, user_id FROM posts WHERE id = $1', [postId]);
if (post.rows.length === 0) {
return res.status(404).json({ error: '帖子不存在' });
}
const check = await pool.query('SELECT is_pinned FROM posts WHERE id = $1', [postId]);
const isPinned = check.rows[0].is_pinned;
const r = await pool.query(
`UPDATE posts SET is_pinned = $1, pinned_at = $2 WHERE id = $3 RETURNING *`,
[!isPinned, !isPinned ? new Date().toISOString() : null, postId]
);
await createNotification(
post.rows[0].user_id,
'system',
isPinned ? '你的帖子已被取消置顶' : '你的帖子已被置顶',
isPinned ? '管理员取消了你的帖子置顶' : '管理员把你的帖子置顶了',
'/?post=' + postId
);
res.json(r.rows[0]);
} catch (err) {
res.status(500).json({ error: '操作失败,请稍后重试' });
}
});
// ============================================================ // ============================================================
// 回复接口 // 回复接口
// ============================================================ // ============================================================
@@ -666,34 +869,64 @@ app.post('/api/reports', auth, async (req, res) => {
app.put('/api/reports/:id', auth, admin, async (req, res) => { app.put('/api/reports/:id', auth, admin, async (req, res) => {
const { status, note } = req.body; const { status, note } = req.body;
if (!['pending', 'approved', 'rejected'].includes(status)) { if (!['approved', 'rejected'].includes(status)) {
return res.status(400).json({ error: '无效的状态' }); return res.status(400).json({ error: '无效的状态' });
} }
let client;
try { try {
const report = await pool.query('SELECT reporter_id, post_id FROM reports WHERE id = $1', [req.params.id]); client = await pool.connect();
await client.query('BEGIN');
const report = await client.query(
'SELECT reporter_id, post_id, status FROM reports WHERE id = $1 FOR UPDATE',
[req.params.id]
);
if (report.rows.length === 0) {
await client.query('ROLLBACK');
return res.status(404).json({ error: '举报不存在' });
}
if (report.rows[0].status !== 'pending') {
await client.query('ROLLBACK');
return res.status(409).json({ error: '该举报已处理' });
}
await pool.query( await client.query(
`UPDATE reports `UPDATE reports
SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3 SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3
WHERE id = $4`, WHERE id = $4`,
[status, req.user.id, note || '', req.params.id] [status, req.user.id, note || '', req.params.id]
); );
if (report.rows[0]) { if (status === 'approved' && report.rows[0].post_id) {
await client.query('DELETE FROM posts WHERE id = $1', [report.rows[0].post_id]);
}
const statusText = status === 'approved' ? '已删除' : '已驳回'; const statusText = status === 'approved' ? '已删除' : '已驳回';
await createNotification( await client.query(
`INSERT INTO notifications (user_id, type, title, content, link)
VALUES ($1, $2, $3, $4, $5)`,
[
report.rows[0].reporter_id, report.rows[0].reporter_id,
'report_handled', 'report_handled',
'你的举报已被处理', '你的举报已被处理',
`你举报的帖子已被管理员${statusText}`, `你举报的帖子已被管理员${statusText}`,
report.rows[0].post_id ? '/?post=' + report.rows[0].post_id : null status === 'rejected' && report.rows[0].post_id ? '/?post=' + report.rows[0].post_id : null,
]
); );
}
res.json({ success: true }); await client.query('COMMIT');
res.json({ success: true, post_deleted: status === 'approved' });
} catch (err) { } catch (err) {
if (client) {
try {
await client.query('ROLLBACK');
} catch (rollbackError) {
console.error('回滚举报处理事务失败:', rollbackError);
}
}
res.status(500).json({ error: '操作失败,请稍后重试' }); res.status(500).json({ error: '操作失败,请稍后重试' });
} finally {
if (client) client.release();
} }
}); });
@@ -756,7 +989,6 @@ app.get('/api/stats', async (req, res) => {
posts: parseInt(postsRes.rows[0].count) || 0, posts: parseInt(postsRes.rows[0].count) || 0,
users: parseInt(usersRes.rows[0].count) || 0, users: parseInt(usersRes.rows[0].count) || 0,
topics: parseInt(postsRes.rows[0].count) || 0, topics: parseInt(postsRes.rows[0].count) || 0,
online: Math.floor(Math.random() * 20) + 5,
}); });
} catch (err) { } catch (err) {
res.status(500).json({ error: '服务器错误' }); res.status(500).json({ error: '服务器错误' });
@@ -764,40 +996,43 @@ app.get('/api/stats', async (req, res) => {
}); });
// ============================================================ // ============================================================
// 事件日志 // 事件日志(支持分页)
// ============================================================ // ============================================================
// 获取事件日志(管理员) // 获取事件日志(管理员)—— 支持分页
app.get('/api/event-logs', auth, admin, async (req, res) => { app.get('/api/event-logs', auth, admin, async (req, res) => {
try { try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 20;
const offset = (page - 1) * limit;
// 查询总数
const countResult = await pool.query('SELECT COUNT(*) FROM event_logs');
const total = parseInt(countResult.rows[0].count);
const r = await pool.query( const r = await pool.query(
`SELECT el.*, u.username `SELECT el.*, u.username
FROM event_logs el FROM event_logs el
LEFT JOIN users u ON el.user_id = u.id LEFT JOIN users u ON el.user_id = u.id
ORDER BY el.created_at DESC ORDER BY el.created_at DESC
LIMIT 100` LIMIT $1 OFFSET $2`,
[limit, offset]
); );
res.json(r.rows);
res.json({
data: r.rows,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit)
}
});
} catch (err) { } catch (err) {
res.status(500).json({ error: '服务器错误' }); res.status(500).json({ error: '服务器错误' });
} }
}); });
// 记录事件
app.post('/api/event-logs', auth, async (req, res) => {
const { action } = req.body;
try {
await pool.query(
`INSERT INTO event_logs (user_id, action, ip)
VALUES ($1, $2, $3)`,
[req.user.id, action, req.ip || '0.0.0.0']
);
res.json({ success: true });
} catch (err) {
res.json({ success: true });
}
});
// ============================================================ // ============================================================
// 图片上传 // 图片上传
// ============================================================ // ============================================================
@@ -827,6 +1062,67 @@ app.post('/api/upload', auth, upload.single('file'), (req, res) => {
res.json({ url: '/uploads/' + req.file.filename }); res.json({ url: '/uploads/' + req.file.filename });
}); });
// ============================================================
// 自定义 CSS
// ============================================================
const CUSTOM_CSS_DIR = path.join(__dirname, 'uploads/custom');
// 确保目录存在
if (!fs.existsSync(CUSTOM_CSS_DIR)) fs.mkdirSync(CUSTOM_CSS_DIR, { recursive: true });
// 保存自定义 CSS(管理员)
const cssUpload = multer({ dest: 'uploads/temp/' });
app.post('/api/admin/custom-css', auth, admin, cssUpload.single('file'), async (req, res) => {
if (!req.file) {
return res.status(400).json({ error: '请选择文件' });
}
if (req.file.originalname !== 'style.css') {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: '文件名必须是 style.css' });
}
// 移动到最终位置
const targetPath = path.join(CUSTOM_CSS_DIR, 'style.css');
if (fs.existsSync(targetPath)) fs.unlinkSync(targetPath);
fs.renameSync(req.file.path, targetPath);
// 记录到设置表
await pool.query(
`INSERT INTO settings (key, value) VALUES ($1, $2)
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
['custom_css_enabled', 'true']
);
res.json({ success: true });
});
// 获取自定义 CSS(公开)
app.get('/api/custom-css', async (req, res) => {
const cssPath = path.join(CUSTOM_CSS_DIR, 'style.css');
if (fs.existsSync(cssPath)) {
res.setHeader('Content-Type', 'text/css');
res.sendFile(cssPath);
} else {
res.status(404).send('');
}
});
// 删除自定义 CSS(管理员)
app.delete('/api/admin/custom-css', auth, admin, async (req, res) => {
const cssPath = path.join(CUSTOM_CSS_DIR, 'style.css');
if (fs.existsSync(cssPath)) {
fs.unlinkSync(cssPath);
await pool.query(
`INSERT INTO settings (key, value) VALUES ($1, $2)
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
['custom_css_enabled', 'false']
);
}
res.json({ success: true });
});
// ============================================================ // ============================================================
// 私信系统 // 私信系统
// ============================================================ // ============================================================
@@ -978,10 +1274,18 @@ app.post('/api/conversations/:id/messages', auth, async (req, res) => {
// 标记消息已读 // 标记消息已读
app.put('/api/messages/:id/read', auth, async (req, res) => { app.put('/api/messages/:id/read', auth, async (req, res) => {
try { try {
await pool.query(` const result = await pool.query(`
UPDATE messages SET is_read = true UPDATE messages AS m SET is_read = true
WHERE id = $1 AND sender_id != $2 FROM conversations AS c
WHERE m.id = $1
AND m.sender_id != $2
AND c.id = m.conversation_id
AND (c.user1_id = $2 OR c.user2_id = $2)
RETURNING m.id
`, [req.params.id, req.user.id]); `, [req.params.id, req.user.id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: '消息不存在或无权限' });
}
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
res.status(500).json({ error: '服务器错误' }); res.status(500).json({ error: '服务器错误' });
@@ -1237,25 +1541,51 @@ app.post('/api/auth/reset-password', async (req, res) => {
}); });
// ============================================================ // ============================================================
// 托管前端文件 // 托管公开前端文件
// ============================================================ // ============================================================
app.use(express.static('.')); app.use('/js', express.static(path.join(__dirname, 'js'), {
dotfiles: 'deny',
fallthrough: false,
index: false,
}));
app.get('/style.css', (req, res) => res.sendFile(path.join(__dirname, 'style.css')));
app.get('/config.js', (req, res) => res.sendFile(path.join(__dirname, 'config.js')));
app.get('*', (req, res) => { app.get('*', (req, res) => {
if (!req.path.startsWith('/api')) { if (req.path.startsWith('/api')) {
res.sendFile(path.join(__dirname, 'index.html')); return res.status(404).json({ error: '接口不存在' });
} }
if (path.extname(req.path)) {
return res.status(404).send('Not found');
}
return res.sendFile(path.join(__dirname, 'index.html'));
});
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: '请求内容过大' });
}
if (err.message === 'Origin is not allowed by CORS') {
return res.status(403).json({ error: '不允许的跨域来源' });
}
console.error(err);
return res.status(500).json({ error: '服务器错误' });
}); });
// ============================================================ // ============================================================
// 启动服务器 // 启动服务器
// ============================================================ // ============================================================
app.listen(PORT, '0.0.0.0', () => { if (require.main === module) {
app.listen(PORT, '0.0.0.0', () => {
console.log('========================================'); console.log('========================================');
console.log(' 🌊 Forumlify 已启动'); console.log(' 🌊 Forumlify 已启动');
console.log(' 📡 http://localhost:' + PORT); console.log(' 📡 http://localhost:' + PORT);
console.log(' 📡 API: http://localhost:' + PORT + '/api'); console.log(' 📡 API: http://localhost:' + PORT + '/api');
console.log('========================================'); console.log('========================================');
}); });
}
module.exports = { app, pool };
+1813 -342
View File
File diff suppressed because it is too large. Load diff
+75
View File
@@ -0,0 +1,75 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const request = require('supertest');
const bcrypt = require('bcryptjs');
const multerPackage = require('multer/package.json');
const projectPackage = require('../package.json');
const { app, pool } = require('../server');
test.after(async () => {
await pool.end();
});
test('serves the frontend with hardened response headers', async () => {
const response = await request(app).get('/').expect(200);
assert.match(response.headers['content-type'], /^text\/html/);
assert.equal(response.headers['x-content-type-options'], 'nosniff');
assert.equal(response.headers['x-frame-options'], 'SAMEORIGIN');
assert.equal(response.headers['x-powered-by'], undefined);
});
test('does not serve backend source and deployment files', async () => {
for (const path of ['/server.js', '/schema.sql', '/package.json', '/docker-compose.yml']) {
await request(app).get(path).expect(404);
}
});
test('unknown API route returns JSON 404 instead of hanging', async () => {
const response = await request(app)
.get('/api/definitely-unknown')
.timeout({ response: 1000, deadline: 2000 })
.expect(404);
assert.deepEqual(response.body, { error: '接口不存在' });
assert.ok(response.headers.ratelimit);
});
test('request body limit returns a structured 413 response', async () => {
const response = await request(app)
.post('/api/auth/login')
.send({ email: 'user@example.test', password: 'x'.repeat(110000) })
.expect(413);
assert.equal(response.body.error, '请求内容过大');
});
test('registration and login validate required fields before database access', async () => {
let response = await request(app)
.post('/api/auth/register')
.send({ email: '', password: '', username: '' })
.expect(400);
assert.equal(response.body.error, '请填写完整信息');
response = await request(app)
.post('/api/auth/login')
.send({ email: '', password: '' })
.expect(400);
assert.equal(response.body.error, '请填写邮箱和密码');
});
test('protected routes reject unauthenticated requests', async () => {
const response = await request(app)
.post('/api/posts')
.send({ title: 'test', content: 'test' })
.expect(401);
assert.equal(response.body.error, '请先登录');
});
test('bcryptjs hashes passwords without native install scripts', async () => {
const hash = await bcrypt.hash('correct horse battery staple', 4);
assert.equal(await bcrypt.compare('correct horse battery staple', hash), true);
assert.equal(await bcrypt.compare('wrong password', hash), false);
});
test('security-sensitive dependencies are on patched release lines', () => {
assert.match(multerPackage.version, /^2\.2\./);
assert.equal(projectPackage.dependencies['express-rate-limit'], '8.6.2');
});