feat(auth): add protected routes and enhance auth context

Implement protected routes for admin and dashboard pages to restrict access based on authentication and admin status. Enhance the auth context to handle user data validation and improve error handling during authentication checks.
This commit is contained in:
Daniel Luiz Alves
2025-04-08 15:06:17 -03:00
parent 9e35d27497
commit b077154c22
4 changed files with 73 additions and 1 deletions

View File

@@ -0,0 +1,16 @@
"use client";
import { ProtectedRoute } from "@/components/auth/protected-route";
function AdminPage() {
return (
<ProtectedRoute requireAdmin>
<div>
<h1>Admin Dashboard</h1>
{/* Your admin content */}
</div>
</ProtectedRoute>
);
}
export default AdminPage;

View File

@@ -0,0 +1,16 @@
"use client";
import { ProtectedRoute } from "@/components/auth/protected-route";
function DashboardPage() {
return (
<ProtectedRoute>
<div>
<h1>Dashboard</h1>
{/* Your dashboard content */}
</div>
</ProtectedRoute>
);
}
export default DashboardPage;

View File

@@ -0,0 +1,34 @@
"use client";
import { useAuth } from "@/contexts/auth-context";
import { useRouter } from "next/navigation";
import { useEffect, type ReactNode } from "react";
import { LoadingScreen } from "../layout/loading-screen";
type ProtectedRouteProps = {
children: ReactNode;
requireAdmin?: boolean;
};
export function ProtectedRoute({ children, requireAdmin = false }: ProtectedRouteProps) {
const { isAuthenticated, isAdmin } = useAuth();
const router = useRouter();
useEffect(() => {
if (isAuthenticated === false) {
router.replace("/login");
} else if (requireAdmin && isAdmin === false) {
router.replace("/dashboard");
}
}, [isAuthenticated, isAdmin, requireAdmin, router]);
if (isAuthenticated === null || (requireAdmin && isAdmin === null)) {
return <LoadingScreen />;
}
if (!isAuthenticated || (requireAdmin && !isAdmin)) {
return null;
}
return <>{children}</>;
}

View File

@@ -41,6 +41,10 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const checkAuth = async () => {
try {
const response = await getCurrentUser();
if (!response?.data?.user) {
throw new Error("No user data");
}
const { isAdmin, ...userData } = response.data.user;
setUser(userData);
@@ -48,7 +52,9 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
setIsAuthenticated(true);
} catch (err) {
console.error(err);
logout();
setUser(null);
setIsAdmin(false);
setIsAuthenticated(false);
}
};