In my app (Mongo,Express,Node,React), I'm currently authenticating users from the client to the server using JSON Web tokens. However, I want to be able to have two different types of users access different halves of the app. What is the best way to go about this? I currently have both types of users saved in the same model with a boolean that differentiates them. To clarify, different types of users would be able to access different API's as well as different portions of the client side app.
Is there a package that handles this? JWT feature?
There are 2 ways that you may do this:
Most of the packages will allow you to define what you want to encode.
Tips:
Always set an expiry on your tokens. It's simply a date stored on the JWT. When you decode the token just make sure that the date is in future, if not deny access.
Create a middleware that checks the user's role. For example:
router.get('/restricted-area', requiresAdmin, (req, res, next) => {
// only admin can access this
});
function requiresAdmin(req, res, next) {
if(req.user.admin !== true) {
res.status(401).end();
} else {
next();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With