Skip to content
Snippets Groups Projects
index.js 8.75 KiB
Newer Older
const axios = require("axios");

import Vue from 'vue';
import Vuex from 'vuex';
import router from '../router'
import feature_type from "./modules/feature_type"
import feature from "./modules/feature"
import map from "./modules/map"

leandro's avatar
leandro committed
axios.defaults.headers.common['X-CSRFToken'] = (name => {
  var re = new RegExp(name + "=([^;]+)");
  var value = re.exec(document.cookie);
  return (value != null) ? unescape(value[1]) : null;
})('csrftoken');


Vue.use(Vuex);


axios.defaults.withCredentials = true; // * add cookies to axios
function updateAxiosHeader() {
  axios.defaults.headers.common['X-CSRFToken'] = (name => {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? unescape(value[1]) : null;
  })('csrftoken');
}
// ! À vérifier s'il y a un changement de token pendant l'éxécution de l'appli
updateAxiosHeader();

Timothee P's avatar
Timothee P committed
const noPermissions = { "can_view_project": true, "can_create_project": false, "can_update_project": false, "can_view_feature": true, "can_view_archived_feature": true, "can_create_feature": false, "can_update_feature": false, "can_delete_feature": false, "can_publish_feature": false, "can_create_feature_type": false, "can_view_feature_type": true, "is_project_administrator": false }

