2025-02-27 00:38:36 +08:00

75 lines
2.0 KiB
TypeScript

import { WxServices } from '@/routes/wx/services.ts'
import { simple } from './simple.ts'
export const createLoginHtml = (wxService: WxServices) => {
const redirectUrl = wxService.isNew ? '/user/info' : '/'
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wx Login</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#loading {
font-size: 1.2rem;
color: #555;
}
</style>
</head>
<body>
<div>Login Success</div>
<div id="loading">Redirecting, please wait...</div>
<script>
(function() {
// Save the token to localStorage
localStorage.setItem('token', '${wxService.webToken}');
// Redirect after 2 seconds
setTimeout(() => {
window.location.href = '${redirectUrl}';
}, 2000);
})();
</script>
</body>
</html>
`
}
simple.get('/api/wx/login', async (req, res) => {
try {
const url = req.url
const query = new URLSearchParams(url.split('?')[1])
const code = query.get('code')
const state = query.get('state')
if (!code) {
res.end('code is required')
return
}
const wxService = new WxServices()
await wxService.login(code)
if (wxService.isNew) {
await wxService.getUserInfo()
}
res.setHeader('Content-Type', 'text/html')
res.end(createLoginHtml(wxService))
} catch (e) {
console.error(e)
res.end('error')
}
})
simple.get('/api/wx/on-ai/login', async (req, res) => {
const url = req.url
const query = new URLSearchParams(url.split('?')[1])
const code = query.get('code')
const state = query.get('state')
const onAIBaseUrl = 'https://note.on-ai.ai'
const newUrl = `${onAIBaseUrl}/api/wx/login?code=${code}&state=${state}`
res.setHeader('Content-Type', 'text/html')
res.end(`<script>window.location.href='${newUrl}'</script>`)
})