Next.js Discord

Discord Forum

Redirect if user is blocked

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
user has attribute status that can be active or blocked. sometimes others block you. if you are blocked and try to block other or any other request you make(any request like fetch users etc) you should redirect to /login page

8 Replies

Sun bearOP
what will be good way to do that
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function POST(request: Request) {
  const session: any = await getServerSession(authOptions);
  if (!session || session.status === "blocked") {
    return NextResponse.redirect(new URL("/login"));
  }
  const { selectedUsers } = await request.json();
  await prisma.users.updateMany({
    where: {
      id: {
        in: selectedUsers,
      },
    },
    data: {
      status: "blocked",
    },
  });
  return NextResponse.json({
    authenticated: true,
    session,
  });
}
actually i tried to add status in next auth configuration callbacks
but as i saw it doesnt work
so should i firstly fetch user and then check if user status here
or is there othe way
if the attribute is stored in jwt tokens, you can't ensure it's the latest data in your database.
Therefore, it's fine and recommended to use fetch the user first, then check if the user is blocked or not