view client/src/application/stores/user.js @ 585:ef307bd6b5d8

refac: restructured client application To make the application more accessible for developers, the structure was reorganized. Instead of sticking to technical terminology, the application terminology is according to the domain: I.e. "map" contains everything regarding map (including store).
author Thomas Junk <thomas.junk@intevation.de>
date Fri, 07 Sep 2018 11:13:56 +0200
parents
children ca628dce90dd
line wrap: on
line source

import { HTTP } from "../lib/http";

const User = {
  namespaced: true,
  state: {
    authenticated: false,
    expires: null,
    roles: [],
    user: ""
  },
  getters: {
    isAuthenticated: state => {
      return state.authenticated;
    },
    userinfo: state => {
      return state.user;
    },
    roles: state => {
      return state.roles;
    },
    expires: state => {
      return state.expires;
    },
    isWaterwayAdmin: state => {
      return state.roles.includes("waterway_admin");
    },
    isSysAdmin: state => {
      return state.roles.includes("sys_admin");
    }
  },
  mutations: {
    auth_success: (state, data) => {
      const { token, user, expires, roles } = data;
      localStorage.setItem("expires", expires);
      localStorage.setItem("roles", roles);
      localStorage.setItem("token", token);
      localStorage.setItem("user", user);
      state.expires = expires;
      state.roles = roles;
      state.user = user;
      state.authenticated = true;
    },
    clear_auth: state => {
      state.authenticated = false;
      state.expires = null;
      state.roles = [];
      state.user = "";
      localStorage.clear();
    },
    set_user: (state, name) => {
      state.user = name;
    },
    set_roles: (state, roles) => {
      state.roles = roles;
    },
    set_expires: (state, expires) => {
      state.expires = expires;
    },
    set_authenticate: state => {
      state.authenticated = true;
    }
  },
  actions: {
    login({ commit }, user) {
      // using POST is a bit more secure than GET
      return new Promise((resolve, reject) => {
        HTTP.post("/login", user)
          .then(response => {
            commit("auth_success", response.data);
            resolve(response);
          })
          .catch(error => {
            commit("clear_auth");
            reject(error);
          });
      });
    }
  }
};

export default User;