2023-09-14 11:29:24 +02:00

78 lines
2.0 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",
}
export interface IUserJwtPayload {
userId: string;
email: string | null;
openId: {
providerName: PROVIDER_OPENID;
userId: string | number;
};
office_Id: string;
role: string;
rules: string[];
exp: number;
}
export interface ICustomerJwtPayload {
userId: string;
email: string;
}
export default class JwtService {
private static instance: JwtService;
private constructor() {}
public static getInstance() {
return (this.instance ??= new this());
}
public decodeJwt(): IUserJwtPayload | undefined {
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
if (!accessToken) return;
return jwt_decode(accessToken);
}
public decodeCustomerJwt(): ICustomerJwtPayload | undefined {
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
if (!accessToken) return;
return jwt_decode(accessToken);
}
/**
* @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 decodedToken = this.decodeJwt();
if (!decodedToken) return;
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);
}
}
}
public hasRule(name: string, action: string) {
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
if (!accessToken) return false;
const decodedToken = this.decodeJwt();
if (!decodedToken) return false;
return decodedToken?.rules?.some((rule: string) => rule === `${action} ${name}`);
}
}