// Trip authentication token management const TOKEN_STORAGE_PREFIX = 'juntete_trip_token_' export function storeTripToken(tripId: number, token: string): void { if (typeof window === 'undefined') { console.warn('[storeTripToken] Cannot store token - window is undefined') return } const key = `${TOKEN_STORAGE_PREFIX}${tripId}` localStorage.setItem(key, token) console.log(`[storeTripToken] Stored token for trip ${tripId} in key: ${key}`) // Verify it was stored const stored = localStorage.getItem(key) if (stored !== token) { console.error(`[storeTripToken] Token storage verification failed for trip ${tripId}`) } else { console.log(`[storeTripToken] Token storage verified for trip ${tripId}`) } } export function getTripToken(tripId: number): string | null { if (typeof window === 'undefined') { console.warn('[getTripToken] Cannot get token - window is undefined') return null } const key = `${TOKEN_STORAGE_PREFIX}${tripId}` const token = localStorage.getItem(key) console.log(`[getTripToken] Trip ${tripId}, key: ${key}, token:`, token ? 'found' : 'not found') return token } export function removeTripToken(tripId: number): void { if (typeof window === 'undefined') return localStorage.removeItem(`${TOKEN_STORAGE_PREFIX}${tripId}`) } export function getAuthHeaders(tripId: number): HeadersInit { const token = getTripToken(tripId) console.log(`[getAuthHeaders] Trip ${tripId}, token:`, token ? 'present' : 'missing') const headers: HeadersInit = { 'Content-Type': 'application/json', } if (token) { headers['Authorization'] = `Bearer ${token}` console.log(`[getAuthHeaders] Added Authorization header for trip ${tripId}`) } else { console.warn(`[getAuthHeaders] No token found for trip ${tripId}`) } return headers } export async function authenticateTrip(tripId: number, password: string): Promise { const response = await fetch('/api/auth/trip/authenticate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ trip_id: tripId, password: password, }), }) if (!response.ok) { const errorData = await response.json() throw new Error(errorData.detail || 'Authentication failed') } const data = await response.json() storeTripToken(tripId, data.access_token) return data.access_token }