feat(CSRF): Refresh Token on CSRF Error
parent
2191edf6bf
commit
b548676fd3
|
|
@ -9,6 +9,7 @@ export const $larafetch = $fetch.create({
|
||||||
async onRequest({ options }) {
|
async onRequest({ options }) {
|
||||||
const { backendUrl, frontendUrl } = useRuntimeConfig().public
|
const { backendUrl, frontendUrl } = useRuntimeConfig().public
|
||||||
const event = process.nitro ? useEvent() : null
|
const event = process.nitro ? useEvent() : null
|
||||||
|
|
||||||
let token = event
|
let token = event
|
||||||
? parseCookies(event)[CSRF_COOKIE]
|
? parseCookies(event)[CSRF_COOKIE]
|
||||||
: useCookie(CSRF_COOKIE).value
|
: useCookie(CSRF_COOKIE).value
|
||||||
|
|
@ -46,17 +47,23 @@ export const $larafetch = $fetch.create({
|
||||||
},
|
},
|
||||||
async onResponseError({ response }) {
|
async onResponseError({ response }) {
|
||||||
const status = response.status
|
const status = response.status
|
||||||
|
|
||||||
|
if (status === 419) {
|
||||||
|
await initCsrf(true)
|
||||||
|
}
|
||||||
if ([500].includes(status)) {
|
if ([500].includes(status)) {
|
||||||
console.error('[Laravel Error]', response.statusText, response._data)
|
console.error('[Laravel Error]', response.statusText, response._data)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
async function initCsrf() {
|
async function initCsrf(forceRefresh = false) {
|
||||||
const { backendUrl } = useRuntimeConfig().public
|
const { backendUrl } = useRuntimeConfig().public
|
||||||
const existingToken = useCookie(CSRF_COOKIE).value
|
const existingToken = useCookie(CSRF_COOKIE).value
|
||||||
|
|
||||||
if (existingToken) { return existingToken }
|
if (existingToken && !forceRefresh) {
|
||||||
|
return existingToken
|
||||||
|
}
|
||||||
|
|
||||||
await $fetch('/sanctum/csrf-cookie', {
|
await $fetch('/sanctum/csrf-cookie', {
|
||||||
baseURL: backendUrl,
|
baseURL: backendUrl,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue