Authorization for Next admin
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.
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 };