Files
mwitnessing/components/protectedRoute.tsx
Dobromir Popov bab62816b0 only use blocked date and no published date for blocking;
allow any date to be selected as block date - not only the end of the month
2024-09-17 23:18:51 +03:00

94 lines
3.4 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;
autoRedirect?: boolean;
}
const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false, autoRedirect = 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 (autoRedirect) {
signIn();
}
}
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 className="flex items-center justify-center min-h-screen">
<div className="text-center">
<h1 className="text-2xl font-bold mb-4 text-blue-500">{session?.user?.email},</h1>
<p className="mb-6">{`Нямате достъп до тази страница.`}</p>
<p className="mb-6">{`Ако мислите, че това е грешка, моля, свържете се с администраторите`}</p>
</div>
</div>
</>);
}
if (status === "loading") {
return <div>Зареждане...</div>;
}
if (!session) {
if (deniedMessage !== undefined) {
return <div>{deniedMessage}</div>;
}
return <a href="/api/auth/signin">Защитено съдържание. Впишете се.. </a>
}
};
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 };
}
// Static method to check if the user has a specific role
ProtectedRoute.IsInRole = async (roleName) => {
const session = await getSession();
return (session && session.user && session.user.role === roleName) || false;
};
ProtectedRoute.GetCurrentUserId = async () => {
const session = await getSession();
return session && session.user && session.user.id;
}