import { computed, ref, watch } from 'vue' import { storeToRefs } from 'pinia' import { useAuthStore, type AuthUser } from '~/stores/auth' import type { AuthClient, AuthMode } from '~/types/auth' function normalizeAuthMode(value: string | undefined): AuthMode { if (value === 'mock' || value === 'userinfo') { return value } return 'disabled' } function createMockUser(): AuthUser { return { id: 'mock-user', email: 'mock@example.com', firstName: 'Mock', lastName: 'User', roles: ['USER'] } } function canUseWindow() { return typeof window !== 'undefined' } export default defineNuxtPlugin(() => { const runtimeConfig = useRuntimeConfig() const authStore = useAuthStore() const { isAuthenticated, isInitialized, user } = storeToRefs(authStore) const mode = normalizeAuthMode(runtimeConfig.public.authMode) const ready = ref(false) const initialize = async () => { if (ready.value) { return } if (mode === 'disabled') { authStore.initialize(null) ready.value = true return } if (mode === 'mock') { authStore.initialize(createMockUser()) ready.value = true return } try { const authUser = await $fetch(runtimeConfig.public.authUserinfoUrl, { credentials: 'include' }) authStore.initialize(authUser) } catch { authStore.initialize(null) } ready.value = true } watch( isInitialized, (value) => { if (value) { ready.value = true } }, { immediate: true } ) const login = () => { if (mode === 'disabled') { return } if (mode === 'mock') { authStore.setUser(createMockUser()) return } if (canUseWindow()) { window.location.href = runtimeConfig.public.authLoginUrl } } const logout = () => { authStore.clearSession() if (mode === 'disabled') { return } if (mode === 'mock') { return } if (canUseWindow()) { window.location.href = runtimeConfig.public.authLogoutUrl } } const auth: AuthClient = { mode, isEnabled: mode !== 'disabled', isReady: ready, isAuthenticated: computed(() => isAuthenticated.value), user, ensureInitialized: initialize, login, logout } return { provide: { auth } } })