Check DB or update session when DB role changes

I need to block access to certain routes based on the user's role and companies associated with they.
The problem I'm having is that if a user is already connected with a session, when their role is updated on the DB the session does not update, so it keeps the same role and companies, keeping the same permission as before.
Solution
This is my initial implemetation, works great:
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";

export function AuthGuard({ children }: { children: JSX.Element }) {
  const { status, data: session } = useSession();
  const router = useRouter();

  const adminRoutes = ["/admin"];
  const isAdminRoute = adminRoutes.some((route) =>
    router.pathname.startsWith(route)
  );
  const isRootRoute = router.pathname === "/";
  const isDashboardRouteAndIdNotSet =
    router.pathname.startsWith("/dashboard") && !router.query.companySlug;

  useEffect(() => {
    if (status !== "loading") {
      //auth is initialized and there is no user
      if (!session) {
        void signIn();
      }
    }
  }, [router, status, session]);

  /* show loading indicator while the auth provider is still initializing */
  if (status === "loading") {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <h1 className="text-5xl">Securing route</h1>
      </div>
    );
  }

  // if auth initialized with a valid user show protected page
  if (session) {
    // if user tries to access root route or /dashboard without a slug and is logged in, redirect to dashboard/[companySlug]
    if (isRootRoute || isDashboardRouteAndIdNotSet) {
      console.log("redirecting to dashboard");
      const companyName = session.user?.companies[0]?.name;
      void router.push(`/dashboard/${companyName}`);
      return null;
    }

    const isSuperAdmin = session.user?.role === "SUPERADMIN";

    // if user is not admin and tries to access admin routes, redirect to home
    if (!isSuperAdmin && isAdminRoute) {
      void router.push("/");
      return null;
    }

    return <>{children}</>;
  }

  /* otherwise don't return anything, will do a redirect from useEffect */
  return null;
}
Was this page helpful?