Private
Public Access
84 lines
2.0 KiB
TypeScript
84 lines
2.0 KiB
TypeScript
export interface AuthTokens {
|
|
access_token: string;
|
|
refresh_token: string;
|
|
expires_in: number;
|
|
token_type: string;
|
|
permissions?: number[];
|
|
}
|
|
|
|
export const AUTH_CHANGE_EVENT = 'auth-change';
|
|
|
|
export function setToken(token: string): void {
|
|
if (typeof window !== 'undefined') {
|
|
localStorage.setItem('token', token);
|
|
}
|
|
}
|
|
|
|
export function removeToken(): void {
|
|
if (typeof window !== 'undefined') {
|
|
localStorage.removeItem('token');
|
|
}
|
|
}
|
|
|
|
export function getToken(): string {
|
|
if (typeof window !== 'undefined') {
|
|
return localStorage.getItem('token') || '';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
export function setAuthTokens(auth: AuthTokens): void {
|
|
if (typeof window !== 'undefined') {
|
|
localStorage.setItem('auth', JSON.stringify(auth));
|
|
}
|
|
}
|
|
|
|
export function getAuthTokens(): AuthTokens | null {
|
|
if (typeof window !== 'undefined') {
|
|
const auth = localStorage.getItem('auth');
|
|
return auth ? JSON.parse(auth) : null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function removeAuthTokens(): void {
|
|
if (typeof window !== 'undefined') {
|
|
localStorage.removeItem('auth');
|
|
}
|
|
}
|
|
|
|
export function getPermissions(): number[] {
|
|
return getAuthTokens()?.permissions ?? [];
|
|
}
|
|
|
|
export function notifyAuthChange(): void {
|
|
if (typeof window !== 'undefined') {
|
|
window.dispatchEvent(new Event(AUTH_CHANGE_EVENT));
|
|
}
|
|
}
|
|
|
|
export function decodeJwtPayload<T = Record<string, unknown>>(token: string): T | null {
|
|
try {
|
|
const part = token.split('.')[1];
|
|
if (!part) return null;
|
|
|
|
const base64 = part.replace(/-/g, '+').replace(/_/g, '/');
|
|
const padding = (4 - (base64.length % 4)) % 4;
|
|
const padded = base64 + '='.repeat(padding);
|
|
|
|
const binary = atob(padded);
|
|
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
return JSON.parse(new TextDecoder().decode(bytes)) as T;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function getTokenExpiry(): number | null {
|
|
const token = getAuthTokens()?.access_token;
|
|
if (!token) return null;
|
|
|
|
const payload = decodeJwtPayload<{ exp?: number }>(token);
|
|
return payload?.exp ? payload.exp * 1000 : null;
|
|
}
|