useAuth.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { storeToRefs } from 'pinia'
  2. import { useAuthStore } from '~/stores/auth'
  3. import { userApi } from '~/api/user'
  4. // Authentication composable for managing user auth state via Pinia
  5. export const useAuth = () => {
  6. const authStore = useAuthStore()
  7. const { isInitialized, isAuthenticated, isPlaymate, token, userProfile, wallet, playmateInfo } = storeToRefs(authStore)
  8. const restoreAuth = () => {
  9. authStore.restoreAuth()
  10. }
  11. const refreshAuth = async () => {
  12. try {
  13. await userApi.renewalToken()
  14. }
  15. catch (error) {
  16. console.error('Failed to refresh token:', error)
  17. throw error
  18. }
  19. }
  20. const refreshUser = async () => {
  21. try {
  22. const result = await userApi.getMyInfo()
  23. authStore.setUserProfile(result.userProfile)
  24. authStore.setWallet(result.wallet)
  25. }
  26. catch (error) {
  27. console.error('Failed to fetch user:', error)
  28. }
  29. }
  30. const refreshPlaymateInfo = async () => {
  31. if (!userProfile.value?.playmate || !userProfile.value?.userNo) return
  32. try {
  33. const result = await userApi.getPlaymateInfo(userProfile.value?.userNo)
  34. authStore.setPlaymateInfo(result)
  35. }
  36. catch (error) {
  37. console.error('Failed to fetch playmate info:', error)
  38. }
  39. }
  40. const login = async (type: 'google', googleData: string) => {
  41. try {
  42. const result = await userApi.loginWithGoogle({ data: googleData })
  43. if (result) {
  44. authStore.setAuth(result.token)
  45. authStore.setUserProfile(result.userProfile)
  46. authStore.setWallet(result.wallet)
  47. return result
  48. }
  49. return null
  50. }
  51. catch (error) {
  52. console.error('Failed to login:', error)
  53. return null
  54. }
  55. }
  56. const loginWithEmail = async (email: string) => {
  57. try {
  58. const result = await userApi.loginWithEmail(email)
  59. if (result) {
  60. authStore.setAuth(result.token)
  61. authStore.setUserProfile(result.userProfile)
  62. authStore.setWallet(result.wallet)
  63. return result
  64. }
  65. return null
  66. }
  67. catch (error) {
  68. console.error('Failed to login with email:', error)
  69. return null
  70. }
  71. }
  72. const logout = () => {
  73. authStore.logout()
  74. }
  75. return {
  76. isInitialized,
  77. isAuthenticated,
  78. isPlaymate,
  79. token,
  80. userProfile,
  81. wallet,
  82. playmateInfo,
  83. restoreAuth,
  84. refreshAuth,
  85. refreshUser,
  86. refreshPlaymateInfo,
  87. login,
  88. loginWithEmail,
  89. logout,
  90. }
  91. }