ai-chatbot/public/dingtalk-callback.html
2026-05-23 10:57:26 +08:00

333 lines
13 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: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background:
linear-gradient(180deg, rgba(250, 250, 250, 0.96) 0%, rgba(255, 255, 255, 1) 52%),
radial-gradient(circle at top center, rgba(0, 145, 255, 0.08), transparent 38%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #171717;
letter-spacing: 0;
}
.container {
text-align: center;
padding: 36px 34px 32px;
background: #ffffff;
border-radius: 12px;
box-shadow:
rgba(0, 0, 0, 0.08) 0 0 0 1px,
rgba(0, 0, 0, 0.04) 0 2px 2px,
rgba(0, 0, 0, 0.04) 0 16px 32px -20px;
max-width: 420px;
width: 90%;
}
.brand-mark {
width: 42px;
height: 42px;
border-radius: 10px;
margin: 0 auto 22px;
display: flex;
align-items: center;
justify-content: center;
background: #171717;
color: #ffffff;
font-size: 18px;
font-weight: 700;
line-height: 1;
box-shadow: rgba(0, 0, 0, 0.08) 0 0 0 1px;
}
.loading-spinner {
width: 34px;
height: 34px;
border: 2px solid #ededed;
border-top-color: #171717;
border-radius: 50%;
animation: spin 0.9s linear infinite;
margin: 0 auto 18px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.status-text {
color: #171717;
font-size: 17px;
font-weight: 600;
line-height: 1.5;
margin-bottom: 8px;
}
.hint-text {
color: #666666;
font-size: 13px;
line-height: 1.7;
}
.status-row {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 18px;
padding: 5px 10px;
border-radius: 999px;
background: #f5f5f5;
color: #666666;
font-size: 12px;
line-height: 1.4;
box-shadow: rgb(235, 235, 235) 0 0 0 1px;
}
.status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: #0a72ef;
box-shadow: 0 0 0 4px rgba(10, 114, 239, 0.12);
}
.error-container {
display: none;
}
.error-title {
color: #b42318;
font-size: 15px;
font-weight: 500;
line-height: 1.7;
margin-bottom: 22px;
word-break: break-word;
}
.back-button {
min-height: 38px;
padding: 0 16px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
background: #171717;
color: #ffffff;
border: 0;
border-radius: 6px;
transition: background-color 0.18s ease, transform 0.18s ease;
}
.back-button:hover {
background: #000000;
transform: translateY(-1px);
}
.back-button:focus-visible {
outline: 2px solid #0a72ef;
outline-offset: 2px;
}
@media (max-width: 520px) {
body {
align-items: flex-start;
padding-top: 26vh;
}
.container {
padding: 32px 24px 28px;
width: calc(100% - 32px);
}
}
</style>
</head>
<body>
<div class="container">
<div id="loadingContainer">
<div class="brand-mark">AI</div>
<div class="loading-spinner"></div>
<p id="statusText" class="status-text">正在登录...</p>
<p class="hint-text">正在通过钉钉确认企业身份,完成后会自动回到工作台。</p>
<div class="status-row">
<span class="status-dot"></span>
安全连接已建立
</div>
</div>
<div id="errorContainer" class="error-container">
<div class="brand-mark">AI</div>
<p id="errorTitle" class="error-title"></p>
<button id="backButton" class="back-button">返回登录</button>
</div>
</div>
<script>
(function() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state') || 'default';
const loadingContainer = document.getElementById('loadingContainer');
const errorContainer = document.getElementById('errorContainer');
const statusText = document.getElementById('statusText');
const errorTitle = document.getElementById('errorTitle');
const backButton = document.getElementById('backButton');
console.log('[DingTalk Callback] Code:', code ? code.substring(0, 10) + '...' : 'null');
console.log('[DingTalk Callback] State:', state);
if (!code) {
showError('授权失败:缺少授权码');
return;
}
// 调用后端钉钉登录接口
login(code, state);
async function login(code, state) {
try {
statusText.textContent = '正在验证身份...';
const url = '/api/auth/dingtalk/callback?code=' + encodeURIComponent(code) + '&state=' + encodeURIComponent(state);
console.log('[DingTalk Callback] Calling:', url);
const response = await fetch(url, {
method: 'GET',
credentials: 'include'
});
console.log('[DingTalk Callback] Response status:', response.status);
const data = await response.json();
console.log('[DingTalk Callback] Response data:', data);
if (data.success) {
statusText.textContent = '授权成功,正在登录...';
console.log('[DingTalk Callback] Got token:', data.token.substring(0, 10) + '...');
// 直接在这里完成 Auth.js 登录
completeLogin(data.token, normalizeCallbackUrl(data.callbackUrl));
} else {
throw new Error(data.error || data.message || '登录失败');
}
} catch (error) {
console.error('[DingTalk Callback] Error:', error);
showError('登录失败:' + error.message);
}
}
function normalizeCallbackUrl(callbackUrl) {
if (typeof callbackUrl !== 'string' || !callbackUrl) return '/';
try {
const parsed = new URL(callbackUrl, window.location.origin);
if (parsed.origin !== window.location.origin) return '/';
return parsed.pathname + parsed.search + parsed.hash;
} catch (error) {
return '/';
}
}
async function completeLogin(token, callbackUrl) {
try {
statusText.textContent = '正在登录系统...';
// 获取 CSRF token
console.log('[DingTalk Callback] Getting CSRF token...');
const csrfRes = await fetch('/api/auth/csrf');
const { csrfToken } = await csrfRes.json();
console.log('[DingTalk Callback] Got CSRF token');
// 调用 Auth.js 登录
console.log('[DingTalk Callback] Calling Auth.js login...');
const loginRes = await fetch('/api/auth/callback/credentials', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
csrfToken: csrfToken,
token: token,
callbackUrl: callbackUrl,
}),
credentials: 'include',
});
console.log('[DingTalk Callback] Login response status:', loginRes.status);
if (loginRes.ok || loginRes.redirected) {
statusText.textContent = '登录成功,正在跳转...';
console.log('[DingTalk Callback] Login successful, redirecting to home...');
// 等待更长时间确保 cookie 被设置并同步
await new Promise(resolve => setTimeout(resolve, 800));
// 验证 session 是否已创建
const sessionRes = await fetch('/api/auth/session', {
credentials: 'include'
});
const session = await sessionRes.json();
console.log('[DingTalk Callback] Session after login:', session);
if (session && session.user) {
console.log('[DingTalk Callback] Session validated, redirecting...');
// 使用 window.top.location 确保跳转整个页面(即使在 iframe 中)
try {
if (window.top && window.top.location) {
window.top.location.replace(callbackUrl);
} else {
window.location.replace(callbackUrl);
}
} catch (e) {
// 如果跨域阻止,使用当前窗口跳转
console.warn('[DingTalk Callback] Cross-origin blocked, using current window');
window.location.replace(callbackUrl);
}
} else {
console.error('[DingTalk Callback] Session not created, retrying...');
// 如果 session 还未创建,再等待一段时间后重试
await new Promise(resolve => setTimeout(resolve, 500));
const retrySessionRes = await fetch('/api/auth/session', {
credentials: 'include'
});
const retrySession = await retrySessionRes.json();
if (retrySession && retrySession.user) {
window.location.replace(callbackUrl);
} else {
throw new Error('登录失败:无法创建会话,请刷新页面重试');
}
}
} else {
const result = await loginRes.json();
throw new Error(result.error || '登录失败');
}
} catch (error) {
console.error('[DingTalk Callback] Error:', error);
showError('登录失败:' + error.message);
}
}
function showError(message) {
loadingContainer.style.display = 'none';
errorTitle.textContent = message;
errorContainer.style.display = 'block';
// 通知父窗口登录失败
if (window.parent !== window) {
window.parent.postMessage({
type: 'dingtalk_login_error',
message: message
}, '*');
}
}
// 返回按钮事件
backButton.addEventListener('click', function() {
if (window.parent !== window) {
window.parent.postMessage({
type: 'dingtalk_login_error',
message: '用户取消登录'
}, '*');
} else {
window.location.href = '/login';
}
});
})();
</script>
</body>
</html>