-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
created new csrf plugin and use it into initialSetup
- Loading branch information
1 parent
1642323
commit 1ca0237
Showing
3 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { ref } from 'vue'; | ||
import { defineNuxtPlugin } from '#imports'; | ||
|
||
export default defineNuxtPlugin((nuxt) => { | ||
const CSRFtoken = ref(''); | ||
|
||
const getCSRFToken = () => CSRFtoken.value; | ||
|
||
const updateCSRFToken = (token) => { | ||
CSRFtoken.value = token; | ||
}; | ||
|
||
const attachCSRFToForm = () => { | ||
const forms = document.querySelectorAll('form'); | ||
forms.forEach((form) => { | ||
const csrfInput = document.createElement('input'); | ||
csrfInput.type = 'hidden'; | ||
csrfInput.name = 'csrf_token'; | ||
csrfInput.value = CSRFtoken.value; | ||
form.append(csrfInput); | ||
}); | ||
}; | ||
|
||
const csrfRef = { | ||
token: CSRFtoken, | ||
getCSRFToken, | ||
updateCSRFToken, | ||
attachCSRFToForm, | ||
}; | ||
|
||
// Store the original fetch function | ||
const originalFetch = window.fetch; | ||
|
||
// Override the fetch function | ||
window.fetch = async (url, options = {}) => { | ||
if (['POST', 'PUT', 'DELETE'].includes(options.method.toUpperCase())) { | ||
options.headers = options.headers || {}; | ||
options.headers['X-CSRF-Token'] = CSRFtoken.value; | ||
} | ||
return originalFetch(url, options); | ||
}; | ||
|
||
// Register the global property | ||
nuxt.provide('$csrf', csrfRef); | ||
|
||
return csrfRef; | ||
}); |