import type { User } from '~/types' export const useAuth = () => { const user = useState('auth.user', () => null) const getCsrfCookie = async () => { await $fetch('/sanctum/csrf-cookie', { credentials: 'include' }) } const getXsrfToken = (): string => { const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/) return match ? decodeURIComponent(match[1]) : '' } const fetchUser = async (): Promise => { try { const response = await $fetch<{ data: User }>('/api/user', { credentials: 'include', }) user.value = response.data } catch { user.value = null } } const login = async (email: string, password: string): Promise => { await getCsrfCookie() await $fetch('/api/login', { method: 'POST', body: { email, password }, credentials: 'include', headers: { 'X-XSRF-TOKEN': getXsrfToken() }, }) await fetchUser() } const logout = async (): Promise => { await $fetch('/api/logout', { method: 'POST', credentials: 'include', headers: { 'X-XSRF-TOKEN': getXsrfToken() }, }) user.value = null await navigateTo('/login') } return { user, login, logout, fetchUser } }