diff --git a/src/components/layout/AppHeader.vue b/src/components/layout/AppHeader.vue index 414e90b..4375cf4 100644 --- a/src/components/layout/AppHeader.vue +++ b/src/components/layout/AppHeader.vue @@ -179,20 +179,21 @@ async function handleLogout() { - - + - 上传 - - + + 上传 + + - @@ -338,7 +340,7 @@ async function handleLogout() { 图鉴 { app.use(router) app.mount('#app') -} else { - authStore.initialize().then(() => { - app.use(router) - app.mount('#app') - }) -} +}) diff --git a/src/stores/auth.ts b/src/stores/auth.ts index 5bd1902..cc0fcab 100644 --- a/src/stores/auth.ts +++ b/src/stores/auth.ts @@ -12,12 +12,13 @@ export const useAuthStore = defineStore('auth', () => { const isLoggedIn = computed(() => !!user.value) const isAdmin = computed(() => profile.value?.role === 'admin') - async function fetchProfile() { - if (!user.value) return + async function fetchProfile(userId?: string) { + const id = userId ?? user.value?.id + if (!id) return const { data } = await supabase .from('profiles') .select('*') - .eq('id', user.value.id) + .eq('id', id) .single() if (data) { profile.value = data as Profile @@ -53,8 +54,8 @@ export const useAuthStore = defineStore('auth', () => { } throw error } + await fetchProfile(data.user.id) user.value = data.user - await fetchProfile() } async function register(email: string, password: string, username: string) { @@ -122,14 +123,21 @@ export const useAuthStore = defineStore('auth', () => { async function initialize() { const { data: { session } } = await supabase.auth.getSession() - user.value = session?.user ?? null - if (user.value) await fetchProfile() + const initialUser = session?.user ?? null + if (initialUser) await fetchProfile(initialUser.id) + user.value = initialUser loading.value = false supabase.auth.onAuthStateChange((_event, session) => { - user.value = session?.user ?? null - if (user.value) fetchProfile() - else profile.value = null + const nextUser = session?.user ?? null + if (nextUser) { + fetchProfile(nextUser.id).then(() => { + user.value = nextUser + }) + } else { + user.value = null + profile.value = null + } }) }