turkmentv_front/components/lottery/auth/ProtectedRoute.tsx

54 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-01-29 13:27:26 +00:00
"use client";
2024-12-23 19:13:36 +00:00
2025-01-29 13:27:26 +00:00
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useLotteryAuth } from "@/store/useLotteryAuth";
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-10 12:31:34 +00:00
const { isAuthenticated, setAuth } = useLotteryAuth();
2025-01-02 12:47:39 +00:00
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 () => {
2025-01-10 12:31:34 +00:00
// ✅ Check credentials from localStorage
2025-01-29 13:27:26 +00:00
const phone = localStorage.getItem("lotteryPhone");
const code = localStorage.getItem("lotteryCode");
2025-01-10 12:31:34 +00:00
2025-01-02 12:47:39 +00:00
if (phone && code) {
try {
2025-01-10 12:31:34 +00:00
// ✅ Authenticate using stored credentials
2025-01-02 12:47:39 +00:00
const response = await Queries.authenticateLottery(phone, code);
2025-01-09 12:36:40 +00:00
if (response.errorMessage) {
2025-01-10 12:31:34 +00:00
// If authentication fails, redirect to the auth page
2025-01-29 13:27:26 +00:00
router.replace("/lottery/auth");
2025-01-09 12:36:40 +00:00
} else {
2025-01-10 12:31:34 +00:00
// ✅ Set the authenticated state
2025-01-09 12:36:40 +00:00
setAuth(response, phone, code);
setIsLoading(false);
}
2025-01-02 12:47:39 +00:00
} catch (err) {
2025-01-29 13:27:26 +00:00
console.error("Authentication failed:", err);
router.replace("/lottery/auth");
2025-01-02 12:47:39 +00:00
}
} else {
2025-01-10 12:31:34 +00:00
// Redirect to the auth page if no credentials are found
2025-01-29 13:27:26 +00:00
router.replace("/lottery/auth");
2025-01-02 12:47:39 +00:00
}
};
checkAuth();
2025-01-10 12:31:34 +00:00
}, [router, setAuth]);
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;