import type { User } from '~/types' export const useAuth = () => { const user = useState('auth.user', () => null) const getCsrfCookie = async () => { await useApiFetch('/sanctum/csrf-cookie') } const fetchUser = async (): Promise => { try { const response = await useApiFetch<{ data: User }>('/api/user') user.value = response.data } catch { user.value = null } } const login = async (email: string, password: string): Promise => { await getCsrfCookie() await useApiFetch('/api/login', { method: 'POST', body: { email, password }, }) await fetchUser() } const logout = async (): Promise => { try { await useApiFetch('/api/logout', { method: 'POST' }) } finally { // Always clear local state and leave, even if the request failed. user.value = null await navigateTo('/login') } } return { user, login, logout, fetchUser } }