games_app/prediqo_web/src/shared/auth/tokenStorage.ts
2026-06-29 15:01:23 +02:00

51 lines
1.6 KiB
TypeScript

/**
* Local storage helpers for persisting authentication credentials in the browser.
* Reads, writes, and clears access tokens, refresh tokens, user id, and role.
*/
/** Authentication fields persisted in browser local storage. */
export type StoredAuth = {
accessToken: string | null;
refreshToken: string | null;
userId: string | null;
role: string | null;
};
const KEYS = {
accessToken: 'cw.accessToken',
refreshToken: 'cw.refreshToken',
userId: 'cw.userId',
role: 'cw.role',
} as const;
/**
* Reads the current authentication snapshot from local storage.
*
* @returns Stored auth tokens and user metadata, or null values when absent.
*/
export function readAuth(): StoredAuth {
return {
accessToken: localStorage.getItem(KEYS.accessToken),
refreshToken: localStorage.getItem(KEYS.refreshToken),
userId: localStorage.getItem(KEYS.userId),
role: localStorage.getItem(KEYS.role),
};
}
/**
* Persists non-null authentication fields to local storage.
*
* @param auth - Auth values to store; null fields are skipped.
*/
export function writeAuth(auth: StoredAuth): void {
if (auth.accessToken != null) localStorage.setItem(KEYS.accessToken, auth.accessToken);
if (auth.refreshToken != null) localStorage.setItem(KEYS.refreshToken, auth.refreshToken);
if (auth.userId != null) localStorage.setItem(KEYS.userId, auth.userId);
if (auth.role != null) localStorage.setItem(KEYS.role, auth.role);
}
/** Removes all persisted authentication data from local storage. */
export function clearAuth(): void {
Object.values(KEYS).forEach((k) => localStorage.removeItem(k));
}