57 lines
No EOL
1.6 KiB
TypeScript
57 lines
No EOL
1.6 KiB
TypeScript
import { jwtDecode } from "jwt-decode"
|
|
import { AUTH_TOKEN_KEY, USER_KEY, type User } from "../lib/api"
|
|
import { navigate } from "astro:transitions/client"
|
|
|
|
export function saveUser(user: User) {
|
|
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
|
}
|
|
|
|
export function getUser(): User | null {
|
|
checkJWTValidity()
|
|
|
|
const user_string = localStorage.getItem(USER_KEY)
|
|
if (user_string) return JSON.parse(user_string) as User
|
|
else logout()
|
|
return null
|
|
}
|
|
|
|
export function logout() {
|
|
localStorage.removeItem(USER_KEY)
|
|
localStorage.removeItem(AUTH_TOKEN_KEY)
|
|
}
|
|
|
|
export function isEmailValid(email: string): boolean {
|
|
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
|
|
return emailRegex.test(email);
|
|
}
|
|
|
|
export function checkJWTValidity() {
|
|
const token = localStorage.getItem(AUTH_TOKEN_KEY)
|
|
if (!token || isTokenExpired(token)) {
|
|
logout()
|
|
}
|
|
}
|
|
|
|
export function isTokenExpired(token: string): boolean {
|
|
try {
|
|
const { exp } = jwtDecode<{ exp: number }>(token)
|
|
const expirationDatetimeInSeconds = exp * 1000
|
|
return Date.now() >= expirationDatetimeInSeconds
|
|
} catch {
|
|
return true
|
|
}
|
|
}
|
|
|
|
export const navigateBackAndReload = () => {
|
|
if (document.referrer) {
|
|
navigate(document.referrer, { history: 'replace' });
|
|
setTimeout(() => window.location.reload(), 50);
|
|
} else {
|
|
navigate('/');
|
|
}
|
|
};
|
|
|
|
export const navigatePathAndReload = (path: string) => {
|
|
navigate(path, { history: 'replace' });
|
|
setTimeout(() => window.location.reload(), 50);
|
|
} |