88 lines
2.3 KiB
TypeScript
88 lines
2.3 KiB
TypeScript
import { useServerSdk } from '../hooks/index';
|
||
|
||
/**
|
||
* H5版本的Google OAuth鉴权服务
|
||
*/
|
||
export class AuthService {
|
||
/**
|
||
* 检查用户登录状态
|
||
* 包括处理OAuth回调和验证本地token
|
||
*/
|
||
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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 跳转到Google OAuth登录页面
|
||
*/
|
||
async login(redirectPath?: string): Promise<void> {
|
||
const { hostname, protocol, port } = window.location;
|
||
let baseUrl = `${protocol}//${hostname}`;
|
||
if (hostname === 'localhost') {
|
||
baseUrl = `${protocol}//${hostname}:${port}`;
|
||
}
|
||
const redirectUrl = `https://mixvideo-workflow.bowong.cc/auth/google/authorize?redirect_url=${baseUrl}${redirectPath || ''}`;
|
||
window.location.href = redirectUrl;
|
||
}
|
||
|
||
/**
|
||
* 登出用户
|
||
*/
|
||
async logout(): Promise<void> {
|
||
try {
|
||
const serverSdk = useServerSdk();
|
||
serverSdk.clearAccessToken();
|
||
console.log('用户已登出');
|
||
} catch (error) {
|
||
console.error('登出失败:', error);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取用户信息
|
||
*/
|
||
async getUserInfo() {
|
||
try {
|
||
const serverSdk = useServerSdk();
|
||
return await serverSdk.profile();
|
||
} catch (error) {
|
||
console.error('获取用户信息失败:', error);
|
||
return null;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 导出单例实例
|
||
export const authService = new AuthService();
|