Logout

Header

  • Composable Action: composables/useDjustAuth/useAuthApi.ts
  • API Route: POST /api/auth/logout (future implementation)

Detailed Description

The logout action is a critical security function that safely terminates user sessions and clears all authentication-related data from the application. It ensures complete session cleanup by removing stored tokens, clearing user state, and invalidating server-side sessions to prevent unauthorized access.

This action is designed to be comprehensive and secure, handling both client-side cleanup and server-side session invalidation. The logout process is fail-safe, meaning it will complete the cleanup operations even if some steps encounter errors, ensuring that users are always properly logged out from the application.

The logout function is used in various scenarios including explicit user logout requests, automatic logout on token expiration, security-triggered logouts, and application cleanup procedures. It serves as the primary mechanism for session termination and security maintenance.

Process Flow

sequenceDiagram
    participant U as User
    participant C as Vue Component
    participant UA as useDjustAuth
    participant S as User Store
    participant Cookies as Cookie Storage
    participant API as Auth API

    U->>C: Request logout
    C->>UA: logout()
    UA->>API: POST /auth/logout (optional)
    UA->>Cookies: Clear all auth cookies
    UA->>S: Clear user state
    S->>C: State cleared
    C->>U: Redirect to login

    alt API Error
        API-->>UA: Server error
        UA->>UA: Continue with cleanup
        Note over UA: Logout completes despite API errors
    end

Call Parameters

Main Interface

// No parameters required - logout is a simple action
const logout = async (): Promise<void>

Detailed Parameters

ParameterTypeRequiredDefaultExampleImpact
None----No parameters needed for logout

Example Call

const { logout } = useDjustAuth();

try {
  await logout();
  console.log("Logout successful");
  // User is now logged out and redirected
} catch (error) {
  console.error("Logout error:", error.message);
  // Cleanup still occurs even if there's an error
}

Returns from Composable

Success Response Format

// Logout returns void - no response data
Promise<void>;

Response Details

The logout function does not return data as its purpose is to clean up the current session. Success is indicated by the completion of the promise without throwing an error. The function always attempts to complete all cleanup operations regardless of individual step failures.

Error Management

Error Types and Returns

HTTP CodeError TypeCauseSystem ActionUser Message
NetworkConnection ErrorAPI endpoint unavailableContinue with local cleanup"Logout completed locally"
500Internal Server ErrorServer-side logout failureContinue with local cleanup"Logout completed"
TimeoutRequest TimeoutServer response too slowContinue with local cleanup"Logout completed"

Error Handling Code Example

const { logout } = useDjustAuth();
const router = useRouter();

try {
  await logout();

  // Redirect to login page after successful logout
  await router.push("/auth/login");
} catch (error) {
  // Even if logout encounters errors, the user is still logged out locally
  console.warn("Logout completed with warnings:", error);

  // Still redirect to login page
  await router.push("/auth/login");
}

Use Cases

  1. Explicit User Logout

    • User clicks logout button in application header
    • System performs complete session cleanup
    • User is redirected to login page
    • All authentication state is cleared
  2. Security-Triggered Logout

    • System detects suspicious activity or security violation
    • Automatic logout is triggered for user protection
    • Session is immediately terminated
    • User must re-authenticate to continue
  3. Token Expiration Logout

    • Authentication tokens expire and cannot be refreshed
    • System automatically logs out user
    • Session state is cleaned up
    • User is prompted to log in again
  4. Application Cleanup

    • User closes browser or navigates away from application
    • System performs cleanup during beforeunload events
    • Session state is preserved according to security policies
    • Cleanup ensures no sensitive data remains

Important Points

Performance

The logout process is optimized for speed and reliability with parallel execution of cleanup operations where possible. The system implements fail-safe mechanisms to ensure logout completion even if individual operations fail, and provides immediate user feedback without waiting for server confirmation.

Security

Security is the primary focus with comprehensive token invalidation, secure cookie clearing with proper flags, prevention of token reuse or session replay attacks, and complete cleanup of sensitive data from client-side storage.

Flexibility

The system supports various logout scenarios including graceful logout with server notification, forced logout for security purposes, offline logout when server is unavailable, and customizable post-logout redirection.

Integration

Seamless integration with the application ecosystem includes automatic Pinia store cleanup, coordination with route protection middleware, integration with session timeout mechanisms, and proper cleanup of related feature states.

Technical Implementation

/**
 * Logs out the current user and clears all authentication data
 * @returns Promise<void> - Completes when logout is finished
 * @throws {Error} - Only throws if critical cleanup fails
 */
const logout = async (): Promise<void> => {
  try {
    // Future: Add API call to invalidate server-side session
    // await useFetch('/api/auth/logout', { method: 'POST' });

    // Clear authentication cookies
    clearTokenCookies();

    // Clear user state from store
    userStore.logout();
  } catch (error) {
    console.error("Failed to logout:", error);

    // Even if there are errors, ensure local cleanup is complete
    clearTokenCookies();
    userStore.logout();
  }
};

Execution Flow

  1. Server Notification (Future Implementation)

    // await useFetch('/api/auth/logout', { method: 'POST' });
    // Server invalidates session and refresh tokens
  2. Cookie Cleanup

    clearTokenCookies();
    // Removes: token, refreshToken, customer-account-id, store-id, etc.
  3. Store Cleanup

    userStore.logout();
    // Clears: user data, account info, authentication status
  4. Error Handling

    // Ensures cleanup completes even if steps fail
    // Logs errors for debugging but doesn't prevent logout
  5. Completion

    // User is now logged out regardless of any errors
    // Application state is clean and secure