lovart3/public/dingtalk-callback.html
2025-12-25 23:08:33 +08:00

247 lines
10 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(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
}
.container {
text-align: center;
padding: 40px;
background: rgba(255, 255, 255, 0.1);
border-radius: 16px;
backdrop-filter: blur(10px);
max-width: 400px;
width: 90%;
}
.loading-spinner {
width: 50px;
height: 50px;
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid #fff;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.status-text {
font-size: 18px;
margin-bottom: 10px;
}
.error-container {
display: none;
}
.error-title {
font-size: 18px;
color: #ff6b6b;
margin-bottom: 20px;
word-break: break-word;
}
.back-button {
padding: 12px 24px;
font-size: 16px;
cursor: pointer;
background: rgba(255, 255, 255, 0.2);
color: white;
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 8px;
transition: all 0.3s ease;
header: 1px solid rgba(255, 255, 255, 0.3);
}
.back-button:hover {
background: rgba(255, 255, 255, 0.3);
}
</style>
</head>
<body>
<div class="container">
<div id="loadingContainer">
<div class="loading-spinner"></div>
<p id="statusText" class="status-text">正在登录...</p>
</div>
<div id="errorContainer" class="error-container">
<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);
} else {
throw new Error(data.error || data.message || '登录失败');
}
} catch (error) {
console.error('[DingTalk Callback] Error:', error);
showError('登录失败:' + error.message);
}
}
async function completeLogin(token) {
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: '/',
}),
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('/');
} else {
window.location.replace('/');
}
} catch (e) {
// 如果跨域阻止,使用当前窗口跳转
console.warn('[DingTalk Callback] Cross-origin blocked, using current window');
window.location.replace('/');
}
} 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('/');
} 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>