import { AxiosInstance } from "axios"; import { Entity } from "../../types/entity"; import { getLoginUrl } from "../../utils/auth-utils"; /** * Create the authentication module * @param client HTTP client * @param appId Application ID * @param serverUrl Server URL * @returns Authentication module */ export function createAuthModule( client: AxiosInstance, appId: string | number, serverUrl: string ) { return { /** * Get the current authenticated user * @returns Promise resolving to the user entity */ me: async (): Promise => { try { return client.get(`/auth/me`); } catch (error) { console.info( "Error fetching user from /auth/me, falling back to /apps/:appId/entities/User/me", (error as Error).message ); return client.get(`/apps/${appId}/entities/User/me`); } }, /** * Update the current authenticated user * @param data Updated user data * @returns Promise resolving to the updated user entity */ updateMe: async (data: Record): Promise => { return client.put(`/apps/${appId}/entities/User/me`, data); }, /** * Redirect to the login page * @param nextUrl Optional URL to redirect to after successful login */ login(nextUrl?: string): void { if (typeof window === "undefined") { throw new Error( "Login method can only be used in a browser environment" ); } console.log("redirecting to login page..."); const returnUrl = nextUrl || window.location.href; const loginUrl = getLoginUrl(returnUrl, { serverUrl, appId }); window.location.href = loginUrl; }, /** * Log out the current user * @param redirectUrl Optional URL to redirect to after logout * @returns Promise that resolves when logout is complete */ async logout(redirectUrl?: string): Promise { // Remove the authorization header delete client.defaults.headers.common["Authorization"]; // Remove the token from localStorage if (typeof window !== "undefined" && window.localStorage) { try { window.localStorage.removeItem("b44_access_token"); } catch (error) { console.error("Failed to remove token from localStorage:", error); } } // Redirect if a URL is provided if (redirectUrl && typeof window !== "undefined") { window.location.href = redirectUrl; } return Promise.resolve(); }, /** * Set the authentication token * @param token Authentication token * @param saveToStorage Whether to save the token to localStorage */ setToken(token: string, saveToStorage: boolean = true): void { if (token) { // Set the authorization header client.defaults.headers.common["Authorization"] = `Bearer ${token}`; // Save the token to localStorage if requested if ( saveToStorage && typeof window !== "undefined" && window.localStorage ) { try { window.localStorage.setItem("b44_access_token", token); } catch (error) { console.error("Failed to save token to localStorage:", error); } } } }, /** * Check if the user is authenticated * @returns Promise resolving to authentication status */ async isAuthenticated(): Promise { try { await this.me(); return true; } catch (error) { return false; } }, }; }