import fetchHelper from './fetchHelper' import getTokenHelper from './getTokenHelper' import { shouldLogoutOnError, classifyAuthError } from './authErrorHelper' /** * Force logout helper - handles logout when authentication truly fails * * This helper now properly classifies errors to distinguish between: * - True authentication failures (expired/invalid tokens) -> logout * - Authorization failures (forbidden/permission denied) -> no logout * - Other errors -> no logout * * @param event - The request event * @param record - The error record with status and message * @returns true if logout was performed, false otherwise */ export default async function forceLogoutHelper(event: any, record: any): Promise { // Classify the error to determine if logout is needed const classification = classifyAuthError(record) // Log the classification for debugging (can be removed in production) if (process.env.NODE_ENV === 'development') { console.log('[forceLogoutHelper] Error classification:', { status: record.status, errorType: classification.errorType, shouldLogout: classification.shouldLogout, reason: classification.reason }) } // Only logout if this is a true authentication failure if (!classification.shouldLogout) { return false } try { let token: string = await getTokenHelper(event) // Clear user cookie //@ts-ignore setCookie(event, 'logship_user', null) // Call logout endpoint const res = await fetchHelper(event, 'auth/logout', 'POST', token, { token: token, }) // Clear auth tokens if logout was successful if(res) { //@ts-ignore setCookie(event, 'logship_it', '') setCookie(event, 'logship_rt', '') } return true } catch (error) { // If logout fails, still clear cookies to ensure user is logged out console.error('[forceLogoutHelper] Logout failed, clearing cookies anyway:', error) //@ts-ignore setCookie(event, 'logship_user', null) setCookie(event, 'logship_it', '') setCookie(event, 'logship_rt', '') return true } }