turkmentv_front/components/lottery/auth/ProtectedRoute.tsx

51 lines
1.4 KiB
TypeScript
Raw Normal View History

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);
2025-01-09 12:36:40 +00:00
if (response.errorMessage) {
router.replace('/lottery/auth');
} else {
setAuth(response, phone, code);
setIsLoading(false);
}
2025-01-02 12:47:39 +00:00
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;