mirror of
https://github.com/Bubka/2FAuth.git
synced 2024-12-23 23:49:53 +01:00
Handle missing/invalid CSRF token & let 422 errors pass through
This commit is contained in:
parent
fe9002501b
commit
6769ab381b
52
resources/js_vue3/services/httpClientFactory.js
vendored
52
resources/js_vue3/services/httpClientFactory.js
vendored
@ -1,5 +1,6 @@
|
||||
import axios from "axios"
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { useNotifyStore } from '@/stores/notify'
|
||||
|
||||
export const httpClientFactory = (endpoint = 'api') => {
|
||||
let baseURL
|
||||
@ -16,22 +17,57 @@ export const httpClientFactory = (endpoint = 'api') => {
|
||||
withCredentials: true,
|
||||
})
|
||||
|
||||
// see https://github.com/fsgreco/vue3-laravel-api/blob/main/src/api/middlewareCSRF.js
|
||||
//httpClient.interceptors.request.use( middlewareCSRF, err => Promise.reject(err))
|
||||
// httpClient.interceptors.request.use(
|
||||
// async function (config) {
|
||||
// // We get a CSRF token when needed
|
||||
// const cookies = Object.fromEntries(document.cookie.split('; ').map(c => c.split('=')))
|
||||
// console.log(cookies)
|
||||
|
||||
// if (! Object.hasOwnProperty(cookies, 'XSRF-TOKEN') && ['post', 'put', 'patch', 'delete'].includes(config.method))
|
||||
// {
|
||||
// await axios.get('/refresh-csrf', {withCredentials:true})
|
||||
// return config
|
||||
// }
|
||||
|
||||
// return config
|
||||
// },
|
||||
// (error) => {
|
||||
// Promise.reject(error)
|
||||
// }
|
||||
// )
|
||||
|
||||
httpClient.interceptors.response.use(
|
||||
(response) => {
|
||||
return response;
|
||||
},
|
||||
function (error) {
|
||||
if (
|
||||
error.response &&
|
||||
[401, 419].includes(error.response.status)
|
||||
) {
|
||||
async function (error) {
|
||||
const originalRequestConfig = error.config
|
||||
|
||||
// Here we handle a missing/invalid CSRF cookie
|
||||
// We try to get a fresh on, but only once.
|
||||
if (error.response.status === 419 && ! originalRequestConfig._retried) {
|
||||
originalRequestConfig._retried = true;
|
||||
await axios.get('/refresh-csrf')
|
||||
return httpClient.request(originalRequestConfig)
|
||||
}
|
||||
|
||||
// Return the error when we need to handle it at component level
|
||||
if (error.config.hasOwnProperty('returnError') && error.config.returnError === true) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (error.response && [401].includes(error.response.status)) {
|
||||
const user = useUserStore()
|
||||
user.reset()
|
||||
}
|
||||
return Promise.reject(error);
|
||||
|
||||
// Always return the form validation errors
|
||||
if (error.response.status === 422) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
useNotifyStore().error(error)
|
||||
return new Promise(() => {})
|
||||
}
|
||||
)
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user