Files
mwitnessing/components/protectedRoute.tsx
2024-02-22 04:19:38 +02:00

71 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// components/ProtectedRoute.tsx
import { useSession, signIn } from "next-auth/react";
import { useEffect, ReactNode } from "react";
import { useRouter } from 'next/router';
import { UserRole } from '../Enums/UserRole';
import { getSession } from "next-auth/react";
interface ProtectedRouteProps {
children: ReactNode;
allowedRoles: UserRole[];
deniedMessage?: string;
bypass?: boolean;
}
const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false }: ProtectedRouteProps) => {
const { data: session, status } = useSession()
const router = useRouter();
useEffect(() => {
console.log("session.role:" + session?.user?.role);
if (!status || status === "unauthenticated") {
// Redirect to the sign-in page
if (!bypass) {
signIn();
}
return null;
}
else {
console.log("session.role:" + session?.user?.role);
}
}, [session, status, router]);
if (status === "authenticated") {
const userRole = session.user.role as UserRole; // Assuming role is part of the session object
// Grant access if allowedRoles is not defined, or if the user's role is among the allowed roles
if (bypass || !allowedRoles || (allowedRoles && allowedRoles.includes(userRole))) {
return <>{children}</>;
}
// Handle denied access
if (deniedMessage !== undefined) {
return <div>{deniedMessage}</div>;
}
return <div>Нямате достъп до тази страница. Ако мислите, че това е грешка, моля, свържете се с администраторите</div>;
}
if (status === "loading") {
return <div>Зареждане...</div>;
}
if (!session) return <a href="/api/auth/signin">Защитено съдържание. Впишете се.. </a>
return children;
};
export default ProtectedRoute;
export async function serverSideAuth({ req, allowedRoles }) {
const session = await getSession({ req });
if (!session || (allowedRoles && !allowedRoles.includes(session.user.role))) {
// User is not authenticated or doesn't have the required role
return {
redirect: {
destination: '/api/auth/signin', // Redirect to the sign-in page
permanent: false,
},
};
}
// Return the session if the user is authenticated and has the required role
return { session };
}