初始化项目:基础设施 + 用户认证 + 后台管理系统 + AGPL 3.0 许可

This commit is contained in:
2026-05-26 13:46:33 +08:00
parent 1315df6501
commit 483fdd919f
56 changed files with 5804 additions and 40 deletions

View File

@ -0,0 +1,194 @@
/* ============================================================
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 (reads from <meta> tag rendered by server) ----
window.MetaLab.csrfToken = function () {
var meta = document.querySelector('meta[name="csrf-token"]');
return meta ? meta.getAttribute('content') : '';
};
// ---- 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();
});
}
// ---- 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)
})();

View File

@ -0,0 +1,80 @@
/* ============================================================
MetaLab Login JS — 登录页面专属脚本
============================================================ */
(function () {
'use strict';
var loginForm = document.getElementById('loginForm');
var emailInput = document.getElementById('email');
var passwordInput = document.getElementById('password');
var rememberMeCheckbox = document.getElementById('rememberMe');
var emailError = document.getElementById('emailError');
var passwordError = document.getElementById('passwordError');
var submitBtn = document.getElementById('submitBtn');
var toast = document.getElementById('toast');
if (!loginForm) return;
function checkFormValidity() {
var email = emailInput.value.trim();
var password = passwordInput.value;
submitBtn.disabled = !(email && password);
}
emailInput.addEventListener('input', function () {
var v = emailInput.value.trim();
if (v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) {
emailInput.classList.add('error');
emailError.style.display = 'block';
} else {
emailInput.classList.remove('error');
emailError.style.display = 'none';
}
checkFormValidity();
});
passwordInput.addEventListener('input', checkFormValidity);
loginForm.addEventListener('submit', function (e) {
e.preventDefault();
var email = emailInput.value.trim();
var password = passwordInput.value;
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
emailInput.classList.add('error');
emailError.style.display = 'block';
return;
}
if (!password) {
passwordInput.classList.add('error');
passwordError.style.display = 'block';
return;
}
doLogin(email, password);
});
function doLogin(email, password) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/auth/login', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var resp;
try { resp = JSON.parse(xhr.responseText); } catch (err) { resp = null; }
if (xhr.status === 200 && resp && resp.success) {
window.MetaLab.toast(toast, '登录成功', false);
setTimeout(function () {
window.location.href = '/';
}, 800);
} else {
var msg = (resp && resp.message) ? resp.message : '登录失败,请稍后重试';
window.MetaLab.toast(toast, msg, true);
}
}
};
xhr.send(JSON.stringify({ email: email, password: password, remember_me: rememberMeCheckbox.checked }));
}
})();

View File

