This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

semble / src / webapp / lib / auth / dal.ts
1.8 kB 62 lines
1import type { GetProfileResponse } from '@/api-client/ApiClient'; 2import { cache } from 'react'; 3import { ClientCookieAuthService } from '@/services/auth/CookieAuthService.client'; 4 5const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://127.0.0.1:4000'; 6 7let isRefreshing = false; 8let refreshPromise: Promise<GetProfileResponse | null> | null = null; 9 10interface VerifySessionOptions { 11 redirectOnFail?: boolean; 12} 13 14export const verifySessionOnClient = cache( 15 async ( 16 options?: VerifySessionOptions, 17 ): Promise<GetProfileResponse | null> => { 18 const { redirectOnFail = false } = options || {}; 19 20 if (isRefreshing && refreshPromise) { 21 console.log('Auth refresh already in progress, waiting...'); 22 return refreshPromise; 23 } 24 25 isRefreshing = true; 26 refreshPromise = (async () => { 27 try { 28 const response = await fetch(`${appUrl}/api/auth/me`, { 29 method: 'GET', 30 credentials: 'include', 31 }); 32 33 if (!response.ok) { 34 if (redirectOnFail && typeof window !== 'undefined') { 35 // Redirect to login only if requested 36 window.location.href = '/login'; 37 } 38 return null; 39 } 40 41 const { user }: { user: GetProfileResponse } = await response.json(); 42 return user; 43 } finally { 44 isRefreshing = false; 45 refreshPromise = null; 46 } 47 })(); 48 49 return refreshPromise; 50 }, 51); 52 53/** 54 * Logs out the current user by clearing tokens and redirecting to login 55 * Can be called from both client and server contexts 56 */ 57export const logoutUser = async (): Promise<void> => { 58 await ClientCookieAuthService.clearTokens(); 59 if (typeof window !== 'undefined') { 60 window.location.href = '/login'; 61 } 62};