import jwt_decode from "jwt-decode"; import axios from "axios"; export default class Token { get() { return sessionStorage.getItem("token"); } set(token: string) { sessionStorage.setItem("token", token); } getRefresh() { return sessionStorage.getItem("refresh"); } setRefresh(refresh_token: string) { sessionStorage.setItem("refresh", refresh_token); } present() { return sessionStorage.getItem("token") != null; } logout() { sessionStorage.removeItem("token"); sessionStorage.removeItem("refresh"); } refresh() { const options = { headers: { Authorization: `Bearer ${this.getRefresh()}` } } try { const response = axios.post('/refresh_tokens', null, options); this.setRefresh(response.data.refresh); this.set(response.data.token); } catch(error) { this.logout(); } } getEmail() { return this.decode()?.data; } getRole() { return this.decode()?.aud; } getJTI() { return this.decode()?.jti; } getExpirationDate() { return this.decode()?.exp; } private decode(): { data: string; aud: string; jti: string; exp: number; } | null { const token = this.get(); if(token != null) return jwt_decode(token); return null; } }