export default new Vuex.Store({
  modules: {
    feature_type,
    feature,
    map
  },
  state: {
    logged: false,
    user: false,
Timothee P's avatar
Timothee P committed
    configuration: null,
    project_slug: null,
    projects: [],
    last_comments: [],
    staticPages: null,
    SSO_SETTED: false,
    USER_LEVEL_PROJECTS: null,
    user_permissions: null,
Timothee P's avatar
Timothee P committed
    messages: []
  },

  mutations: {
    SET_PROJECTS(state, projects) {
      state.projects = projects;
    },
    ADD_PROJECT(state, project) {
      state.projects = [project, ...state.projects];
    },
    SET_PROJECT_SLUG(state, slug) {
      state.project_slug = slug;
    },
    SET_USER(state, payload) {
      state.user = payload;
    },
    SET_CONFIG(state, payload) {
      state.configuration = payload;
    },
    SET_USERS(state, payload) {
      state.users = payload;
    },
    SET_COOKIE(state, cookie) {
Timothee P's avatar
Timothee P committed
      state.cookie = cookie;
Timothee P's avatar
Timothee P committed
      state.staticPages = staticPages;
Timothee P's avatar
Timothee P committed
      state.SSO_SETTED = SSO_SETTED;
    },
    SET_USER_LEVEL_PROJECTS(state, USER_LEVEL_PROJECTS) {
Timothee P's avatar
Timothee P committed
      state.USER_LEVEL_PROJECTS = USER_LEVEL_PROJECTS;
Timothee P's avatar
Timothee P committed
      state.logged = value;
Timothee P's avatar
Timothee P committed
      state.last_comments = last_comments;
    },
    SET_USER_PERMISSIONS(state, userPermissions) {
Timothee P's avatar
Timothee P committed
      state.user_permissions = userPermissions;
Timothee P's avatar
Timothee P committed
    DISPLAY_MESSAGE(state, comment) {
      state.messages = [{ comment }, ...state.messages];
      document.getElementById("messages").scrollIntoView({ block: "start", inline: "nearest" });
    },
    CLEAR_MESSAGES(state) {
      state.messages = [];
    }
  },

  getters: {
    project: state => state.projects.find((project) => project.slug === state.project_slug),
Timothee P's avatar
Timothee P committed
    permissions: state => state.user_permissions ? state.user_permissions[state.project_slug] : noPermissions,
    project_types: state => state.projects.filter(projet => projet.is_project_type),
    project_user: state => state.projects.filter(projet => projet.creator === state.user.id),
DESPRES Damien's avatar
DESPRES Damien committed
    GET_ALL_PROJECTS({ commit }) {
Timothee P's avatar
Timothee P committed
        let dateArr = date.split("/").reverse();
        return new Date(dateArr[0], dateArr[1] - 1, dateArr[2]);
DESPRES Damien's avatar
DESPRES Damien committed
      return axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}projects/`)
        .then((response) => {
          if (response.status === 200 && response.data) {
            const orderedProjects = response.data.sort((a, b) => parseDate(b.created_on) - parseDate(a.created_on));
Timothee P's avatar
Timothee P committed
            commit("SET_PROJECTS", orderedProjects);
    GET_STATIC_PAGES({ commit }) {
DESPRES Damien's avatar
DESPRES Damien committed
      return axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}flat-pages/`)
        .then((response) => (commit("SET_STATIC_PAGES", response.data)))
        .catch((error) => {
          throw error;
        });
    },

    LOGIN({ commit, dispatch }, payload) {
      if (payload.username && payload.password) {
        return axios
          .post(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}login/`, {
            username: payload.username,
            password: payload.password,
          })
          .then((response) => {
            if (response.status === 200 && response.data) {
              // * use stored previous route to go back after login if page not open on login at first
Timothee P's avatar
Timothee P committed
              let routerHistory = '';
              if (router.options.routerHistory[0] !== undefined) {
                routerHistory = router.options.routerHistory[0].name !== "login" ? router.options.routerHistory : "/";
leandro's avatar
leandro committed
              } else {
Timothee P's avatar
Timothee P committed
                routerHistory = "/";
leandro's avatar
leandro committed
              }
Timothee P's avatar
Timothee P committed
              router.push(routerHistory[routerHistory.length - 1] || "/");
Timothee P's avatar
Timothee P committed
              dispatch("GET_USER_LEVEL_PERMISSIONS")
              return response.status
          .catch(() => {
            return "error";
    USER_INFO({ state, commit }) {
        axios
          .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}user_info/`)
          .then((response) => {
            if (response && response.status === 200) {
              const user = response.data.user;
              commit("SET_USER", user);
              //window.localStorage.setItem("user", JSON.stringify(user)); // ? nécessaire ?
            }
          })
          .catch(() => {
            router.push({ name: "login" });
          });
      }
    LOGOUT({ commit, dispatch }) {
      // const pageNoRedirect = ["liste-signalements", "details-type-signalement", "details-signalement", "project_detail", "mentions", "aide", "index"]
      axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}logout/`)
        .then((response) => {
          if (response && response.status === 200) {
            commit("SET_USER", false);
            dispatch("GET_USER_LEVEL_PERMISSIONS");
            // if (!pageNoRedirect.includes(router.history.current.name)) router.push("/");
            if (router.history.current.name !== "index") router.push("/");
          }
        })
        .catch((error) => {
          throw error;
        });
    },

    GET_CONFIG({ commit }) {
      axios
        .get("./config/config.json")
        .then((response) => {
          if (response && response.status === 200) {
Timothee P's avatar
Timothee P committed
            commit("SET_CONFIG", response.data);
DESPRES Damien's avatar
DESPRES Damien committed
      return axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}user-level-projects/`)
        .then((response) => {
          if (response && response.status === 200) {
Timothee P's avatar
Timothee P committed
            commit("SET_USER_LEVEL_PROJECTS", response.data);
          }
        })
        .catch((error) => {
          throw error;
        });
    },

    GET_USER_LEVEL_PERMISSIONS({ commit }) {
DESPRES Damien's avatar
DESPRES Damien committed
      return axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}user-permissions/`)
        .then((response) => {
          if (response && response.status === 200) {
Timothee P's avatar
Timothee P committed
            commit("SET_USER_PERMISSIONS", response.data);
    async GET_PROJECT_INFO({ state, commit, dispatch }, slug) {
      let promises = [
        dispatch("GET_PROJECT_LAST_MESSAGES", slug).then(response => response),
        dispatch("feature_type/GET_PROJECT_FEATURE_TYPES", slug).then(response => response),
        dispatch("feature/GET_PROJECT_FEATURES", slug).then(response => response),
      ]
      if (state.user) promises.push(dispatch("map/GET_BASEMAPS", slug).then(response => response))

      const promiseResult = await Promise.all(promises)
      return promiseResult;
    },

    GET_PROJECT_LAST_MESSAGES({ commit }, project_slug) {
DESPRES Damien's avatar
DESPRES Damien committed
      return axios
        .get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}projects/${project_slug}/comments/`)
        .then((response) => {
          if (response && response.status === 200) {
Timothee P's avatar
Timothee P committed
            commit("SET_PROJECT_COMMENTS", response.data.last_comments);