From 4ca6b42ee43a81bc94535bcabffe083dcd1c5d14 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:09:46 +0800 Subject: [PATCH 01/41] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E9=A1=B5=E9=9D=A2=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- schema.sql | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/schema.sql b/schema.sql index 3030cd8..c438fac 100644 --- a/schema.sql +++ b/schema.sql @@ -91,3 +91,20 @@ nano schema.sql CREATE TRIGGER update_posts_updated_at BEFORE UPDATE ON posts FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +-- ============================================================ +-- 自定义页面表 +-- ============================================================ +CREATE TABLE IF NOT EXISTS custom_pages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(50) NOT NULL UNIQUE, + title VARCHAR(100) NOT NULL, + content TEXT NOT NULL, + sort_order INT DEFAULT 0, + enabled BOOLEAN DEFAULT true, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_custom_pages_name ON custom_pages(name); +CREATE INDEX IF NOT EXISTS idx_custom_pages_sort_order ON custom_pages(sort_order); From ffc6409b4208ffffbef240e01820cff846554926 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:12:54 +0800 Subject: [PATCH 02/41] Update server.js --- server.js | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/server.js b/server.js index 386d47c..c196ed1 100644 --- a/server.js +++ b/server.js @@ -813,6 +813,107 @@ app.put('/api/messages/:id/read', auth, async (req, res) => { } }); +// ============================================================ +// 自定义页面 +// ============================================================ + +// 获取所有自定义页面(公开,只返回启用且排序的) +app.get('/api/custom-pages', async (req, res) => { + try { + const r = await pool.query( + 'SELECT id, name, title, sort_order FROM custom_pages WHERE enabled = true ORDER BY sort_order' + ); + res.json(r.rows); + } catch (err) { + res.status(500).json({ error: '服务器错误' }); + } +}); + +// 获取单个自定义页面(公开) +app.get('/api/custom-pages/:name', async (req, res) => { + try { + const r = await pool.query( + 'SELECT id, name, title, content FROM custom_pages WHERE name = $1 AND enabled = true', + [req.params.name] + ); + if (r.rows.length === 0) { + return res.status(404).json({ error: '页面不存在' }); + } + res.json(r.rows[0]); + } catch (err) { + res.status(500).json({ error: '服务器错误' }); + } +}); + +// 获取所有自定义页面(管理员,含禁用) +app.get('/api/admin/custom-pages', auth, admin, async (req, res) => { + try { + const r = await pool.query( + 'SELECT id, name, title, content, sort_order, enabled, created_at, updated_at FROM custom_pages ORDER BY sort_order' + ); + res.json(r.rows); + } catch (err) { + res.status(500).json({ error: '服务器错误' }); + } +}); + +// 创建自定义页面(管理员) +app.post('/api/admin/custom-pages', auth, admin, async (req, res) => { + const { name, title, content, sort_order } = req.body; + if (!name || !title || !content) { + return res.status(400).json({ error: '请填写完整信息' }); + } + if (!/^[a-zA-Z0-9\-_]+$/.test(name)) { + return res.status(400).json({ error: '页面名称只允许字母、数字、短横线和下划线' }); + } + try { + const r = await pool.query( + `INSERT INTO custom_pages (name, title, content, sort_order) + VALUES ($1, $2, $3, $4) + RETURNING *`, + [name, title, content, sort_order || 0] + ); + res.json(r.rows[0]); + } catch (err) { + if (err.code === '23505') { + res.status(400).json({ error: '页面名称已存在' }); + } else { + res.status(500).json({ error: '创建失败,请稍后重试' }); + } + } +}); + +// 更新自定义页面(管理员) +app.put('/api/admin/custom-pages/:id', auth, admin, async (req, res) => { + const { title, content, sort_order, enabled } = req.body; + const id = req.params.id; + try { + const r = await pool.query( + `UPDATE custom_pages + SET title = $1, content = $2, sort_order = $3, enabled = $4, updated_at = NOW() + WHERE id = $5 + RETURNING *`, + [title, content, sort_order || 0, enabled, id] + ); + if (r.rows.length === 0) { + return res.status(404).json({ error: '页面不存在' }); + } + res.json(r.rows[0]); + } catch (err) { + res.status(500).json({ error: '更新失败,请稍后重试' }); + } +}); + +// 删除自定义页面(管理员) +app.delete('/api/admin/custom-pages/:id', auth, admin, async (req, res) => { + try { + await pool.query('DELETE FROM custom_pages WHERE id = $1', [req.params.id]); + res.json({ success: true }); + } catch (err) { + res.status(500).json({ error: '删除失败,请稍后重试' }); + } +}); + // ============================================================ // 托管前端文件 // ============================================================ From d381f5b033b008711afd118583cc4ca7afaff6cc Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:13:23 +0800 Subject: [PATCH 03/41] Update api.js --- js/api.js | 201 ------------------------------------------------------ 1 file changed, 201 deletions(-) diff --git a/js/api.js b/js/api.js index c9c102c..41a0f22 100644 --- a/js/api.js +++ b/js/api.js @@ -64,204 +64,3 @@ const API = { if (data.error) throw new Error(data.error); return data; }, - - async getPost(postId) { - const data = await apiFetch('/posts/' + postId); - if (data.error) throw new Error(data.error); - return data; - }, - - async createPost(title, content, images) { - const data = await apiFetch('/posts', { - method: 'POST', - body: JSON.stringify({ title, content, images: images || [] }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async deletePost(postId) { - const data = await apiFetch('/posts/' + postId, { method: 'DELETE' }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 回复 - // ============================================================ - async getReplies(postId) { - const data = await apiFetch('/posts/' + postId + '/replies'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async createReply(postId, content) { - const data = await apiFetch('/posts/' + postId + '/replies', { - method: 'POST', - body: JSON.stringify({ content }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async deleteReply(replyId) { - const data = await apiFetch('/replies/' + replyId, { method: 'DELETE' }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 用户管理 - // ============================================================ - async getUsers() { - const data = await apiFetch('/users'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async updateUserRole(userId, role) { - const data = await apiFetch('/users/' + userId + '/role', { - method: 'PUT', - body: JSON.stringify({ role }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 举报 - // ============================================================ - async getReports() { - const data = await apiFetch('/reports'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async createReport(postId, reason) { - const data = await apiFetch('/reports', { - method: 'POST', - body: JSON.stringify({ post_id: postId, reason }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async updateReport(reportId, status, note) { - const data = await apiFetch('/reports/' + reportId, { - method: 'PUT', - body: JSON.stringify({ status, note }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 统计 - // ============================================================ - async getStats() { - const data = await apiFetch('/stats'); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 友情链接 - // ============================================================ - async getLinks() { - const data = await apiFetch('/links'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async addLink(title, url) { - const data = await apiFetch('/links', { - method: 'POST', - body: JSON.stringify({ title, url }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async deleteLink(id) { - const data = await apiFetch('/links/' + id, { method: 'DELETE' }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 事件日志 - // ============================================================ - async getEventLogs() { - const data = await apiFetch('/event-logs'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async logEvent(action) { - try { - await apiFetch('/event-logs', { - method: 'POST', - body: JSON.stringify({ action }) - }); - } catch (e) { /* 静默失败 */ } - }, - - // ============================================================ - // 论坛设置 - // ============================================================ - async getSettings() { - const data = await apiFetch('/settings'); - if (data.error) throw new Error(data.error); - return data; - }, - - async updateSettings(forum_name) { - const data = await apiFetch('/settings', { - method: 'PUT', - body: JSON.stringify({ forum_name }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - // ============================================================ - // 私信 - // ============================================================ - async getConversations() { - const data = await apiFetch('/conversations'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async getOrCreateConversation(other_user_id) { - const data = await apiFetch('/conversations', { - method: 'POST', - body: JSON.stringify({ other_user_id }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async getMessages(conversationId) { - const data = await apiFetch('/conversations/' + conversationId + '/messages'); - if (data.error) throw new Error(data.error); - return data || []; - }, - - async sendMessage(conversationId, content) { - const data = await apiFetch('/conversations/' + conversationId + '/messages', { - method: 'POST', - body: JSON.stringify({ content }) - }); - if (data.error) throw new Error(data.error); - return data; - }, - - async markMessageRead(messageId) { - const data = await apiFetch('/messages/' + messageId + '/read', { - method: 'PUT' - }); - if (data.error) throw new Error(data.error); - return data; - } -}; From 43a45162e1b8317b406f645d9bc16c8fca674c12 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:14:34 +0800 Subject: [PATCH 04/41] Update api.js --- js/api.js | 247 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 247 insertions(+) diff --git a/js/api.js b/js/api.js index 41a0f22..e771de8 100644 --- a/js/api.js +++ b/js/api.js @@ -64,3 +64,250 @@ const API = { if (data.error) throw new Error(data.error); return data; }, + + async getPost(postId) { + const data = await apiFetch('/posts/' + postId); + if (data.error) throw new Error(data.error); + return data; + }, + + async createPost(title, content, images) { + const data = await apiFetch('/posts', { + method: 'POST', + body: JSON.stringify({ title, content, images: images || [] }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async deletePost(postId) { + const data = await apiFetch('/posts/' + postId, { method: 'DELETE' }); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 回复 + // ============================================================ + async getReplies(postId) { + const data = await apiFetch('/posts/' + postId + '/replies'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async createReply(postId, content) { + const data = await apiFetch('/posts/' + postId + '/replies', { + method: 'POST', + body: JSON.stringify({ content }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async deleteReply(replyId) { + const data = await apiFetch('/replies/' + replyId, { method: 'DELETE' }); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 用户管理 + // ============================================================ + async getUsers() { + const data = await apiFetch('/users'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async updateUserRole(userId, role) { + const data = await apiFetch('/users/' + userId + '/role', { + method: 'PUT', + body: JSON.stringify({ role }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 举报 + // ============================================================ + async getReports() { + const data = await apiFetch('/reports'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async createReport(postId, reason) { + const data = await apiFetch('/reports', { + method: 'POST', + body: JSON.stringify({ post_id: postId, reason }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async updateReport(reportId, status, note) { + const data = await apiFetch('/reports/' + reportId, { + method: 'PUT', + body: JSON.stringify({ status, note }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 统计 + // ============================================================ + async getStats() { + const data = await apiFetch('/stats'); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 友情链接 + // ============================================================ + async getLinks() { + const data = await apiFetch('/links'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async addLink(title, url) { + const data = await apiFetch('/links', { + method: 'POST', + body: JSON.stringify({ title, url }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async deleteLink(id) { + const data = await apiFetch('/links/' + id, { method: 'DELETE' }); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 事件日志 + // ============================================================ + async getEventLogs() { + const data = await apiFetch('/event-logs'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async logEvent(action) { + try { + await apiFetch('/event-logs', { + method: 'POST', + body: JSON.stringify({ action }) + }); + } catch (e) { /* 静默失败 */ } + }, + + // ============================================================ + // 论坛设置 + // ============================================================ + async getSettings() { + const data = await apiFetch('/settings'); + if (data.error) throw new Error(data.error); + return data; + }, + + async updateSettings(forum_name) { + const data = await apiFetch('/settings', { + method: 'PUT', + body: JSON.stringify({ forum_name }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 私信 + // ============================================================ + async getConversations() { + const data = await apiFetch('/conversations'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async getOrCreateConversation(other_user_id) { + const data = await apiFetch('/conversations', { + method: 'POST', + body: JSON.stringify({ other_user_id }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async getMessages(conversationId) { + const data = await apiFetch('/conversations/' + conversationId + '/messages'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async sendMessage(conversationId, content) { + const data = await apiFetch('/conversations/' + conversationId + '/messages', { + method: 'POST', + body: JSON.stringify({ content }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async markMessageRead(messageId) { + const data = await apiFetch('/messages/' + messageId + '/read', { + method: 'PUT' + }); + if (data.error) throw new Error(data.error); + return data; + }, + + // ============================================================ + // 自定义页面 + // ============================================================ + + async getCustomPages() { + const data = await apiFetch('/custom-pages'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async getCustomPage(name) { + const data = await apiFetch('/custom-pages/' + encodeURIComponent(name)); + if (data.error) throw new Error(data.error); + return data; + }, + + async getAdminCustomPages() { + const data = await apiFetch('/admin/custom-pages'); + if (data.error) throw new Error(data.error); + return data || []; + }, + + async createCustomPage(name, title, content, sort_order) { + const data = await apiFetch('/admin/custom-pages', { + method: 'POST', + body: JSON.stringify({ name, title, content, sort_order }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async updateCustomPage(id, title, content, sort_order, enabled) { + const data = await apiFetch('/admin/custom-pages/' + id, { + method: 'PUT', + body: JSON.stringify({ title, content, sort_order, enabled }) + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async deleteCustomPage(id) { + const data = await apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' }); + if (data.error) throw new Error(data.error); + return data; + } +}; From f9443fb32da1fb3260d3ae12230c3c0f302a9af4 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:15:07 +0800 Subject: [PATCH 05/41] Update admin.js --- js/admin.js | 176 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 174 insertions(+), 2 deletions(-) diff --git a/js/admin.js b/js/admin.js index 98b0a9c..3f35bc7 100644 --- a/js/admin.js +++ b/js/admin.js @@ -244,7 +244,178 @@ function renderAdminSettings() { }); } -// 管理后台Tab切换 +// ============================================================ +// 📄 自定义页面管理 +// ============================================================ + +let editingPageId = null; + +function renderAdminCustomPages() { + const container = document.getElementById('adminContent'); + container.innerHTML = ` +
+

📄 自定义页面

+ +
+
+ `; + + loadCustomPageList(); + + document.getElementById('addCustomPageBtn').addEventListener('click', function() { + editingPageId = null; + openCustomPageEditor(); + }); +} + +function loadCustomPageList() { + const container = document.getElementById('customPageList'); + container.innerHTML = '
加载中...
'; + API.getAdminCustomPages().then(pages => { + if (pages.length === 0) { + container.innerHTML = '
暂无自定义页面
'; + return; + } + let html = `
+ + + + + + + + + + + + + `; + pages.forEach(p => { + html += ` + + + + + + + + + `; + }); + html += '
名称标题URL排序状态操作
${p.name}${p.title}?custom=${p.name}${p.sort_order}${p.enabled ? '✅ 启用' : '❌ 禁用'} + + +
'; + container.innerHTML = html; + + container.querySelectorAll('[data-action="edit"]').forEach(btn => { + btn.addEventListener('click', function() { + const page = pages.find(p => p.id === this.dataset.id); + if (page) { + editingPageId = page.id; + openCustomPageEditor(page); + } + }); + }); + + container.querySelectorAll('[data-action="delete"]').forEach(btn => { + btn.addEventListener('click', function() { + if (!confirm('确定要删除这个页面吗?')) return; + API.deleteCustomPage(this.dataset.id).then(() => { + loadCustomPageList(); + loadCustomPagesNav(); + }).catch(err => alert('删除失败:' + err.message)); + }); + }); + }).catch(err => { + container.innerHTML = '
加载失败
'; + }); +} + +function openCustomPageEditor(page) { + const isEdit = !!page; + const modal = document.createElement('div'); + modal.className = 'modal active'; + modal.style.display = 'flex'; + modal.innerHTML = ` + + `; + + document.body.appendChild(modal); + + modal.querySelector('.close').addEventListener('click', function() { + modal.remove(); + }); + modal.addEventListener('click', function(e) { + if (e.target === this) modal.remove(); + }); + + modal.querySelector('#editorSaveBtn').addEventListener('click', async function() { + const name = document.getElementById('editorPageName').value.trim(); + const title = document.getElementById('editorPageTitle').value.trim(); + const content = document.getElementById('editorContent').value.trim(); + const sort_order = parseInt(document.getElementById('editorSortOrder').value) || 0; + const enabled = document.getElementById('editorEnabled').value === 'true'; + + if (!name) { alert('请输入页面名称'); return; } + if (!title) { alert('请输入导航栏显示名称'); return; } + if (!content) { alert('请输入页面内容'); return; } + if (!/^[a-zA-Z0-9\-_]+$/.test(name)) { + alert('页面名称只允许字母、数字、短横线和下划线'); + return; + } + + try { + if (isEdit) { + await API.updateCustomPage(page.id, title, content, sort_order, enabled); + } else { + await API.createCustomPage(name, title, content, sort_order); + } + modal.remove(); + loadCustomPageList(); + loadCustomPagesNav(); + } catch (err) { + alert('保存失败:' + err.message); + } + }); +} + +// ============================================================ +// 管理后台Tab切换 +// ============================================================ + document.querySelectorAll('.admin-tab').forEach(tab => { tab.addEventListener('click', function() { document.querySelectorAll('.admin-tab').forEach(t => t.classList.remove('active')); @@ -254,7 +425,8 @@ document.querySelectorAll('.admin-tab').forEach(tab => { users: renderAdminUsers, logs: renderAdminLogs, links: renderAdminLinks, - settings: renderAdminSettings + settings: renderAdminSettings, + custom: renderAdminCustomPages }; if (tabMap[this.dataset.tab]) tabMap[this.dataset.tab](); }); From 8665a9a0efb312802f87b5b22b1c7665eea317d7 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:16:11 +0800 Subject: [PATCH 06/41] Update app.js --- js/app.js | 136 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 135 insertions(+), 1 deletion(-) diff --git a/js/app.js b/js/app.js index 4d95b4f..0ee39de 100644 --- a/js/app.js +++ b/js/app.js @@ -60,14 +60,26 @@ function switchPage(page, param) { return; } + if (page === 'custom' && param) { + url.searchParams.set('custom', param); + url.searchParams.delete('page'); + url.searchParams.delete('post'); + url.searchParams.delete('user'); + window.history.pushState({ page: 'custom', custom: param }, '', url); + showCustomPage(param); + return; + } + if (page === 'feed') { url.searchParams.delete('page'); url.searchParams.delete('post'); url.searchParams.delete('user'); + url.searchParams.delete('custom'); } else { url.searchParams.set('page', page); url.searchParams.delete('post'); url.searchParams.delete('user'); + url.searchParams.delete('custom'); } window.history.pushState({ page: page }, '', url); @@ -76,6 +88,13 @@ function switchPage(page, param) { el.classList.remove('active', 'slide-out'); }); + // 隐藏自定义页面容器 + const customContainer = document.getElementById('customPageContainer'); + if (customContainer) { + customContainer.classList.remove('active'); + customContainer.style.display = 'none'; + } + if (page === 'feed') { document.getElementById('app').style.display = 'flex'; currentPage = 'feed'; @@ -334,6 +353,114 @@ function handleImageFiles(files) { if (fileInput) fileInput.value = ''; } +// ============================================================ +// 📄 自定义页面导航 +// ============================================================ + +let customPagesNav = []; + +async function loadCustomPagesNav() { + try { + const pages = await API.getCustomPages(); + customPagesNav = pages; + renderCustomPagesNav(); + } catch (e) { + customPagesNav = []; + } +} + +function renderCustomPagesNav() { + const userDropdown = document.getElementById('userDropdown'); + const existingLinks = userDropdown.querySelectorAll('.custom-page-nav-link'); + existingLinks.forEach(el => el.remove()); + + const messageBtn = document.getElementById('messageBtn'); + if (!messageBtn) return; + + customPagesNav.forEach(page => { + const link = document.createElement('a'); + link.className = 'custom-page-nav-link'; + link.href = '#'; + link.dataset.page = 'custom'; + link.dataset.custom = page.name; + link.textContent = page.title; + link.style.cssText = 'padding:6px 10px;border-radius:4px;color:var(--text-secondary);text-decoration:none;font-size:13px;transition:color 0.15s;margin-right:4px;'; + link.addEventListener('mouseenter', function() { + this.style.color = 'var(--text)'; + }); + link.addEventListener('mouseleave', function() { + this.style.color = 'var(--text-secondary)'; + }); + link.addEventListener('click', function(e) { + e.preventDefault(); + switchPage('custom', page.name); + }); + userDropdown.insertBefore(link, messageBtn.nextSibling); + }); +} + +// ============================================================ +// 📄 自定义页面渲染 +// ============================================================ + +function showCustomPage(pageName) { + document.getElementById('app').style.display = 'none'; + document.querySelectorAll('.page-slide').forEach(el => { + el.classList.remove('active', 'slide-out'); + }); + + let container = document.getElementById('customPageContainer'); + if (!container) { + container = document.createElement('div'); + container.id = 'customPageContainer'; + container.className = 'page-slide'; + container.style.cssText = 'display:none;position:fixed;inset:0;background:var(--bg);z-index:50;padding:84px 32px 40px;overflow-y:auto;transition:background 0.2s;'; + document.body.appendChild(container); + } + + container.innerHTML = '
加载中...
'; + container.classList.add('active'); + container.style.display = 'block'; + currentPage = 'custom'; + + API.getCustomPage(pageName).then(page => { + const iframe = document.createElement('iframe'); + 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.srcdoc = ` + + + + + + + ${page.content} + + + + `; + container.innerHTML = ''; + container.appendChild(iframe); + + document.querySelectorAll('.custom-page-nav-link').forEach(el => { + el.style.color = el.dataset.custom === pageName ? 'var(--primary)' : 'var(--text-secondary)'; + }); + }).catch(err => { + container.innerHTML = '
页面加载失败:' + err.message + '
'; + }); +} + // ============================================================ // 🚀 初始化 // ============================================================ @@ -358,6 +485,7 @@ async function init() { } renderNav(); await loadForumName(); + await loadCustomPagesNav(); renderStats(); renderLinks(); @@ -366,12 +494,15 @@ async function init() { const pageParam = urlParams.get('page'); const userParam = urlParams.get('user'); const postPageParam = urlParams.get('postpage'); + const customParam = urlParams.get('custom'); if (postPageParam) { currentPageNum = parseInt(postPageParam) || 1; } - if (userParam) { + if (customParam) { + showCustomPage(customParam); + } else if (userParam) { showUserPage(userParam); } else if (postParam) { showPostPage(postParam); @@ -558,10 +689,13 @@ async function init() { const page = state.page || 'feed'; const postId = state.postId || null; const username = state.username || null; + const custom = state.custom || null; if (postId) { showPostPage(postId); } else if (username) { showUserPage(username); + } else if (custom) { + showCustomPage(custom); } else { switchPage(page); } From de6a926f7b1610941a946a19fbb30c23b5c167c7 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:19:24 +0800 Subject: [PATCH 07/41] Update index.html --- index.html | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index 2ae6b7d..3742d28 100644 --- a/index.html +++ b/index.html @@ -20,6 +20,7 @@
加载中...
@@ -168,7 +173,6 @@
-

From 0142bc5c2ae63022c38ac1acb70af269e57e860e Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:22:05 +0800 Subject: [PATCH 08/41] Update schema.sql --- schema.sql | 61 ++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 15 deletions(-) diff --git a/schema.sql b/schema.sql index c438fac..53ee04a 100644 --- a/schema.sql +++ b/schema.sql @@ -1,3 +1,7 @@ +-- ============================================================ +-- Forumlify 数据库表结构 +-- ============================================================ + -- 用户表 CREATE TABLE IF NOT EXISTS users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), @@ -61,7 +65,7 @@ CREATE TABLE IF NOT EXISTS event_logs ( ); -- ============================================================ --- 论坛设置表(新增) +-- 论坛设置表 -- ============================================================ CREATE TABLE IF NOT EXISTS settings ( key VARCHAR(50) PRIMARY KEY, @@ -74,23 +78,34 @@ INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify') ON CONFLICT (key) DO NOTHING; -- ============================================================ --- 自动更新 updated_at 的触发器 +-- 私信系统 -- ============================================================ -CREATE OR REPLACE FUNCTION update_updated_at() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = now(); - RETURN NEW; -END; -$$ LANGUAGE plpgsql; -DROP TRIGGER IF EXISTS update_posts_updated_at ON posts; +-- 私信会话表 +CREATE TABLE IF NOT EXISTS conversations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + last_message_at TIMESTAMPTZ DEFAULT now(), + created_at TIMESTAMPTZ DEFAULT now(), + UNIQUE(user1_id, user2_id) +); -cd /root/forumlify -nano schema.sql -CREATE TRIGGER update_posts_updated_at - BEFORE UPDATE ON posts - FOR EACH ROW EXECUTE FUNCTION update_updated_at(); +-- 私信消息表 +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + content TEXT NOT NULL, + is_read BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT now() +); + +-- 创建索引 +CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id); +CREATE INDEX IF NOT EXISTS idx_messages_sender_id ON messages(sender_id); +CREATE INDEX IF NOT EXISTS idx_conversations_user1_id ON conversations(user1_id); +CREATE INDEX IF NOT EXISTS idx_conversations_user2_id ON conversations(user2_id); -- ============================================================ -- 自定义页面表 @@ -108,3 +123,19 @@ CREATE TABLE IF NOT EXISTS custom_pages ( CREATE INDEX IF NOT EXISTS idx_custom_pages_name ON custom_pages(name); CREATE INDEX IF NOT EXISTS idx_custom_pages_sort_order ON custom_pages(sort_order); + +-- ============================================================ +-- 自动更新 updated_at 的触发器 +-- ============================================================ +CREATE OR REPLACE FUNCTION update_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = now(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS update_posts_updated_at ON posts; +CREATE TRIGGER update_posts_updated_at + BEFORE UPDATE ON posts + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); From 53ee6fb63a2836c11d8b989cf2993b09d78aa9ee Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:31:54 +0800 Subject: [PATCH 09/41] Update app.js --- js/app.js | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/js/app.js b/js/app.js index 0ee39de..f896980 100644 --- a/js/app.js +++ b/js/app.js @@ -88,7 +88,6 @@ function switchPage(page, param) { el.classList.remove('active', 'slide-out'); }); - // 隐藏自定义页面容器 const customContainer = document.getElementById('customPageContainer'); if (customContainer) { customContainer.classList.remove('active'); @@ -370,21 +369,16 @@ async function loadCustomPagesNav() { } function renderCustomPagesNav() { - const userDropdown = document.getElementById('userDropdown'); - const existingLinks = userDropdown.querySelectorAll('.custom-page-nav-link'); - existingLinks.forEach(el => el.remove()); - - const messageBtn = document.getElementById('messageBtn'); - if (!messageBtn) return; + const container = document.getElementById('customNavLinks'); + if (!container) return; + container.innerHTML = ''; customPagesNav.forEach(page => { const link = document.createElement('a'); - link.className = 'custom-page-nav-link'; link.href = '#'; - link.dataset.page = 'custom'; link.dataset.custom = page.name; link.textContent = page.title; - link.style.cssText = 'padding:6px 10px;border-radius:4px;color:var(--text-secondary);text-decoration:none;font-size:13px;transition:color 0.15s;margin-right:4px;'; + link.style.cssText = 'color:var(--text-secondary);text-decoration:none;font-size:14px;padding:4px 10px;border-radius:4px;transition:color 0.15s;'; link.addEventListener('mouseenter', function() { this.style.color = 'var(--text)'; }); @@ -395,7 +389,7 @@ function renderCustomPagesNav() { e.preventDefault(); switchPage('custom', page.name); }); - userDropdown.insertBefore(link, messageBtn.nextSibling); + container.appendChild(link); }); } From 487773788dffdb1545250ba5a77cf6ddcb3f7bb4 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:32:33 +0800 Subject: [PATCH 10/41] Update admin.js --- js/admin.js | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/js/admin.js b/js/admin.js index 3f35bc7..12ea827 100644 --- a/js/admin.js +++ b/js/admin.js @@ -283,7 +283,6 @@ function loadCustomPageList() { 名称 标题 URL - 排序 状态 操作 @@ -296,7 +295,6 @@ function loadCustomPageList() { ${p.name} ${p.title} ?custom=${p.name} - ${p.sort_order} ${p.enabled ? '✅ 启用' : '❌ 禁用'} @@ -352,11 +350,6 @@ function openCustomPageEditor(page) {

-
- - -
+
+
+ + +
+ +
+
+ `; + + document.getElementById('settingsSaveBtn').addEventListener('click', async function() { + const username = document.getElementById('settingsUsername').value.trim(); + const bio = document.getElementById('settingsBio').value.trim(); + if (!username) { alert('用户名不能为空'); return; } + try { + const data = await apiFetch('/users/' + user.id, { + method: 'PUT', + body: JSON.stringify({ username, bio }) + }); + if (data.error) throw new Error(data.error); + currentUser.username = username; + currentUser.bio = bio; + alert('保存成功!'); + renderNav(); + renderSettingsPage(); + } catch (err) { + alert('保存失败:' + err.message); + } + }); + } catch (err) { + container.innerHTML = '
加载失败
'; + } +} + // ============================================================ // 🚀 初始化 // ============================================================ @@ -551,29 +679,6 @@ async function init() { }); }); - document.getElementById('settingsSave').addEventListener('click', async () => { - if (!currentUser) { alert('请先登录'); return; } - const username = document.getElementById('settingsUsername').value.trim(); - const bio = document.getElementById('settingsBio').value.trim(); - if (!username) { alert('用户名不能为空'); return; } - try { - const data = await apiFetch('/users/' + currentUser.id, { - method: 'PUT', - body: JSON.stringify({ username, bio }) - }); - if (data.error) throw new Error(data.error); - currentUser.username = username; - currentUser.bio = bio; - alert('保存成功!'); - renderNav(); - if (currentPage === 'feed') { - renderFeed(); - } - } catch (err) { - alert('保存失败:' + err.message); - } - }); - document.getElementById('forumName').addEventListener('click', function() { switchPage('feed'); }); From 40bb6efecbda8a609f3396531bff6c9e1e6b39e9 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 22:56:01 +0800 Subject: [PATCH 15/41] Update index.html --- index.html | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/index.html b/index.html index 6dacd90..36a63e0 100644 --- a/index.html +++ b/index.html @@ -99,6 +99,7 @@ +
-

暂无消息

+
+
加载中...
+
+
- '; } const replyCount = p.reply_count || 0; + + // Markdown 渲染 + const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, '
'); + html += `
${username} ${time} + ${p.edited_at ? '(已编辑)' : ''}
${p.title || '无标题'}
-
${(p.content || '').replace(/\n/g, '
')}
+
${renderedContent}
${imagesHtml}
From 317c9b1281cc6176a461940f3edd30c85f2a654f Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:20:04 +0800 Subject: [PATCH 27/41] Update admin.js From 1a0f6e6b70f8b200ec028cdad6aff7c91e9a7642 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:23:26 +0800 Subject: [PATCH 28/41] Update index.html --- index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/index.html b/index.html index 36a63e0..b058167 100644 --- a/index.html +++ b/index.html @@ -4,6 +4,7 @@ Forumlify + From afd3dd54c8b5bb4292a1921760e006f43fe14320 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:27:34 +0800 Subject: [PATCH 29/41] Update post.js --- js/post.js | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/js/post.js b/js/post.js index 25aeef2..c9b1c1f 100644 --- a/js/post.js +++ b/js/post.js @@ -54,19 +54,34 @@ async function renderPostDetail(postId) { imagesHtml += '
'; } + // Markdown 渲染(安全处理) + let renderedContent = post.content || ''; + try { + if (typeof marked !== 'undefined' && marked.parse) { + renderedContent = marked.parse(renderedContent); + } else { + renderedContent = renderedContent.replace(/\n/g, '
'); + } + } catch (e) { + renderedContent = renderedContent.replace(/\n/g, '
'); + } + let html = `
${username} ${time} - ${currentUser && currentUser.id === post.user_id ? `` : ''} + ${post.edited_at ? `(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})` : ''} +
+ ${currentUser && currentUser.id === post.user_id ? `` : ''} + ${currentUser && currentUser.id === post.user_id ? `` : ''} +
-
${post.title || '无标题'}
-
${(post.content || '').replace(/\n/g, '
')}
+
${renderedContent}
${imagesHtml}
@@ -110,6 +125,17 @@ async function renderPostDetail(postId) { document.getElementById('replyCaptchaInput').value = ''; refreshCaptcha('reply'); + // 编辑按钮 + const editBtn = document.getElementById('editPostBtn'); + if (editBtn) { + editBtn.addEventListener('click', function() { + const postId = this.dataset.postid; + const currentTitle = post.title || ''; + const currentContent = post.content || ''; + openEditModal(postId, currentTitle, currentContent); + }); + } + const deleteBtn = document.getElementById('detailDeleteBtn'); if (deleteBtn) { deleteBtn.addEventListener('click', function() { From 3ce6bebdec69e827809d604bd883fb0ca0d30582 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:32:16 +0800 Subject: [PATCH 30/41] Update server.js --- server.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/server.js b/server.js index 41d72fd..8a27bad 100644 --- a/server.js +++ b/server.js @@ -398,6 +398,34 @@ app.post('/api/posts', auth, async (req, res) => { } }); +// 编辑帖子 +app.put('/api/posts/:id', auth, async (req, res) => { + const { title, content } = req.body; + const postId = req.params.id; + + if (!content || content.trim().length === 0) { + return res.status(400).json({ error: '请填写内容' }); + } + + try { + const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [postId]); + if (post.rows.length === 0) { + return res.status(404).json({ error: '帖子不存在' }); + } + if (post.rows[0].user_id !== req.user.id) { + return res.status(403).json({ error: '无权限编辑此帖子' }); + } + + const r = await pool.query( + `UPDATE posts SET title = $1, content = $2, edited_at = NOW() WHERE id = $3 RETURNING *`, + [title || '无标题', content, postId] + ); + res.json(r.rows[0]); + } catch (err) { + res.status(500).json({ error: '编辑失败,请稍后重试' }); + } +}); + // 删除帖子 app.delete('/api/posts/:id', auth, async (req, res) => { try { From c674847586654d3a5e59996d0c0417e9e6c24e08 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:40:43 +0800 Subject: [PATCH 31/41] Update schema.sql --- schema.sql | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/schema.sql b/schema.sql index 95183ce..ecb7a66 100644 --- a/schema.sql +++ b/schema.sql @@ -155,3 +155,15 @@ CREATE TRIGGER update_posts_updated_at ALTER TABLE posts ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ; +-- ============================================================ +-- 恢复码表(密码重置用) +-- ============================================================ +CREATE TABLE IF NOT EXISTS recovery_codes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + code_hash VARCHAR(255) NOT NULL, + is_used BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id); From 4ec329afbc415732cf8d8cd8284afaa355dffc84 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:41:36 +0800 Subject: [PATCH 32/41] Update api.js --- js/api.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/js/api.js b/js/api.js index 494f63f..042bcd8 100644 --- a/js/api.js +++ b/js/api.js @@ -329,5 +329,31 @@ const API = { }); if (data.error) throw new Error(data.error); return data; + }, + + // ============================================================ + // 恢复码 + // ============================================================ + async generateRecoveryCodes() { + const data = await apiFetch('/auth/recovery-codes/generate', { + method: 'POST' + }); + if (data.error) throw new Error(data.error); + return data; + }, + + async getRecoveryCodesCount() { + const data = await apiFetch('/auth/recovery-codes/count'); + if (data.error) throw new Error(data.error); + return data; + }, + + async resetPassword(email, recoveryCode, newPassword) { + const data = await apiFetch('/auth/reset-password', { + method: 'POST', + body: JSON.stringify({ email, recoveryCode, newPassword }) + }); + if (data.error) throw new Error(data.error); + return data; } }; From 4880859c5417eced1ae548b776c669dc3ee0c5c1 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:42:51 +0800 Subject: [PATCH 33/41] Update app.js --- js/app.js | 165 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 163 insertions(+), 2 deletions(-) diff --git a/js/app.js b/js/app.js index 072dfa8..10191f2 100644 --- a/js/app.js +++ b/js/app.js @@ -512,7 +512,7 @@ async function renderMessagesPage() { } // ============================================================ -// ⚙️ 设置页面(含头像上传) +// ⚙️ 设置页面(含头像上传和恢复码管理) // ============================================================ async function renderSettingsPage() { @@ -530,6 +530,13 @@ async function renderSettingsPage() { const userPosts = await apiFetch('/posts?user_id=' + user.id); const postCount = userPosts.data ? userPosts.data.length : 0; + // 获取恢复码数量 + let recoveryCount = 0; + try { + const countData = await API.getRecoveryCodesCount(); + recoveryCount = countData.count || 0; + } catch (e) {} + container.innerHTML = `
@@ -562,6 +569,17 @@ async function renderSettingsPage() {
+ + +
+

🔑 恢复码

+

用于忘记密码时重置账户。每个恢复码只能使用一次。

+
+ + +
+
剩余 ${recoveryCount} 个可用恢复码
+
`; @@ -625,6 +643,7 @@ async function renderSettingsPage() { }); } + // 保存设置 document.getElementById('settingsSaveBtn').addEventListener('click', async function() { const username = document.getElementById('settingsUsername').value.trim(); const bio = document.getElementById('settingsBio').value.trim(); @@ -645,6 +664,39 @@ async function renderSettingsPage() { } }); + // 恢复码管理 + const viewBtn = document.getElementById('viewRecoveryCodesBtn'); + const regenBtn = document.getElementById('regenerateRecoveryCodesBtn'); + const statusText = document.getElementById('recoveryCodesStatus'); + + if (viewBtn) { + viewBtn.addEventListener('click', async function() { + try { + const data = await API.generateRecoveryCodes(); + showRecoveryCodesModal(data.codes); + // 更新状态 + const countData = await API.getRecoveryCodesCount(); + if (statusText) statusText.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码'; + } catch (err) { + alert('获取恢复码失败:' + err.message); + } + }); + } + + if (regenBtn) { + regenBtn.addEventListener('click', async function() { + if (!confirm('重新生成将替换所有旧的恢复码,确定继续吗?')) return; + try { + const data = await API.generateRecoveryCodes(); + showRecoveryCodesModal(data.codes); + const countData = await API.getRecoveryCodesCount(); + if (statusText) statusText.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码'; + } catch (err) { + alert('重新生成失败:' + err.message); + } + }); + } + } catch (err) { container.innerHTML = '
加载失败
'; } @@ -685,7 +737,6 @@ function openEditModal(postId, currentTitle, currentContent) { try { await API.updatePost(postId, title, content); modal.remove(); - // 刷新当前视图 if (currentPage === 'post') { renderPostDetail(currentPostId); } else { @@ -698,6 +749,73 @@ function openEditModal(postId, currentTitle, currentContent) { }); } +// ============================================================ +// 🔑 恢复码显示模态框 +// ============================================================ + +function showRecoveryCodesModal(codes) { + let modal = document.getElementById('recoveryCodesModal'); + if (!modal) { + modal = document.createElement('div'); + modal.id = 'recoveryCodesModal'; + modal.className = 'modal active'; + modal.style.display = 'flex'; + document.body.appendChild(modal); + } + + let codesHtml = ''; + codes.forEach((code, i) => { + codesHtml += ` +
+ ${String(i + 1).padStart(2, '0')}. + ${code} +
+ `; + }); + + modal.innerHTML = ` + + `; + + modal.style.display = 'flex'; + modal.classList.add('active'); + + document.getElementById('closeRecoveryCodesBtn').addEventListener('click', function() { + modal.remove(); + }); + + document.getElementById('copyRecoveryCodesBtn').addEventListener('click', function() { + const text = codes.join('\n'); + navigator.clipboard.writeText(text).then(() => { + document.getElementById('copyStatus').textContent = '✅ 已复制到剪贴板'; + }).catch(() => { + const textarea = document.createElement('textarea'); + textarea.value = text; + document.body.appendChild(textarea); + textarea.select(); + document.execCommand('copy'); + textarea.remove(); + document.getElementById('copyStatus').textContent = '✅ 已复制到剪贴板'; + }); + }); + + modal.addEventListener('click', function(e) { + if (e.target === this) modal.remove(); + }); +} + // ============================================================ // 🚀 初始化 // ============================================================ @@ -898,6 +1016,49 @@ async function init() { }); }); + // 忘记密码事件 + const forgotLink = document.getElementById('forgotPasswordLink'); + if (forgotLink) { + forgotLink.addEventListener('click', function(e) { + e.preventDefault(); + document.getElementById('forgotPasswordModal').classList.add('active'); + document.getElementById('resetStatus').textContent = ''; + }); + } + + document.getElementById('resetPasswordSubmit').addEventListener('click', async function() { + const email = document.getElementById('resetEmail').value.trim(); + const code = document.getElementById('resetRecoveryCode').value.trim().toUpperCase(); + const newPassword = document.getElementById('resetNewPassword').value; + const statusEl = document.getElementById('resetStatus'); + + if (!email || !code || !newPassword) { + statusEl.textContent = '请填写完整信息'; + statusEl.style.color = '#ef4444'; + return; + } + if (newPassword.length < 6) { + statusEl.textContent = '密码至少6位'; + statusEl.style.color = '#ef4444'; + return; + } + + try { + await API.resetPassword(email, code, newPassword); + statusEl.textContent = '✅ 重置成功!请登录'; + statusEl.style.color = '#22c55e'; + setTimeout(() => { + document.getElementById('forgotPasswordModal').classList.remove('active'); + document.getElementById('resetEmail').value = ''; + document.getElementById('resetRecoveryCode').value = ''; + document.getElementById('resetNewPassword').value = ''; + }, 1500); + } catch (err) { + statusEl.textContent = '❌ ' + err.message; + statusEl.style.color = '#ef4444'; + } + }); + window.addEventListener('popstate', function(e) { const state = e.state || {}; const page = state.page || 'feed'; From e7493446a706e4503dddbe2ead5fb63d259a7776 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:43:32 +0800 Subject: [PATCH 34/41] Update auth.js --- js/auth.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/js/auth.js b/js/auth.js index 89c8042..f30618d 100644 --- a/js/auth.js +++ b/js/auth.js @@ -48,7 +48,7 @@ document.getElementById('registerSubmit').addEventListener('click', async () => if (password.length < 6) { alert('密码至少6位'); return; } if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; } try { - await API.register(email, password, username); + const result = await API.register(email, password, username); document.getElementById('registerModal').classList.remove('active'); document.getElementById('regUsername').value = ''; document.getElementById('regEmail').value = ''; @@ -56,9 +56,20 @@ document.getElementById('registerSubmit').addEventListener('click', async () => document.getElementById('regCaptchaInput').value = ''; alert('注册成功!请登录'); - const result = await API.login(email, password); - if (result.user) { - currentUser = result.user; + // 生成恢复码 + try { + const recoveryData = await API.generateRecoveryCodes(); + if (recoveryData.codes) { + showRecoveryCodesModal(recoveryData.codes); + } + } catch (e) { + console.warn('恢复码生成失败:', e); + } + + const loginResult = await API.login(email, password); + if (loginResult.user) { + const profile = await AUTH.getUserProfile(loginResult.user.id); + currentUser = { ...loginResult.user, ...profile }; API.logEvent('register').catch(() => {}); renderNav(); if (currentPage === 'admin' && currentUser.role !== 'admin') { From 3f0e82f86440ae10f083021140baf8327a2f2bb7 Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:45:19 +0800 Subject: [PATCH 35/41] Update server.js --- server.js | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/server.js b/server.js index 8a27bad..8c653eb 100644 --- a/server.js +++ b/server.js @@ -1057,6 +1057,110 @@ app.put('/api/notifications/read-all', auth, async (req, res) => { } }); +// ============================================================ +// 恢复码系统(密码重置) +// ============================================================ + +// 生成随机恢复码 +function generateRecoveryCode() { + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + let code = ''; + for (let i = 0; i < 20; i++) { + code += chars[Math.floor(Math.random() * chars.length)]; + if (i === 4 || i === 9 || i === 14) code += '-'; + } + return code; +} + +// 生成 10 个恢复码 +app.post('/api/auth/recovery-codes/generate', auth, async (req, res) => { + try { + await pool.query('DELETE FROM recovery_codes WHERE user_id = $1', [req.user.id]); + + const codes = []; + const codeHashes = []; + for (let i = 0; i < 10; i++) { + const code = generateRecoveryCode(); + codes.push(code); + const hash = await bcrypt.hash(code, 10); + codeHashes.push(hash); + } + + for (const hash of codeHashes) { + await pool.query( + 'INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2)', + [req.user.id, hash] + ); + } + + res.json({ codes }); + } catch (err) { + res.status(500).json({ error: '生成恢复码失败' }); + } +}); + +// 获取当前可用的恢复码数量 +app.get('/api/auth/recovery-codes/count', auth, async (req, res) => { + try { + const r = await pool.query( + 'SELECT COUNT(*) FROM recovery_codes WHERE user_id = $1 AND is_used = false', + [req.user.id] + ); + res.json({ count: parseInt(r.rows[0].count) }); + } catch (err) { + res.status(500).json({ error: '服务器错误' }); + } +}); + +// 重置密码(使用恢复码) +app.post('/api/auth/reset-password', async (req, res) => { + const { email, recoveryCode, newPassword } = req.body; + + if (!email || !recoveryCode || !newPassword) { + return res.status(400).json({ error: '请填写完整信息' }); + } + if (newPassword.length < 6) { + return res.status(400).json({ error: '密码至少6位' }); + } + + try { + const user = await pool.query('SELECT id FROM users WHERE email = $1', [email]); + if (user.rows.length === 0) { + return res.status(404).json({ error: '用户不存在' }); + } + + const codes = await pool.query( + 'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false', + [user.rows[0].id] + ); + + let matched = false; + let matchedId = null; + + for (const row of codes.rows) { + const valid = await bcrypt.compare(recoveryCode, row.code_hash); + if (valid) { + matched = true; + matchedId = row.id; + break; + } + } + + if (!matched) { + return res.status(400).json({ error: '恢复码无效或已使用' }); + } + + await pool.query('UPDATE recovery_codes SET is_used = true WHERE id = $1', [matchedId]); + + const hash = await bcrypt.hash(newPassword, 10); + await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, user.rows[0].id]); + + res.json({ success: true }); + } catch (err) { + res.status(500).json({ error: '重置失败,请稍后重试' }); + } +}); + // ============================================================ // 托管前端文件 // ============================================================ From 6eb1673653ff089c1533c459f614fd291858a58f Mon Sep 17 00:00:00 2001 From: Furrium Network Date: Sun, 9 Aug 2026 23:47:26 +0800 Subject: [PATCH 36/41] Update index.html --- index.html | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index b058167..896708c 100644 --- a/index.html +++ b/index.html @@ -239,7 +239,10 @@

登录

- + +
@@ -283,6 +286,22 @@ + + +