@ -0,0 +1,305 @@
/* ============================================================
MetaLab Register JS — 注册页面专属脚本
============================================================ */
(function () {
'use strict';
// ---- DOM refs ----
var openGuidelines = document.getElementById('openGuidelines');
var modalOverlay = document.getElementById('modalOverlay');
var modalBody = document.getElementById('modalBody');
var modalClose = document.getElementById('modalClose');
var modalEnforce = document.getElementById('modalEnforce');
var confirmBtn = document.getElementById('confirmBtn');
var previewCloseBtn = document.getElementById('previewCloseBtn');
var timerCount = document.getElementById('timerCount');
var timerLabel = document.getElementById('timerLabel');
var timerUnit = document.getElementById('timerUnit');
var timerDone = document.getElementById('timerDone');
var timer = document.getElementById('timer');
var scrollHint = document.getElementById('scrollHint');
var submitBtn = document.getElementById('submitBtn');
var registerForm = document.getElementById('registerForm');
var toast = document.getElementById('toast');
var emailInput = document.getElementById('email');
var passwordInput = document.getElementById('password');
var confirmPasswordInput = document.getElementById('confirmPassword');
var rememberMeCheckbox = document.getElementById('rememberMe');
var emailError = document.getElementById('emailError');
var passwordError = document.getElementById('passwordError');
var confirmPasswordError = document.getElementById('confirmPasswordError');
// Guard: exit if not on auth page
if (!registerForm) return;
var countdown = 60;
var timerInterval = null;
var reachedBottom = false;
var agreed = false;
var isRegistrationMode = false;
var countdownPaused = false;
// ---- Modal Open ----
function openModal(onAgreed) {
isRegistrationMode = typeof onAgreed === 'function';
clearInterval(timerInterval);
countdown = 60;
reachedBottom = false;
agreed = false;
modalBody.scrollTop = 0;
modalOverlay.classList.add('active');
modalOverlay._onAgreed = isRegistrationMode ? onAgreed : null;
if (isRegistrationMode) {
modalEnforce.style.display = '';
confirmBtn.style.display = '';
previewCloseBtn.style.display = 'none';
timerCount.textContent = '60';
timerLabel.style.display = '';
timerCount.style.display = '';
timerUnit.style.display = '';
timerDone.style.display = 'none';
timer.classList.remove('done');
countdownPaused = false;
confirmBtn.disabled = true;
scrollHint.style.display = 'flex';
scrollHint.textContent = '▼ 请滚动至底部完成阅读';
scrollHint.style.color = 'var(--color-danger)';
startCountdown();
} else {
modalEnforce.style.display = 'none';
confirmBtn.style.display = 'none';
previewCloseBtn.style.display = '';
}
}
// ---- Countdown ----
function startCountdown() {
timerInterval = setInterval(function () {
if (countdownPaused) return;
countdown--;
timerCount.textContent = countdown;
if (countdown <= 0) {
clearInterval(timerInterval);
timerLabel.style.display = 'none';
timerCount.style.display = 'none';
timerUnit.style.display = 'none';
timerDone.style.display = '';
timer.classList.add('done');
scrollHint.textContent = '▼ 请滚动至底部完成阅读';
updateConfirmState();
}
}, 1000);
}
// ---- Scroll Detection ----
modalBody.addEventListener('scroll', function () {
if (reachedBottom) return;
if (modalBody.scrollTop + modalBody.clientHeight >= modalBody.scrollHeight - 5) {
reachedBottom = true;
scrollHint.textContent = '✓ 已阅读至底部';
scrollHint.style.color = '#27ae60';
updateConfirmState();
}
});
// ---- Pause countdown on tab/window inactive ----
document.addEventListener('visibilitychange', function () {
if (!isRegistrationMode) return;
countdownPaused = document.hidden;
});
window.addEventListener('blur', function () {
if (isRegistrationMode) countdownPaused = true;
});
window.addEventListener('focus', function () {
if (isRegistrationMode) countdownPaused = false;
});
// ---- Update Confirm Button ----
function updateConfirmState() {
if (countdown <= 0 && reachedBottom) {
confirmBtn.disabled = false;
scrollHint.style.display = 'none';
}
}
// ---- Confirm (agree to guidelines) ----
confirmBtn.addEventListener('click', function () {
agreed = true;
modalOverlay.classList.remove('active');
if (modalOverlay._onAgreed) {
modalOverlay._onAgreed();
modalOverlay._onAgreed = null;
}
});
// ---- Close Modal ----
modalClose.addEventListener('click', function () {
modalOverlay.classList.remove('active');
});
previewCloseBtn.addEventListener('click', function () {
modalOverlay.classList.remove('active');
});
modalOverlay.addEventListener('click', function (e) {
if (e.target === modalOverlay) {
modalOverlay.classList.remove('active');
}
});
// ---- Open Guidelines Link (preview only) ----
openGuidelines.addEventListener('click', function (e) {
e.preventDefault();
openModal(null);
});
// ---- Form Validation ----
function checkFormValidity() {
var email = emailInput.value.trim();
var password = passwordInput.value;
var confirm = confirmPasswordInput.value;
var emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
var passwordValid = password.length >= 8 && /[a-zA-Z]/.test(password) && /\d/.test(password);
var confirmValid = passwordValid && confirm === password;
submitBtn.disabled = !(emailValid && passwordValid && confirmValid);
}
emailInput.addEventListener('input', function () {
var v = emailInput.value.trim();
if (v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) {
emailInput.classList.add('error');
emailError.style.display = 'block';
} else {
emailInput.classList.remove('error');
emailError.style.display = 'none';
}
checkFormValidity();
});
passwordInput.addEventListener('input', function () {
var v = passwordInput.value;
if (v && (v.length < 8 || !/[a-zA-Z]/.test(v) || !/\d/.test(v))) {
passwordInput.classList.add('error');
passwordError.style.display = 'block';
} else {
passwordInput.classList.remove('error');
passwordError.style.display = 'none';
}
if (confirmPasswordInput.value) {
validateConfirmPassword();
}
checkFormValidity();
});
confirmPasswordInput.addEventListener('input', function () {
validateConfirmPassword();
checkFormValidity();
});
function validateConfirmPassword() {
var confirm = confirmPasswordInput.value;
var password = passwordInput.value;
if (confirm && confirm !== password) {
confirmPasswordInput.classList.add('error');
confirmPasswordError.style.display = 'block';
} else {
confirmPasswordInput.classList.remove('error');
confirmPasswordError.style.display = 'none';
}
}
// ---- Form Submit: validate → check email → open guidelines → on agree → submit ----
registerForm.addEventListener('submit', function (e) {
e.preventDefault();
var email = emailInput.value.trim();
var password = passwordInput.value;
var confirm = confirmPasswordInput.value;
// Client-side validation
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
emailInput.classList.add('error');
emailError.style.display = 'block';
return;
}
if (password.length < 8 || !/[a-zA-Z]/.test(password) || !/\d/.test(password)) {
passwordInput.classList.add('error');
passwordError.style.display = 'block';
return;
}
if (confirm !== password) {
confirmPasswordInput.classList.add('error');
confirmPasswordError.style.display = 'block';
return;
}
// Disable submit to prevent double-click
submitBtn.disabled = true;
submitBtn.textContent = '检查中...';
// Step 1: Check if email already registered (before showing 60s guidelines)
var checkXhr = new XMLHttpRequest();
checkXhr.open('POST', '/api/auth/check-email', true);
checkXhr.setRequestHeader('Content-Type', 'application/json');
checkXhr.onreadystatechange = function () {
if (checkXhr.readyState !== 4) return;
submitBtn.disabled = true; // will be re-enabled by checkFormValidity if needed
var resp;
try { resp = JSON.parse(checkXhr.responseText); } catch (err) { resp = null; }
if (checkXhr.status === 200 && resp && resp.success) {
if (resp.data && resp.data.exists) {
// Already registered → notify user immediately, skip guidelines
window.MetaLab.toast(toast, '该邮箱已注册,请直接登录', true);
submitBtn.textContent = '注 册';
submitBtn.disabled = false;
} else {
// Not registered → proceed to guidelines modal
submitBtn.textContent = '注 册';
openModal(function () {
doRegister(email, password, confirm);
});
}
} else {
// API error → show message, don't block
var msg = (resp && resp.message) ? resp.message : '网络异常,请稍后重试';
window.MetaLab.toast(toast, msg, true);
submitBtn.textContent = '注 册';
submitBtn.disabled = false;
}
};
checkXhr.send(JSON.stringify({ email: email }));
});
// ---- AJAX Register ----
function doRegister(email, password, confirmPassword) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/auth/register', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var resp;
try { resp = JSON.parse(xhr.responseText); } catch (err) { resp = null; }
if (xhr.status === 200 && resp && resp.success) {
window.MetaLab.toast(toast, '🎉 注册成功!欢迎加入 MetaLab', false);
// Token 已通过 HttpOnly Cookie 自动设置JS 无需处理
// 注册即登录,跳转首页
setTimeout(function () {
window.location.href = '/';
}, 1500);
} else {
var msg = (resp && resp.message) ? resp.message : '注册失败,请稍后重试';
window.MetaLab.toast(toast, msg, true);
}
}
};
xhr.send(JSON.stringify({
email: email,
password: password,
confirm_password: confirmPassword,
remember_me: rememberMeCheckbox.checked
}));
}
})();