Feature: Add csrf settings for axios request

This commit is contained in:
winkidney
2019-11-29 14:11:14 +08:00
committed by Isaac Bythewood
parent 076d59613a
commit 602ca97d00
2 changed files with 39 additions and 1 deletions

View File

@@ -0,0 +1,37 @@
import axios from 'axios';
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
return null;
}
function getCSRFToken() {
return getCookie('csrftoken');
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function setUpAxiosCsrfConfig() {
axios.interceptors.request.use(
(config) => {
if (!csrfSafeMethod(config.method.toUpperCase())) {
// eslint-disable-next-line no-param-reassign
config.headers['X-CSRFToken'] = getCSRFToken();
}
return config;
},
(error) => {
Promise.reject(error);
},
);
}
export default setUpAxiosCsrfConfig;

View File

@@ -3,11 +3,12 @@ import Vue from 'vue';
import { VueMasonryPlugin } from 'vue-masonry';
import App from './App.vue';
import router from './router';
import setUpAxiosCsrfConfig from './components/utils/csrf';
Vue.config.productionTip = false;
Vue.use(Buefy);
Vue.use(VueMasonryPlugin);
setUpAxiosCsrfConfig();
new Vue({
router,