Skip to content

Commit

Permalink
created new csrf plugin and use it into initialSetup
Browse files Browse the repository at this point in the history
  • Loading branch information
rbodnariu-plenty committed Oct 9, 2023
1 parent 1642323 commit 1ca0237
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
13 changes: 13 additions & 0 deletions apps/web/composables/useInitalSetup/useInitialSetup.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Cart, SessionResult } from '@plentymarkets/shop-api';
import { useSdk } from '~/sdk';
import { SetInitialData, UseInitialSetupReturn } from './types';
import { getCurrentInstance } from 'vue';

/** Function for getting current customer/cart data from session
* @example
Expand All @@ -15,6 +16,18 @@ const setInitialData: SetInitialData = async () => {

const { setCart } = useCart();
setCart(data.value?.data.basket as Cart);

const csrf = data.value?.data.csrf;

const appInstance = getCurrentInstance();
interface CsrfObject {
updateCSRFToken: (token: string) => void;
}

if (appInstance && appInstance.appContext.config.globalProperties.$csrf) {
appInstance.appContext.config.globalProperties.$csrf.updateCSRFToken(csrf);
}
console.log('csrf:' + csrf);
};

/**
Expand Down
1 change: 1 addition & 0 deletions apps/web/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,5 @@ export default defineNuxtConfig({
},
registerWebManifestInRouteRules: true,
},
plugins: ['~/plugins/csrf.js'],
});
47 changes: 47 additions & 0 deletions apps/web/plugins/csrf.js
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;
});

0 comments on commit 1ca0237

Please sign in to comment.