53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
import jwt_decode from "jwt-decode";
|
|
import CookieService from "../CookieService/CookieService";
|
|
import User from "@Front/Api/Auth/IdNot/User";
|
|
|
|
enum PROVIDER_OPENID {
|
|
idNot = "idNot",
|
|
}
|
|
|
|
interface IUserJwtPayload {
|
|
userId: string;
|
|
openId: {
|
|
providerName: PROVIDER_OPENID;
|
|
userId: string | number;
|
|
};
|
|
office_Id: string;
|
|
role: string;
|
|
rules: string[];
|
|
exp: number;
|
|
}
|
|
|
|
export default class JwtService {
|
|
private static instance: JwtService;
|
|
private constructor() {}
|
|
|
|
public static getInstance() {
|
|
return (this.instance ??= new this());
|
|
}
|
|
|
|
/**
|
|
* @description : set a cookie with a name and a value that expire in 7 days
|
|
* @throws {Error} If the name or the value is empty
|
|
*/
|
|
public async checkJwt() {
|
|
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
|
|
|
|
if (!accessToken) return;
|
|
const decodedToken: IUserJwtPayload = jwt_decode(accessToken);
|
|
|
|
const now = Math.floor(Date.now() / 1000);
|
|
|
|
if (decodedToken.exp < now) {
|
|
const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken");
|
|
|
|
if (!refreshToken) return;
|
|
const newAccessToken: { accessToken: string } = await User.getInstance().refreshToken(refreshToken);
|
|
|
|
if (newAccessToken) {
|
|
CookieService.getInstance().setCookie("leCoffreAccessToken", newAccessToken.accessToken);
|
|
}
|
|
}
|
|
}
|
|
}
|