Spaces:
Sleeping
Sleeping
File size: 1,748 Bytes
f871fed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
'use client'
import { useAuthStore } from '@/lib/stores/auth-store'
import { useRouter } from 'next/navigation'
import { useEffect } from 'react'
export function useAuth() {
const router = useRouter()
const {
isAuthenticated,
isLoading,
login,
logout,
checkAuth,
checkAuthRequired,
error,
hasHydrated,
authRequired
} = useAuthStore()
useEffect(() => {
// Only check auth after the store has hydrated from localStorage
if (hasHydrated) {
// First check if auth is required
if (authRequired === null) {
checkAuthRequired().then((required) => {
// If auth is required, check if we have valid credentials
if (required) {
checkAuth()
}
})
} else if (authRequired) {
// Auth is required, check credentials
checkAuth()
}
// If authRequired === false, we're already authenticated (set in checkAuthRequired)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasHydrated, authRequired])
const handleLogin = async (password: string) => {
const success = await login(password)
if (success) {
// Check if there's a stored redirect path
const redirectPath = sessionStorage.getItem('redirectAfterLogin')
if (redirectPath) {
sessionStorage.removeItem('redirectAfterLogin')
router.push(redirectPath)
} else {
router.push('/notebooks')
}
}
return success
}
const handleLogout = () => {
logout()
router.push('/login')
}
return {
isAuthenticated,
isLoading: isLoading || !hasHydrated, // Treat lack of hydration as loading
error,
login: handleLogin,
logout: handleLogout
}
} |