2022-08-31 14:28:35 +02:00
|
|
|
import type { JwtPayload } from "jwt-decode";
|
|
|
|
import type { Ref, UnwrapRef } from "vue";
|
|
|
|
import jwtDecode from "jwt-decode";
|
|
|
|
import { isErrorResponse } from "./base";
|
|
|
|
import { refresh_token } from "./auth";
|
2022-08-24 16:15:33 +02:00
|
|
|
|
|
|
|
export async function check_token(
|
2022-08-31 14:28:35 +02:00
|
|
|
token: TokenInjectType
|
2022-08-24 16:15:33 +02:00
|
|
|
): Promise<string | void> {
|
2022-08-31 14:28:35 +02:00
|
|
|
if (!token.jwt.value) return token.logout();
|
|
|
|
const payload = jwtDecode<JwtPayload>(token.jwt.value);
|
|
|
|
if (!payload) return token.logout();
|
|
|
|
// Expires in more than 60 Minute
|
|
|
|
if (payload.exp && payload.exp > Math.floor(Date.now() / 1000 + 60 * 60))
|
|
|
|
return token.jwt.value;
|
|
|
|
const new_token = await refresh_token(token.jwt.value);
|
|
|
|
if (isErrorResponse(new_token)) return token.logout();
|
|
|
|
token.setToken(new_token.jwt);
|
|
|
|
return new_token.jwt;
|
2022-08-24 16:15:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export type TokenInjectType = {
|
2022-08-31 14:28:35 +02:00
|
|
|
jwt: Ref<UnwrapRef<string | null>>;
|
|
|
|
setToken: (token: string) => void;
|
|
|
|
logout: () => void;
|
2022-08-24 16:15:33 +02:00
|
|
|
};
|