I am trying to make some kind of server middleware that verifies the auth state of a user to render the page. It's working but I want to access the current user if authenticated and authorized without recalling unstable_getServerSession.
The function I implemented:
export const requireAuth =
(role: Role, func: GetServerSideProps) => async (ctx: GetServerSidePropsContext) => {
const session = await unstable_getServerSession(
ctx.req,
ctx.res,
authOptions
);
if (!session || (session as Session).user?.role !== role) {
return {
redirect: {
destination: "/auth/login", // login path
permanent: false,
},
};
}
return await func(ctx); // I want to pass the user here
};
The execution context of that function :
const Page = () => {
return (
...page
);
};
export const getServerSideProps = requireAuth('ADMIN', async (ctx) => {
// I want to be able to access the currently authenticated user here without
// repeating the same process above
return { props: {} };
});
export default Page;