|
| 1 | +import type { User } from '@supabase/auth-js' |
| 2 | +import { UserApi } from '@widget-js/core' |
| 3 | +import consola from 'consola' |
| 4 | +import { computed, ref } from 'vue' |
| 5 | +import { supabase } from '@/api/supabase' |
| 6 | + |
| 7 | +const user = ref<User | null>(null) |
| 8 | + |
| 9 | +supabase.auth.onAuthStateChange((event, session) => { |
| 10 | + consola.info('onAuthStateChange', event, session) |
| 11 | + if (event === 'SIGNED_OUT') { |
| 12 | + user.value = null |
| 13 | + UserApi.logout() |
| 14 | + } |
| 15 | + else if (event === 'USER_UPDATED') { |
| 16 | + user.value = session!.user |
| 17 | + UserApi.updateUser(session!.user) |
| 18 | + } |
| 19 | + else if (event === 'SIGNED_IN') { |
| 20 | + user.value = session!.user |
| 21 | + supabase.auth.startAutoRefresh() |
| 22 | + UserApi.login(session!) |
| 23 | + } |
| 24 | + else if (event === 'TOKEN_REFRESHED') { |
| 25 | + UserApi.updateSession(session!) |
| 26 | + } |
| 27 | +}) |
| 28 | + |
| 29 | +export function useUser(onload?: (user?: User) => void) { |
| 30 | + const loading = ref(false) |
| 31 | + const nickname = computed(() => { |
| 32 | + if (user.value) { |
| 33 | + if (user.value.user_metadata.nickname) { |
| 34 | + return user.value.user_metadata.nickname |
| 35 | + } |
| 36 | + if (user.value.email) { |
| 37 | + return user.value.email.split('@')[0] |
| 38 | + } |
| 39 | + return 'User' |
| 40 | + } |
| 41 | + return '未登录' |
| 42 | + }) |
| 43 | + |
| 44 | + const userId = computed(() => { |
| 45 | + return user.value?.id || '' |
| 46 | + }) |
| 47 | + |
| 48 | + const avatar = computed(() => { |
| 49 | + return user.value?.user_metadata?.avatar || '' |
| 50 | + }) |
| 51 | + |
| 52 | + function refreshUser() { |
| 53 | + loading.value = true |
| 54 | + supabase.auth.getUser().then(({ data }) => { |
| 55 | + user.value = data.user |
| 56 | + onload?.(data.user || undefined) |
| 57 | + }).finally(() => { |
| 58 | + loading.value = false |
| 59 | + }) |
| 60 | + } |
| 61 | + |
| 62 | + refreshUser() |
| 63 | + return { user, refreshUser, loading, nickname, avatar, userId } |
| 64 | +} |
0 commit comments