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:Jump to solution
This is my initial implemetation, works great:
```
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";...
4 Replies
Currently I have this middleware.ts that checks the user role and the companies that the user has access to.
The roles are:
- USER : Can access only the /dashboard/[companyId] route if the companyId is present in the token.companiesIds;
- ADMIN: Currently the same access as the USER role (other routes will be implemented in the future);
- SUPERADMIN: Can access all /dashboard/[companyId] independent if the companyId is present in their token.companiesIds.
All requests that try to access "/" or a /dashboard/[companyId] are redirected to /dashboard/[companyId] using the first companyId in token.companiesIds.
Is there a way to do this without using getServerSideProps on every route? (using /pages directory)
I thought about doing a wrapper component with the getServerSideProps check, and than wrapping the whole app with it, is there a cleaner way to do it?
if you are using jwts
you can't change the token after was created
your options are: use db sessions
YES! thank you, that is exactly what I needed, I was using JWT to protect the routes using middleware.ts, but that was the wrong choice.
Found a great article about protecting routes using a "AuthGuard" component:
https://dev.to/ivandotv/protecting-static-pages-in-next-js-application-1e50
DEV Community
Protecting static pages in Next.js application
In this article, I will explain how to structure your Next.js application so you can protect your sta...
Solution
This is my initial implemetation, works great: