token refresh and exp check
This commit is contained in:
parent
f1e6e8b8d3
commit
91ff0835fb
5 changed files with 25 additions and 12 deletions
|
@ -2,8 +2,5 @@ import { useAccountStore } from "@/stores/account";
|
|||
|
||||
export async function loadAccountData(to: any, from: any, next: any) {
|
||||
const account = useAccountStore();
|
||||
account.fetchAccountContests();
|
||||
account.fetchAccountInvites();
|
||||
account.fetchAccountLicense();
|
||||
next();
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ 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 };
|
||||
|
||||
|
@ -25,15 +26,30 @@ export async function isAuthenticated(to: any, from: any, next: any) {
|
|||
}
|
||||
|
||||
export async function isAuthenticatedPromise(): Promise<Payload> {
|
||||
return new Promise<Payload>((resolve, reject) => {
|
||||
return new Promise<Payload>(async (resolve, reject) => {
|
||||
const auth = useAuthStore();
|
||||
const account = useAccountStore();
|
||||
let decoded = jwtDecode<Payload>(localStorage.getItem("accessToken") ?? "");
|
||||
|
||||
auth.setSuccess();
|
||||
if (typeof decoded == "string" || !decoded) {
|
||||
reject("jwt failed");
|
||||
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);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue