import NProgress from "nprogress"; import { useAuthStore } from "@/stores/auth"; import { useAccountStore } from "@/stores/account"; import { jwtDecode, type JwtPayload } from "jwt-decode"; import { refreshToken } from "../serverCom"; type Payload = JwtPayload & { userId: number; username: string; firstname: string; lastname: string; mail: string }; export async function isAuthenticated(to: any, from: any, next: any) { const auth = useAuthStore(); NProgress.start(); if (auth.authCheck && localStorage.getItem("access_token")) { NProgress.done(); next(); return; } await isAuthenticatedPromise() .then(async (result: any) => { NProgress.done(); next(); }) .catch((err: Error) => { NProgress.done(); next({ name: "login" }); }); } export async function isAuthenticatedPromise(): Promise { return new Promise(async (resolve, reject) => { const auth = useAuthStore(); const account = useAccountStore(); let decoded = jwtDecode(localStorage.getItem("accessToken") ?? ""); auth.setSuccess(); if (typeof decoded == "string" || !decoded) { reject("failed"); } // check jwt expiry const exp = decoded.exp ?? 0; const localTimezoneOffset = new Date().getTimezoneOffset(); const correctedLocalTime = new Date().getTime() + localTimezoneOffset * 60000; if (exp < Math.floor(correctedLocalTime / 1000)) { await refreshToken() .then(() => { console.log("fetched new token"); }) .catch(() => { reject("expired"); }); } var { firstname, lastname, mail, username } = decoded; account.setAccountData(firstname, lastname, mail, username); resolve(decoded); }); }