| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- import { storeToRefs } from 'pinia'
- import { useAuthStore } from '~/stores/auth'
- import { userApi } from '~/api/user'
- // Authentication composable for managing user auth state via Pinia
- export const useAuth = () => {
- const authStore = useAuthStore()
- const { isInitialized, isAuthenticated, isPlaymate, token, userProfile, wallet, playmateInfo } = storeToRefs(authStore)
- const restoreAuth = () => {
- authStore.restoreAuth()
- }
- const refreshAuth = async () => {
- try {
- await userApi.renewalToken()
- }
- catch (error) {
- console.error('Failed to refresh token:', error)
- throw error
- }
- }
- const refreshUser = async () => {
- try {
- const result = await userApi.getMyInfo()
- authStore.setUserProfile(result.userProfile)
- authStore.setWallet(result.wallet)
- }
- catch (error) {
- console.error('Failed to fetch user:', error)
- }
- }
- const refreshPlaymateInfo = async () => {
- if (!userProfile.value?.playmate || !userProfile.value?.userNo) return
- try {
- const result = await userApi.getPlaymateInfo(userProfile.value?.userNo)
- authStore.setPlaymateInfo(result)
- }
- catch (error) {
- console.error('Failed to fetch playmate info:', error)
- }
- }
- const login = async (type: 'google', googleData: string) => {
- try {
- const result = await userApi.loginWithGoogle({ data: googleData })
- if (result) {
- authStore.setAuth(result.token)
- authStore.setUserProfile(result.userProfile)
- authStore.setWallet(result.wallet)
- return result
- }
- return null
- }
- catch (error) {
- console.error('Failed to login:', error)
- return null
- }
- }
- const loginWithEmail = async (email: string) => {
- try {
- const result = await userApi.loginWithEmail(email)
- if (result) {
- authStore.setAuth(result.token)
- authStore.setUserProfile(result.userProfile)
- authStore.setWallet(result.wallet)
- return result
- }
- return null
- }
- catch (error) {
- console.error('Failed to login with email:', error)
- return null
- }
- }
- const logout = () => {
- authStore.logout()
- }
- return {
- isInitialized,
- isAuthenticated,
- isPlaymate,
- token,
- userProfile,
- wallet,
- playmateInfo,
- restoreAuth,
- refreshAuth,
- refreshUser,
- refreshPlaymateInfo,
- login,
- loginWithEmail,
- logout,
- }
- }
|