next-admin icon indicating copy to clipboard operation
next-admin copied to clipboard

Authorization for Next admin

Open TanishqGupta12 opened this issue 9 months ago • 1 comments

Summary

How can I implement authorization for each model in the admin panel? I have different user roles, such as Super Admin, Admin, Normal User, and Custom User. I want to assign different permissions to each role:

Super Admin: Full access to all models.

Admin: Access to the User and Event models.

Normal User: Can only edit their own profile.

TanishqGupta12 avatar Mar 25 '25 08:03 TanishqGupta12

Hello @TanishqGupta12

This is something you can handle in different places, depending on the role you describe :

Admin: Access to the User and Event models.

This can be done in the page level directly

export default async function AdminPage(props: PromisePageProps) {
  const params = await props.params;
  const searchParams = await props.searchParams;
  const user = await myGetUserFunction()
 
  if (user.role === 'admin' && params.nextadmin[0].toLowerCase() !== 'user' || params.nextadmin[0].toLowerCase() !== 'event') {
     // handle forbidden access
  }
//...
}

Normal User: Can only edit their own profile.

The createHandler function that you use at the API route level has an onRequest function that is executed before anything else in the API. If a response is returned from this function, then it will be returned directly, without any other intercation that would normally happen.

const { run } = createHandler({
  apiBasePath: "/api/admin",
  options,
  prisma,
  onRequest: (req, res) => {
    // The same idea here using req.nextUrl or req.url
  }
});

export { run as DELETE, run as GET, run as POST };

foyarash avatar Apr 15 '25 12:04 foyarash