added auth support
This commit is contained in:
parent
869be69d67
commit
f3dbaef776
7 changed files with 112 additions and 3 deletions
17
app/composables/$api.ts
Normal file
17
app/composables/$api.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
export const $api = <T>(
|
||||
path: string,
|
||||
options: Parameters<typeof $fetch<T>>[1] = {}
|
||||
) => {
|
||||
const config = useRuntimeConfig()
|
||||
const xsrfToken = useCookie('XSRF-TOKEN')
|
||||
|
||||
return $fetch<T>(path, {
|
||||
baseURL: config.public.apiBase,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(xsrfToken.value ? {'X-XSRF-TOKEN': xsrfToken.value} : {}),
|
||||
},
|
||||
...options,
|
||||
})
|
||||
}
|
||||
21
app/composables/useApiData.ts
Normal file
21
app/composables/useApiData.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
export const useApiData = <T>(
|
||||
url: string | Ref<string>,
|
||||
options: Parameters<typeof useFetch<T>>[1] = {}
|
||||
) => {
|
||||
const config = useRuntimeConfig()
|
||||
const xsrfToken = useCookie('XSRF-TOKEN')
|
||||
const requestHeaders = useRequestHeaders(['cookie'])
|
||||
|
||||
return useFetch<T>(url, {
|
||||
baseURL: config.public.apiBase,
|
||||
credentials: 'include',
|
||||
watch: false,
|
||||
server: false,
|
||||
headers: computed(() => ({
|
||||
Accept: 'application/json',
|
||||
...requestHeaders,
|
||||
...(xsrfToken.value ? {'X-XSRF-TOKEN': xsrfToken.value} : {}),
|
||||
})),
|
||||
...options,
|
||||
})
|
||||
}
|
||||
20
app/composables/useAuth.ts
Normal file
20
app/composables/useAuth.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
export const useAuth = () => {
|
||||
const config = useRuntimeConfig()
|
||||
const router = useRouter()
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
await $fetch('/sanctum/csrf-cookie', {
|
||||
baseURL: config.public.apiBase,
|
||||
credentials: 'include',
|
||||
})
|
||||
await $api('/api/login', {method: 'POST', body: {email, password}})
|
||||
await router.push('/')
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
await $api('/api/logout', {method: 'POST'})
|
||||
await router.push('/')
|
||||
}
|
||||
|
||||
return {login, logout}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue