Spaces:
Running
Running
| /** | |
| * Session management utilities | |
| * Centralizes authentication session handling for both client and server | |
| */ | |
| /** | |
| * Get credentials from browser localStorage (client-side only) | |
| * @returns {username, password} or null if not found | |
| */ | |
| export function getStoredCredentials(): { username: string; password: string } | null { | |
| if (typeof window === 'undefined') { | |
| return null; // Server-side rendering | |
| } | |
| const stored = localStorage.getItem('auth_credentials'); | |
| if (!stored) { | |
| return null; | |
| } | |
| try { | |
| return JSON.parse(stored); | |
| } catch (error) { | |
| console.error('[Session] Failed to parse stored credentials:', error); | |
| localStorage.removeItem('auth_credentials'); | |
| return null; | |
| } | |
| } | |
| /** | |
| * Store credentials in browser localStorage (client-side only) | |
| */ | |
| export function storeCredentials(username: string, password: string): void { | |
| if (typeof window === 'undefined') { | |
| return; // Server-side rendering | |
| } | |
| localStorage.setItem('auth_credentials', JSON.stringify({ username, password })); | |
| } | |
| /** | |
| * Clear stored credentials from browser localStorage (client-side only) | |
| */ | |
| export function clearStoredCredentials(): void { | |
| if (typeof window === 'undefined') { | |
| return; // Server-side rendering | |
| } | |
| localStorage.removeItem('auth_credentials'); | |
| } | |
| /** | |
| * Generate Basic Auth header from credentials | |
| */ | |
| export function createBasicAuthHeader(username: string, password: string): string { | |
| return 'Basic ' + btoa(`${username}:${password}`); | |
| } | |
| /** | |
| * Parse Basic Auth header to extract credentials | |
| * @returns {username, password} or null if invalid | |
| */ | |
| export function parseBasicAuthHeader(authHeader: string): { username: string; password: string } | null { | |
| if (!authHeader || !authHeader.startsWith('Basic ')) { | |
| return null; | |
| } | |
| try { | |
| const base64Credentials = authHeader.slice(6); // Remove "Basic " prefix | |
| const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8'); | |
| const [username, password] = credentials.split(':'); | |
| if (!username || !password) { | |
| return null; | |
| } | |
| return { username, password }; | |
| } catch (error) { | |
| console.error('[Session] Failed to parse auth header:', error); | |
| return null; | |
| } | |
| } | |
| /** | |
| * Get the user password from environment | |
| * Falls back to 'cz-2025' if not set | |
| */ | |
| export function getDefaultPassword(): string { | |
| return process.env.BASIC_AUTH_PASSWORD || process.env.NEXT_PUBLIC_DEFAULT_PASSWORD || 'cz-2025'; | |
| } | |