Sifa professional network frontend (Next.js, React, TailwindCSS) sifa.id/
at main 38 lines 1.1 kB view raw
1'use client'; 2 3import { useCallback } from 'react'; 4import { useTranslations } from 'next-intl'; 5import { toast } from 'sonner'; 6import { useAuth } from '@/components/auth-provider'; 7 8/** 9 * Returns a guard function that checks auth state before performing an action. 10 * If the user is not authenticated, shows a toast prompting them to sign in. 11 * If authenticated, executes the callback. 12 */ 13export function useRequireAuth() { 14 const { session } = useAuth(); 15 const t = useTranslations('auth'); 16 const isAuthenticated = session !== null; 17 18 const requireAuth = useCallback( 19 (action: () => void | Promise<void>) => { 20 if (!isAuthenticated) { 21 toast(t('loginRequired'), { 22 description: t('loginRequiredDescription'), 23 action: { 24 label: t('signIn'), 25 onClick: () => { 26 window.location.href = `/login?returnTo=${encodeURIComponent(window.location.pathname)}`; 27 }, 28 }, 29 }); 30 return; 31 } 32 void action(); 33 }, 34 [isAuthenticated, t], 35 ); 36 37 return { requireAuth, isAuthenticated }; 38}