mandant-crm/frontend/composables/useAuth.ts

40 lines
978 B
TypeScript
Raw Normal View History

import type { User } from '~/types'
export const useAuth = () => {
const user = useState<User | null>('auth.user', () => null)
const getCsrfCookie = async () => {
await useApiFetch('/sanctum/csrf-cookie')
}
const fetchUser = async (): Promise<void> => {
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<void> => {
await getCsrfCookie()
await useApiFetch('/api/login', {
method: 'POST',
body: { email, password },
})
await fetchUser()
}
const logout = async (): Promise<void> => {
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 }
}