The function
import { getServerAuthSession } from "../server/auth";
import type { Session } from "next-auth";
import type { Role } from "@prisma/client";
type Callback = (data: { session: Session }) => void;
type RoleRedirects = {
[key: string]: {
[key: string]: string;
};
};
const roleRedirects: RoleRedirects = {
user: {
// Only allow users to access their own page
USER: "/dashboard/user/home",
},
admin: {
// Allow admins to access both the admin and user pages
USER: "/dashboard/user",
ADMIN: "/dashboard/accounts-management",
},
};
export async function roleGuard(
ctx: GetServerSidePropsContext,
cb: Callback,
role: Role
) {
try {
const session = await getServerAuthSession(ctx);
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
// Check if the user has the required role or is an admin
const userRole = session.user?.role as Role;
if (userRole !== role && userRole !== "admin") {
// Redirect to the home page if the user doesn't have the required role
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
// Determine the redirection destination based on the user's role
const redirectDestination = roleRedirects[role]?.[userRole];
if (redirectDestination) {
// Redirect to the appropriate page if needed
return {
redirect: {
destination: redirectDestination,
permanent: false,
},
};
}
// Call the callback function with the session object
return cb({ session });
} catch (error) {
// Redirect to the home page in case of errors
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
}