social-platform-donut-backend
social-platform-donut-backend copied to clipboard
Role based features
Description
In this issue, we want to build a mechanism where in we have two types of privileges: 1.User 2.Admin Where in user are allowed to do only certain tasks based on there privileges.
Example:
- User cannot only edit organization level details where in an admin of that org has rights to do so.
Requirements
Resources
How you are planning to implement this functionality? Can't we do this using one flag value in schema to switch between the role? @devesh-verma
Hi @Rupeshiya @devesh-verma . Is this issue still active ? If so, can I take up this issue ?
I see as suggested by @Rupeshiya , isAdmin flag is being used. However, in addition to that, I wish to suggest a more flexible and extendable option that places a 'restrict' middleware before an API router as mentioned in this gist. This would accommodate any future role addition and add restrictions to routes without changing the api-endpoint's business logic.
Hey @aashaypalliwar, I just checked the gist, so basically what you are doing is that making a middleware call to check is the user's role is admin or superAdmin but don't you think it will increase the no of calls, as it's getting executed on each admin routes?
Your middleware adminRouter.use(protect, restrictTo('admin','superAdmin'));
@Rupeshiya , No, it will not have any performance issue per se. Every user is bound to be authenticated using JWT (as is already being done in the project). Upon JWT verification, the user information is being stored in req.user
. Every route that needs to be restricted to a particular role will be guarded by this middleware which simply checks the role indicated in the req.user
object. The restrictTo
middleware will be guarding appropriate groups of routes, thus preventing repetitive code in each of these routes' logic.
@aashaypalliwar I am saying how middleware will check? after each calling that function right?? So basically it will call every time when any request will be sent to the backend, so will not increase the time of each request as that middleware function need some ms to execute??
@Rupeshiya That's what the beauty of express router is! It won't happen. If you place these middleware in respective router say, for example userRouter
, it wont be invoked unless the route /user/*
is invoked. Basically, as you might be knowing, the express router is like a mini-app. Our main app would delegate the request to this router when the request begins with the router's parent endpoint ( /user
in this case), otherwise it won't be invoked.