## 新增功能 ### 消息通知中心 (全新模块) - 新增 MessageController / NotificationService / NotificationRepo - SSR 消息页面 (/messages):左侧边栏 + 右侧卡片列表,noindex 元标签 - 通知能力:列表分页、单条标为已读、一键全部标为已读 - 未读数角标 (1/66/99+):侧边栏 + 导航栏铃铛图标 - 导航栏轮询 /api/messages/unread 每 60 秒刷新未读数 - 审核通过/驳回时自动 fire-and-forget 推送通知 ### 密码修改 - ChangePassword:验证当前密码 → 新密码强度校验(8位+字母+数字) → 哈希更新 - 修改后递增 token_version 强制所有设备退登 ### 账号自助注销 - DeleteAccount:验证密码 → 设置 deleted 状态 → 记录原因 → 吊销 JWT - 注销后登录二次确认:Login 检测 deleted → 返回 confirm_restore - ConfirmRestore 恢复账号,重新签发 token - 注销页文案:"账号将在 7 天后正式注销,期间可随时重新登录恢复" ### IP 审计记录 - 注册时记录 RegIP,登录时记录 LastLoginIP + LastLoginAt - clientIP() 支持 X-Forwarded-For / X-Real-IP 反向代理 ### 安全加固 - Login 防时序攻击:用户不存在时仍执行完整 bcrypt 比对 - FindByEmail 改用 Unscoped() 覆盖软删除用户 - 站长 (owner) 不允许自主注销,避免权限体系死锁 ## Bug 修复 1. 注销按钮不触发:JS IIFE 中 profile 代码 return 阻塞了 account 标签页处理器注册 → 拆分为两层 IIFE,profile 放在内层 2. label 缺少 for 属性导致控制台警告 → 全部补充 for 属性 3. 注销后未自动退登:DeleteAccount 只设状态未吊销 JWT → 末尾加 InvalidateSessions 4. 退登后重定向 500 panic:authenticateToken 中 err||versionMismatch 合并判断 在 err=nil 但版本不匹配时返回 (nil,nil) → 拆为两个独立判断 injectUserContext 增加 claims==nil / 类型断言空安全守卫 5. 注销后登录直接提示"登录成功":FindByEmail 默认 scope 排除软删除记录 → 改用 Unscoped() ## 文件变更 - 新建 17 个文件 (消息/审核/站点设置完整模块) - 修改 25 个文件 (认证/设置/中间件/前端) - 统计:+3229 / -161,42 files changed
214 lines
8.4 KiB
JavaScript
214 lines
8.4 KiB
JavaScript
/* ============================================================
|
||
MetaLab Common JS — 全站共享脚本
|
||
============================================================ */
|
||
(function () {
|
||
'use strict';
|
||
|
||
// ---- Shared utils (exposed to other scripts via window.MetaLab) ----
|
||
window.MetaLab = window.MetaLab || {};
|
||
var toastTimer = null;
|
||
window.MetaLab.toast = function (el, msg, isError) {
|
||
if (!el) return;
|
||
clearTimeout(toastTimer);
|
||
el.textContent = msg;
|
||
el.className = 'toast' + (isError ? ' error' : '');
|
||
void el.offsetWidth;
|
||
el.classList.add('show');
|
||
toastTimer = setTimeout(function () {
|
||
el.classList.remove('show');
|
||
}, 3000);
|
||
};
|
||
|
||
// ---- CSRF token helper (从共享 utils.js 提供的 getCSRFToken 别名) ----
|
||
window.MetaLab.csrfToken = getCSRFToken;
|
||
|
||
// ---- Auto-attach X-CSRF-Token to all state-changing requests ----
|
||
// Monkey-patch XMLHttpRequest and fetch to inject CSRF header
|
||
(function () {
|
||
var token = window.MetaLab.csrfToken();
|
||
if (!token) return;
|
||
|
||
// Patch XMLHttpRequest (used by register.js / login.js / common.js)
|
||
var origXHROpen = XMLHttpRequest.prototype.open;
|
||
var origXHRSend = XMLHttpRequest.prototype.send;
|
||
XMLHttpRequest.prototype.open = function (method, url) {
|
||
this._method = method;
|
||
this._url = url;
|
||
return origXHROpen.apply(this, arguments);
|
||
};
|
||
var SAME_ORIGIN = /^\/(?!\/)/;
|
||
XMLHttpRequest.prototype.send = function () {
|
||
if (SAME_ORIGIN.test(this._url) &&
|
||
this._method && !/^(GET|HEAD|OPTIONS)$/i.test(this._method)) {
|
||
this.setRequestHeader('X-CSRF-Token', token);
|
||
}
|
||
return origXHRSend.apply(this, arguments);
|
||
};
|
||
|
||
// Patch fetch (used by auto-refresh)
|
||
var origFetch = window.fetch;
|
||
window.fetch = function (url, options) {
|
||
options = options || {};
|
||
var headers = options.headers || {};
|
||
var method = (options.method || 'GET').toUpperCase();
|
||
var urlStr = (typeof url === 'string') ? url : '';
|
||
if (SAME_ORIGIN.test(urlStr) && !/^(GET|HEAD|OPTIONS)$/i.test(method)) {
|
||
if (headers instanceof Headers) {
|
||
headers.set('X-CSRF-Token', token);
|
||
} else {
|
||
headers['X-CSRF-Token'] = token;
|
||
}
|
||
options.headers = headers;
|
||
}
|
||
return origFetch(url, options);
|
||
};
|
||
})();
|
||
|
||
var menuBtn = document.getElementById('mobileMenuBtn');
|
||
var navLinks = document.getElementById('navLinks');
|
||
var scrollBtn = document.getElementById('scrollTopBtn');
|
||
|
||
var menuIcon = '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>';
|
||
var closeIcon = '<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
|
||
|
||
// ---- Mobile menu toggle ----
|
||
if (menuBtn && navLinks) {
|
||
menuBtn.addEventListener('click', function () {
|
||
navLinks.classList.toggle('active');
|
||
menuBtn.innerHTML = navLinks.classList.contains('active') ? closeIcon : menuIcon;
|
||
});
|
||
}
|
||
|
||
// ---- Close mobile menu on nav click ----
|
||
var links = document.querySelectorAll('.nav-links a');
|
||
for (var i = 0; i < links.length; i++) {
|
||
links[i].addEventListener('click', function () {
|
||
if (navLinks) {
|
||
navLinks.classList.remove('active');
|
||
}
|
||
if (menuBtn) {
|
||
menuBtn.innerHTML = menuIcon;
|
||
}
|
||
});
|
||
}
|
||
|
||
// ---- Smooth scroll for anchor links ----
|
||
var anchors = document.querySelectorAll('a[href^="#"]');
|
||
for (var j = 0; j < anchors.length; j++) {
|
||
anchors[j].addEventListener('click', function (e) {
|
||
var href = this.getAttribute('href');
|
||
if (href === '#') return;
|
||
var target = document.querySelector(href);
|
||
if (target) {
|
||
e.preventDefault();
|
||
window.scrollTo({ top: target.offsetTop - 55, behavior: 'smooth' });
|
||
}
|
||
});
|
||
}
|
||
|
||
// ---- Scroll-to-top button ----
|
||
if (scrollBtn) {
|
||
window.addEventListener('scroll', function () {
|
||
scrollBtn.classList.toggle('visible', window.scrollY > window.innerHeight * 0.5);
|
||
});
|
||
scrollBtn.addEventListener('click', function () {
|
||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||
});
|
||
}
|
||
|
||
// ---- Dev greeting ----
|
||
console.log('%c🔨 嘿,开发者朋友!', 'color:#2ecc71;font-size:18px;font-weight:bold');
|
||
console.log('%c欢迎来到 MetaLab 的蓝图页。', 'color:#34495e');
|
||
console.log('%c我们正在搭建一个纯净、友好的下一代开发者社区。', 'color:#34495e');
|
||
console.log('%c有任何想法或愿意参与早期测试?欢迎联系我们:metazone@foxmail.com', 'color:#e74c3c;font-style:italic');
|
||
|
||
// ---- Logout ----
|
||
var logoutBtn = document.getElementById('logoutBtn');
|
||
if (logoutBtn) {
|
||
logoutBtn.addEventListener('click', function () {
|
||
var xhr = new XMLHttpRequest();
|
||
xhr.open('POST', '/api/auth/logout', true);
|
||
xhr.onreadystatechange = function () {
|
||
if (xhr.readyState === 4) {
|
||
window.location.href = '/';
|
||
}
|
||
};
|
||
xhr.send();
|
||
});
|
||
}
|
||
|
||
// ---- Unread message badge polling ----
|
||
var msgBadge = document.getElementById('msgBadge');
|
||
if (msgBadge) {
|
||
var POLL_INTERVAL = 60 * 1000; // 1 minute
|
||
function pollUnread() {
|
||
fetch('/api/messages/unread')
|
||
.then(function (res) {
|
||
if (!res.ok) return;
|
||
return res.json();
|
||
})
|
||
.then(function (data) {
|
||
if (!data || !data.success) return;
|
||
var count = data.data && data.data.unread ? data.data.unread : 0;
|
||
msgBadge.textContent = count > 99 ? '99+' : count;
|
||
msgBadge.style.display = count > 0 ? 'flex' : 'none';
|
||
})
|
||
.catch(function () {});
|
||
}
|
||
pollUnread();
|
||
setInterval(pollUnread, POLL_INTERVAL);
|
||
}
|
||
|
||
// ---- Auto-refresh token (silent) ----
|
||
// 场景 A:页面开着时,每 10 分钟静默续期(保持 access token 不过期)
|
||
// 场景 B:关浏览器 15+ min 后回来,access token 过期但 refresh 仍有效
|
||
// → 页面先渲染为未登录 → 刷新成功后 reload 一次获得登录态
|
||
// 不在认证页面执行刷新(登录/注册页无需续期)
|
||
var onAuthPage = /^\/auth\//.test(window.location.pathname);
|
||
if (!onAuthPage) {
|
||
|
||
var REFRESH_INTERVAL = 10 * 60 * 1000; // 10 minutes
|
||
var refreshTimer = null;
|
||
|
||
function tryRefresh(callback) {
|
||
fetch('/api/auth/refresh', { method: 'POST' })
|
||
.then(function (res) {
|
||
if (res.ok) {
|
||
if (callback) callback();
|
||
} else {
|
||
if (refreshTimer) {
|
||
clearInterval(refreshTimer);
|
||
refreshTimer = null;
|
||
}
|
||
}
|
||
})
|
||
.catch(function () {
|
||
if (refreshTimer) {
|
||
clearInterval(refreshTimer);
|
||
refreshTimer = null;
|
||
}
|
||
});
|
||
}
|
||
|
||
// 仅当存在"记住我"标记 Cookie 时才尝试刷新(避免无需刷新时产生 401 控制台报错)
|
||
function hasCookie(name) {
|
||
return document.cookie.split(';').some(function (c) {
|
||
return c.trim().startsWith(name + '=');
|
||
});
|
||
}
|
||
|
||
if (hasCookie('mlb_rm')) {
|
||
tryRefresh(function () {
|
||
refreshTimer = setInterval(function () { tryRefresh(null); }, REFRESH_INTERVAL);
|
||
|
||
if (!document.getElementById('logoutBtn') && !sessionStorage.getItem('mlb_refreshed')) {
|
||
sessionStorage.setItem('mlb_refreshed', '1');
|
||
window.location.reload();
|
||
}
|
||
});
|
||
sessionStorage.removeItem('mlb_refreshed');
|
||
}
|
||
|
||
} // end if (!onAuthPage)
|
||
})();
|