Private
Public Access
actualizado tema tokens
This commit is contained in:
1 parent
38afdcc742
commit
441e2f5833
28 files changed
+506
-194
No files matched your search
@@ -3,8 +3,11 @@ export interface AuthTokens {
|
||||
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);
|
||||
@@ -43,3 +46,38 @@ export function removeAuthTokens(): void {
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user