Files
bw-mini-app/src/platforms/h5/authorize.ts

48 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Authorize } from "../types/index";
import { useServerSdk } from "../../hooks/index";
export class H5Authorize extends Authorize {
async checkLogin(): Promise<boolean> {
// 检查URL中是否有OAuth回调参数
const urlParams = new URLSearchParams(window.location.search);
const accessToken = urlParams.get('access_token');
const userId = urlParams.get('user_id');
if (accessToken && userId) {
// 处理OAuth回调
try {
const serverSdk = useServerSdk();
serverSdk.setAccessToken(accessToken, userId);
// 清理URL参数避免重复处理
const newUrl = window.location.pathname;
window.history.replaceState(null, '', newUrl);
console.log('OAuth登录成功token已保存');
return true;
} catch (error) {
console.error('处理OAuth回调失败:', error);
return false;
}
}
// 如果没有回调参数检查本地存储的token
try {
const serverSdk = useServerSdk();
const profile = await serverSdk.profile();
return !!profile;
} catch (error) {
console.log('本地token无效或已过期');
return false;
}
}
async login(): Promise<void> {
const { hostname, protocol, port } = window.location;
let baseUrl = `${protocol}//${hostname}`
if (hostname === 'localhost') {
baseUrl = `${protocol}//${hostname}:${port}`
}
window.location.href = `https://api.bestaibest.ai/auth/google/authorize?redirect_url=${baseUrl}`
}
}