Some wprk on auth code

This commit is contained in:
Karolis2011
2021-08-10 10:48:40 +03:00
parent e498f41f95
commit b1935f0ffb
10 changed files with 266 additions and 100 deletions

View File

@@ -0,0 +1,75 @@
import Cookies from "cookies-js";
import jwt_decode from "jwt-decode";
const TokenCookieName = "ktusaktutoken";
// initial state
const state = () => ({
token: null,
tokenData: null,
});
// getters
const getters = {
isValid(state) {
if (state.token == null || state.tokenData == null) return false;
const d = state.tokenData;
if (
d.iss !==
"https://login.microsoftonline.com/3415f2f7-f5a8-4092-b52a-003aaf844853/v2.0"
)
return false;
if (d.aud !== "5931fda0-e9e0-4754-80c2-18bcb9d9561a") return false;
const now = new Date();
const exp = new Date(d.exp * 1000);
if (now > exp) return false;
return true;
},
name(state, getters) {
if (!getters.isValid) return null;
return state.tokenData.name;
},
email(state, getters) {
if (!getters.isValid) return null;
return state.tokenData.email;
},
};
// actions
const actions = {
async loadToken({ commit }) {
const token = Cookies.get(TokenCookieName);
commit("setToken", token);
commit("computeTokenVars");
},
async setToken({ commit }, token) {
Cookies.set(TokenCookieName, token);
commit("setToken", token);
commit("computeTokenVars");
},
};
// mutations
const mutations = {
setToken(state, token) {
state.token = token;
},
computeTokenVars(state) {
if (state.token == null) return;
try {
state.tokenData = jwt_decode(state.token);
} catch {
console.log("Token was invalid.");
state.tokenData = null;
state.token = null;
}
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations,
};