2024-12-27 15:23:39 +00:00
|
|
|
'use client';
|
2024-12-23 19:13:36 +00:00
|
|
|
|
2025-01-02 12:47:39 +00:00
|
|
|
import { useEffect, useState } from 'react';
|
2024-12-27 15:23:39 +00:00
|
|
|
import { useRouter } from 'next/navigation';
|
|
|
|
|
import { useLotteryAuth } from '@/store/useLotteryAuth';
|
2025-01-02 12:47:39 +00:00
|
|
|
import { Queries } from '@/api/queries';
|
2024-12-23 19:13:36 +00:00
|
|
|
|
2025-01-02 12:47:39 +00:00
|
|
|
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
|
2024-12-23 19:13:36 +00:00
|
|
|
const router = useRouter();
|
2025-01-02 12:47:39 +00:00
|
|
|
const { isAuthenticated, phone, code, setAuth } = useLotteryAuth();
|
|
|
|
|
const [isLoading, setIsLoading] = useState(true);
|
2024-12-23 19:13:36 +00:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
2025-01-02 12:47:39 +00:00
|
|
|
const checkAuth = async () => {
|
|
|
|
|
// First, check if we have credentials in localStorage
|
|
|
|
|
if (phone && code) {
|
|
|
|
|
try {
|
|
|
|
|
// Try to authenticate with stored credentials
|
|
|
|
|
const response = await Queries.authenticateLottery(phone, code);
|
|
|
|
|
setAuth(response, phone, code);
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
return; // Exit early if authentication successful
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Authentication failed:', err);
|
|
|
|
|
// Only redirect if API request fails
|
|
|
|
|
router.replace('/lottery/auth');
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// Only redirect if no credentials found
|
|
|
|
|
router.replace('/lottery/auth');
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
checkAuth();
|
|
|
|
|
}, []);
|
2024-12-23 19:13:36 +00:00
|
|
|
|
2025-01-02 12:47:39 +00:00
|
|
|
// Show nothing while checking auth
|
|
|
|
|
if (isLoading) {
|
2024-12-27 15:23:39 +00:00
|
|
|
return null;
|
2024-12-23 19:13:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return <>{children}</>;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default ProtectedRoute;
|