You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

71 lines
1.1 KiB

import jwtDecode from "jwt-decode";
/**
* The active JWT
*/
let token: string | null;
/**
* The decoded user object
*/
let user: {
id: number,
name: string,
isAdmin: boolean
} | null;
/**
* Check if the user is an admin
*/
export function isAdmin() {
return user && user.isAdmin;
}
/**
* Check if the client is authenticated
*/
export function isAuthenticated() {
return Boolean(token);
}
/**
* Load the token from local storage
*/
export function loadToken() {
try {
token = localStorage.getItem("jwt");
user = jwtDecode(<string>token);
} catch(e) {
console.log("Failed to load token");
token = null;
user = null;
return false;
}
return true;
}
/**
* Delete the token from local storage
*/
export function forgetToken() {
token = null;
user = null;
localStorage.removeItem("jwt");
}
/**
* Store a JWT token in local storage
*/
export function storeToken(jwtToken: string) {
try {
user = jwtDecode(jwtToken);
token = jwtToken;
localStorage.setItem("jwt", jwtToken);
} catch(e) {
user = null;
token = null;
return false;
}
return true;
}