useGoogleLogin.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. export function useGoogleLogin() {
  2. const loading = ref(false)
  3. const clientID = '482169597782-nic3d8bo67o0gmq93cmgao7050ets16n.apps.googleusercontent.com'
  4. onMounted(() => {
  5. const script = document.createElement('script')
  6. script.src = 'https://accounts.google.com/gsi/client'
  7. script.async = true
  8. script.defer = true
  9. document.head.appendChild(script)
  10. })
  11. /**
  12. * 初始化 Google Auth
  13. */
  14. function initializeGoogleAuth(resolve, reject) {
  15. return window.google.accounts.oauth2.initTokenClient({
  16. client_id: clientID,
  17. scope: 'email profile',
  18. callback: async (response) => {
  19. try {
  20. // 获取用户基本信息
  21. const userInfo = await fetchUserInfo(response.access_token)
  22. const res = {
  23. token: response.access_token,
  24. userInfo,
  25. }
  26. resolve(res)
  27. }
  28. catch (error) {
  29. reject(error)
  30. }
  31. },
  32. error_callback: (error) => {
  33. reject(error)
  34. },
  35. })
  36. }
  37. /**
  38. * 获取用户详细信息
  39. */
  40. async function fetchUserInfo(accessToken) {
  41. const res = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
  42. headers: {
  43. Authorization: `Bearer ${accessToken}`,
  44. },
  45. })
  46. if (!res.ok)
  47. throw new Error('获取用户信息失败')
  48. return await res.json()
  49. }
  50. // 触发登录
  51. function handleGoogleLogin() {
  52. return new Promise((resolve, reject) => {
  53. if (!window.google) {
  54. const t = setTimeout(() => {
  55. clearTimeout(t)
  56. ElMessage.error('当前环境不支持 Google 登录,请使用其他方式登录')
  57. reject(new Error('Google SDK not loaded'))
  58. }, 1000)
  59. return
  60. }
  61. const client = initializeGoogleAuth(resolve, reject)
  62. client.requestAccessToken()
  63. })
  64. }
  65. async function onGoogleLogin() {
  66. try {
  67. loading.value = true
  68. const result = await handleGoogleLogin()
  69. loading.value = false
  70. return result
  71. }
  72. catch (error) {
  73. loading.value = false
  74. }
  75. }
  76. return { loading, onGoogleLogin }
  77. }