Add user module to Vuex store

This commit is contained in:
D. Berge
2020-10-11 17:53:39 +02:00
parent dd32982cbe
commit 0512ac2c3c
6 changed files with 71 additions and 0 deletions

View File

@@ -2,6 +2,7 @@ import Vue from 'vue'
import Vuex from 'vuex'
import api from './modules/api'
import user from './modules/user'
import snack from './modules/snack'
import project from './modules/project'
import notify from './modules/notify'
@@ -11,6 +12,7 @@ Vue.use(Vuex)
export default new Vuex.Store({
modules: {
api,
user,
snack,
project,
notify

View File

@@ -0,0 +1,41 @@
import jwt_decode from 'jwt-decode';
async function login ({commit, dispatch}, loginRequest) {
const url = "/login";
const init = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: loginRequest
}
const res = await dispatch('api', [url, init]);
if (res && res.ok) {
dispatch('setCredentials', true);
}
}
async function logout ({commit, dispatch}) {
commit('setCookie', null);
commit('setUser', null);
await dispatch('api', ["/logout"]);
// Should delete JWT cookie
}
function browserCookie (state) {
return document.cookie.split(/; */).find(i => i.startsWith("JWT="));
}
function cookieChanged (cookie) {
return browserCookie != cookie;
}
function setCredentials ({state, commit, getters, dispatch}, force = false) {
if (cookieChanged(state.cookie) || force) {
const cookie = browserCookie();
commit('setCookie', cookie);
commit('setUser', cookie ? jwt_decode(cookie.split("=")[1]) : null);
}
}
export default { login, logout, setCredentials };

View File

@@ -0,0 +1,6 @@
function user (state) {
return state.user;
}
export default { user };

View File

@@ -0,0 +1,6 @@
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
export default { state, getters, actions, mutations };

View File

@@ -0,0 +1,10 @@
function setCookie (state, cookie) {
state.cookie = cookie;
}
function setUser (state, user) {
state.user = user;
}
export default { setCookie, setUser };

View File

@@ -0,0 +1,6 @@
const state = () => ({
cookie: null,
user: null,
});
export default state;