Files
zsglpt/templates/admin_login.html
2026-05-28 00:46:24 +08:00

747 lines
25 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>后台管理登录 - 知识管理平台</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
background: linear-gradient(135deg, #eef2ff 0%, #f6f7fb 45%, #ecfeff 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
position: relative;
overflow-x: hidden;
}
body::before {
content: '';
position: fixed;
inset: 0;
background:
radial-gradient(800px 500px at 15% 20%, rgba(59,130,246,.18), transparent 60%),
radial-gradient(700px 420px at 85% 70%, rgba(124,58,237,.16), transparent 55%);
pointer-events: none;
}
.login-container {
background: white;
border-radius: 16px;
box-shadow: 0 18px 60px rgba(17,24,39,0.15);
width: 420px;
padding: 38px 34px;
border: 1px solid rgba(17,24,39,0.08);
position: relative;
}
.login-header {
text-align: center;
margin-bottom: 30px;
}
.login-header h1 {
font-size: 24px;
color: #111827;
margin-bottom: 10px;
letter-spacing: 0.2px;
}
.login-header p {
color: #6b7280;
font-size: 14px;
}
.admin-badge {
display: inline-block;
background: rgba(59,130,246,0.10);
color: #1d4ed8;
padding: 6px 14px;
border-radius: 999px;
font-size: 12px;
font-weight: 700;
margin-bottom: 15px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
color: #111827;
font-weight: 700;
font-size: 13px;
}
.form-group input {
width: 100%;
padding: 12px;
border: 1px solid rgba(17,24,39,0.14);
border-radius: 10px;
font-size: 14px;
transition: border-color 0.2s, box-shadow 0.2s;
background: rgba(255,255,255,0.9);
}
.form-group input:focus {
outline: none;
border-color: rgba(59,130,246,0.7);
box-shadow: 0 0 0 4px rgba(59,130,246,0.16);
}
.btn-login {
width: 100%;
padding: 12px;
background: linear-gradient(135deg, #2563eb 0%, #7c3aed 100%);
color: white;
border: none;
border-radius: 10px;
font-size: 16px;
font-weight: 800;
cursor: pointer;
transition: transform 0.15s, filter 0.15s;
}
.btn-login:hover {
transform: translateY(-2px);
filter: brightness(1.02);
}
.btn-login:active {
transform: translateY(0);
}
.back-link {
text-align: center;
margin-top: 20px;
color: #6b7280;
}
.back-link a {
color: #2563eb;
text-decoration: none;
font-weight: 700;
}
.back-link a:hover {
text-decoration: underline;
}
.error-message {
background: rgba(239,68,68,0.10);
color: #b91c1c;
padding: 10px;
border-radius: 10px;
margin-bottom: 20px;
display: none;
border: 1px solid rgba(239,68,68,0.18);
}
.success-message {
background: rgba(16,185,129,0.10);
color: #047857;
padding: 10px;
border-radius: 10px;
margin-bottom: 20px;
display: none;
border: 1px solid rgba(16,185,129,0.18);
}
.warning-box {
background: rgba(245,158,11,0.10);
border: 1px solid rgba(245,158,11,0.18);
color: #92400e;
padding: 10px;
border-radius: 10px;
margin-bottom: 20px;
font-size: 13px;
}
.divider {
display: flex;
align-items: center;
gap: 12px;
color: #6b7280;
font-size: 12px;
font-weight: 700;
margin: 20px 0 14px;
}
.divider::before,
.divider::after {
content: '';
height: 1px;
flex: 1;
background: rgba(17,24,39,0.12);
}
.social-login-area {
display: none;
}
.social-buttons {
display: flex;
flex-direction: column;
gap: 8px;
}
.social-btn {
width: 100%;
height: 40px;
border-radius: 10px;
border: 1px solid rgba(17,24,39,0.14);
background: #fff;
color: #111827;
font-size: 13px;
font-weight: 800;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
transition: background 0.15s, border-color 0.15s;
}
.social-btn:hover:not(:disabled) {
background: #f8fafc;
border-color: rgba(37,99,235,0.32);
}
.social-btn:disabled {
cursor: not-allowed;
opacity: 0.7;
}
.social-icon {
width: 22px;
height: 22px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 12px;
line-height: 1;
}
.provider-wx .social-icon { background: #16a34a; }
.provider-qq .social-icon { background: #2563eb; }
.provider-alipay .social-icon { background: #1677ff; }
.qr-mask {
position: fixed;
inset: 0;
z-index: 20;
display: none;
align-items: center;
justify-content: center;
padding: 18px;
background: rgba(17,24,39,0.45);
}
.qr-dialog {
width: min(340px, 92vw);
border-radius: 14px;
background: #fff;
box-shadow: 0 24px 70px rgba(17,24,39,0.24);
padding: 20px;
}
.qr-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.qr-title {
font-size: 16px;
font-weight: 800;
color: #111827;
}
.qr-close {
width: 32px;
height: 32px;
border-radius: 50%;
border: 1px solid rgba(17,24,39,0.12);
background: #fff;
color: #4b5563;
cursor: pointer;
font-size: 18px;
line-height: 1;
}
.qr-body {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
}
.qr-image {
width: 220px;
height: 220px;
border: 1px solid rgba(17,24,39,0.10);
border-radius: 10px;
padding: 8px;
background: #fff;
}
.qr-prompt {
font-size: 13px;
color: #374151;
text-align: center;
}
@media (max-width: 480px) {
body { padding: 12px; align-items: flex-start; padding-top: 20px; }
.login-container { width: 100%; max-width: 100%; padding: 28px 20px; border-radius: 14px; }
.login-header h1 { font-size: 22px; }
.login-header p { font-size: 13px; }
.admin-badge { font-size: 11px; padding: 4px 12px; }
.form-group { margin-bottom: 18px; }
.form-group label { font-size: 13px; }
.form-group input { padding: 11px; font-size: 16px; } /* iOS防止自动缩放 */
.btn-login { padding: 13px; font-size: 15px; }
.back-link { margin-top: 16px; font-size: 14px; }
}
</style>
</head>
<body>
<div class="login-container">
<div class="login-header">
<span class="admin-badge">管理员登录</span>
<h1>后台管理系统</h1>
<p>知识管理平台</p>
</div>
<div id="errorMessage" class="error-message"></div>
<div id="successMessage" class="success-message"></div>
<form id="loginForm" method="POST" action="/yuyx/api/login" onsubmit="handleLogin(event)">
<div class="form-group">
<label for="username">管理员账号</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" id="password" name="password" required>
</div>
<div id="captchaGroup" class="form-group" style="display: none;">
<label for="captcha">验证码</label>
<div style="display: flex; gap: 10px; align-items: center;">
<input type="text" id="captcha" name="captcha" placeholder="请输入验证码" style="flex: 1;">
<img id="captchaImage" src="" alt="验证码" style="height: 50px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;" onclick="refreshCaptcha()" title="点击刷新">
<button type="button" onclick="refreshCaptcha()" style="padding: 8px 15px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">刷新</button>
</div>
</div>
<button type="submit" class="btn-login">登录后台</button>
</form>
<div id="socialLoginArea" class="social-login-area">
<div class="divider"><span>快捷登录</span></div>
<div id="socialButtons" class="social-buttons"></div>
</div>
<div class="back-link">
<a href="/">返回用户登录</a>
</div>
</div>
<div id="qrMask" class="qr-mask" onclick="handleQrMaskClick(event)">
<div class="qr-dialog" role="dialog" aria-modal="true" aria-labelledby="qrTitle">
<div class="qr-head">
<div id="qrTitle" class="qr-title">微信登录</div>
<button type="button" class="qr-close" onclick="closeQr()" aria-label="关闭">x</button>
</div>
<div class="qr-body">
<img id="qrImage" class="qr-image" alt="快捷登录二维码">
<div id="qrPrompt" class="qr-prompt">请使用微信扫描二维码点关注后登录</div>
</div>
</div>
</div>
<script>
let captchaSession = '';
let needCaptcha = false;
let socialProviders = [];
let socialLoadingProvider = '';
let pollTimer = null;
let pollStartedAt = 0;
const providerLabels = {
qq: 'QQ',
wx: '微信',
alipay: '支付宝'
};
const providerIcons = {
qq: 'Q',
wx: '微',
alipay: '支'
};
function getCookie(name) {
const escaped = String(name || '').replace(/([.*+?^${}()|[\]\\])/g, '\\$1');
const match = document.cookie.match(new RegExp(`(?:^|; )${escaped}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : '';
}
function jsonHeaders() {
const headers = { 'Content-Type': 'application/json' };
const csrfToken = getCookie('csrf_token');
if (csrfToken) {
headers['X-CSRF-Token'] = csrfToken;
}
return headers;
}
function showError(message) {
const errorDiv = document.getElementById('errorMessage');
const successDiv = document.getElementById('successMessage');
successDiv.style.display = 'none';
errorDiv.textContent = message || '操作失败';
errorDiv.style.display = 'block';
}
function showSuccess(message) {
const errorDiv = document.getElementById('errorMessage');
const successDiv = document.getElementById('successMessage');
errorDiv.style.display = 'none';
successDiv.textContent = message || '操作成功';
successDiv.style.display = 'block';
}
async function readJson(response) {
try {
return await response.json();
} catch (error) {
return {};
}
}
async function handleLogin(event) {
event.preventDefault();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
const captchaInput = document.getElementById('captcha');
const captcha = captchaInput ? captchaInput.value.trim() : '';
const errorDiv = document.getElementById('errorMessage');
const successDiv = document.getElementById('successMessage');
errorDiv.style.display = 'none';
successDiv.style.display = 'none';
if (!username || !password) {
errorDiv.textContent = '用户名和密码不能为空';
errorDiv.style.display = 'block';
return;
}
if (needCaptcha && !captcha) {
errorDiv.textContent = '请输入验证码';
errorDiv.style.display = 'block';
return;
}
try {
const response = await fetch('/yuyx/api/login', {
method: 'POST',
credentials: 'same-origin', // 确保发送和接收cookies
headers: jsonHeaders(),
body: JSON.stringify({
username: username,
password: password,
captcha_session: captchaSession,
captcha: captcha,
need_captcha: needCaptcha
})
});
const data = await response.json();
if (response.ok) {
successDiv.textContent = '登录成功,正在跳转...';
successDiv.style.display = 'block';
// 等待1秒确保cookie设置完成
await new Promise(resolve => setTimeout(resolve, 1000));
// 使用replace避免返回按钮回到登录页
window.location.replace(data.redirect || '/yuyx/admin');
} else {
errorDiv.textContent = data.error || '登录失败';
errorDiv.style.display = 'block';
if (data.need_captcha) {
needCaptcha = true;
document.getElementById('captchaGroup').style.display = 'block';
await generateCaptcha();
}
}
} catch (error) {
errorDiv.textContent = '网络错误,请稍后重试';
errorDiv.style.display = 'block';
}
}
async function generateCaptcha() {
try {
const response = await fetch('/api/generate_captcha', {
method: 'POST',
headers: jsonHeaders()
});
const data = await response.json();
if (data.session_id && data.captcha_image) {
captchaSession = data.session_id;
document.getElementById('captchaImage').src = data.captcha_image;
}
} catch (error) {
console.error('生成验证码失败:', error);
}
}
async function refreshCaptcha() {
await generateCaptcha();
document.getElementById('captcha').value = '';
}
function adminSocialRedirectUri() {
const url = new URL(window.location.href);
url.pathname = '/yuyx';
url.search = '';
url.hash = '';
return url.toString();
}
function qrPrompt(provider) {
if (provider === 'wx') return '请使用微信扫描二维码点关注后登录';
if (provider === 'qq') return '请使用 QQ 扫描二维码登录';
return '请使用支付宝扫描二维码登录';
}
function setSocialButtonsDisabled(disabled) {
document.querySelectorAll('.social-btn').forEach((btn) => {
btn.disabled = Boolean(disabled);
});
}
function renderSocialButtons() {
const area = document.getElementById('socialLoginArea');
const buttons = document.getElementById('socialButtons');
const visibleProviders = socialProviders.filter((provider) => providerLabels[provider]);
if (!visibleProviders.length) {
area.style.display = 'none';
buttons.innerHTML = '';
return;
}
area.style.display = 'block';
buttons.innerHTML = visibleProviders.map((provider) => {
const label = providerLabels[provider];
const icon = providerIcons[provider] || label.slice(0, 1);
return `
<button type="button" class="social-btn provider-${provider}" data-provider="${provider}">
<span class="social-icon">${icon}</span>
<span>${label}登录</span>
</button>
`;
}).join('');
buttons.querySelectorAll('.social-btn').forEach((button) => {
button.addEventListener('click', () => startSocialLogin(button.dataset.provider));
});
}
async function loadSocialConfig() {
try {
const response = await fetch('/api/auth/social/config', {
method: 'GET',
credentials: 'same-origin'
});
const data = await readJson(response);
socialProviders = response.ok && data.enabled && Array.isArray(data.providers) ? data.providers : [];
} catch (error) {
socialProviders = [];
}
renderSocialButtons();
}
function stopPolling() {
if (pollTimer) {
window.clearTimeout(pollTimer);
pollTimer = null;
}
}
function closeQr() {
stopPolling();
document.getElementById('qrMask').style.display = 'none';
document.getElementById('qrImage').removeAttribute('src');
}
function handleQrMaskClick(event) {
if (event.target && event.target.id === 'qrMask') {
closeQr();
}
}
function openQr(provider, value) {
document.getElementById('qrTitle').textContent = `${providerLabels[provider] || '快捷'}登录`;
document.getElementById('qrPrompt').textContent = qrPrompt(provider);
document.getElementById('qrImage').src = `/yuyx/api/admin-auth/social/qr?data=${encodeURIComponent(value)}`;
document.getElementById('qrMask').style.display = 'flex';
}
function schedulePoll(provider, state, intervalSeconds) {
stopPolling();
pollStartedAt = Date.now();
const tick = async () => {
if (Date.now() - pollStartedAt > 5 * 60 * 1000) {
closeQr();
showError('二维码已过期,请重新获取');
return;
}
try {
const response = await fetch('/yuyx/api/admin-auth/social/poll', {
method: 'POST',
credentials: 'same-origin',
headers: jsonHeaders(),
body: JSON.stringify({ provider, state })
});
const data = await readJson(response);
if (!response.ok) {
closeQr();
showError(data.error || data.message || '扫码状态获取失败,请重新尝试');
return;
}
if (data.status === 'authorized' && data.url) {
closeQr();
window.location.assign(data.url);
return;
}
pollTimer = window.setTimeout(tick, Math.max(Number(intervalSeconds || 2), 2) * 1000);
} catch (error) {
closeQr();
showError('扫码状态获取失败,请重新尝试');
}
};
pollTimer = window.setTimeout(tick, Math.max(Number(intervalSeconds || 2), 2) * 1000);
}
async function startSocialLogin(provider) {
if (!provider || socialLoadingProvider) return;
socialLoadingProvider = provider;
setSocialButtonsDisabled(true);
try {
const response = await fetch('/yuyx/api/admin-auth/social/login-url', {
method: 'POST',
credentials: 'same-origin',
headers: jsonHeaders(),
body: JSON.stringify({
provider,
redirect_uri: adminSocialRedirectUri()
})
});
const data = await readJson(response);
if (!response.ok) {
showError(data.error || data.message || '获取快捷登录地址失败');
return;
}
if (provider !== 'wx') {
window.location.assign(data.url);
return;
}
const value = data.scan_url || data.qrcode || data.url;
if (!value || !data.scan_state) {
showError('微信二维码获取失败');
return;
}
openQr(provider, value);
schedulePoll(provider, data.scan_state, data.scan_poll_interval || 2);
} catch (error) {
showError('获取快捷登录地址失败');
} finally {
socialLoadingProvider = '';
setSocialButtonsDisabled(false);
}
}
async function waitForAdminSession(maxAttempts = 8) {
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
try {
const response = await fetch('/yuyx/api/admin-auth/social/session', {
method: 'GET',
credentials: 'same-origin',
cache: 'no-store'
});
if (response.ok) {
return true;
}
} catch (error) {
// retry below
}
await new Promise((resolve) => setTimeout(resolve, 180 + attempt * 120));
}
return false;
}
async function handleSocialCallback() {
const params = new URLSearchParams(window.location.search || '');
const provider = String(params.get('provider') || params.get('type') || '').trim();
const code = String(params.get('code') || '').trim();
if (!provider || !code) return;
showSuccess('正在完成快捷登录...');
try {
const response = await fetch('/yuyx/api/admin-auth/social/callback', {
method: 'POST',
credentials: 'same-origin',
headers: jsonHeaders(),
body: JSON.stringify({ provider, code })
});
const data = await readJson(response);
if (!response.ok) {
showError(data.error || data.message || '快捷登录失败');
return;
}
showSuccess('登录成功,正在跳转...');
await waitForAdminSession();
window.location.replace(data.redirect || '/yuyx/admin');
} catch (error) {
showError('快捷登录失败');
}
}
document.addEventListener('DOMContentLoaded', () => {
const params = new URLSearchParams(window.location.search || '');
const hasSocialCallback = Boolean(
String(params.get('code') || '').trim()
&& String(params.get('provider') || params.get('type') || '').trim()
);
if (hasSocialCallback) {
handleSocialCallback();
return;
}
loadSocialConfig();
});
</script>
</body>
</html>