Barazo default frontend barazo.forum
at main 38 lines 1.1 kB view raw
1'use client' 2 3import { useCallback } from 'react' 4import { useAuth } from '@/hooks/use-auth' 5import { useToast } from '@/hooks/use-toast' 6 7/** 8 * Returns a guard function that checks auth state before performing an action. 9 * If the user is not authenticated, shows a toast prompting them to log in. 10 * If authenticated, executes the callback. 11 */ 12export function useRequireAuth() { 13 const { isAuthenticated } = useAuth() 14 const { toast } = useToast() 15 16 const requireAuth = useCallback( 17 (action: () => void | Promise<void>) => { 18 if (!isAuthenticated) { 19 toast({ 20 title: 'Login required', 21 description: 'You need to log in before you can perform this action.', 22 action: { 23 label: 'Log in', 24 altText: 'Go to login page', 25 onClick: () => { 26 window.location.href = `/login?returnTo=${encodeURIComponent(window.location.pathname)}` 27 }, 28 }, 29 }) 30 return 31 } 32 void action() 33 }, 34 [isAuthenticated, toast] 35 ) 36 37 return { requireAuth, isAuthenticated } 38}