When creating the JWT token, you can store information within it, such as the user id, the user name, and the access level him. Having its access level, you can create a middleware that checks whether the access level of that JWT is valid or invalid, and if valid, allows access to that route.
In the code below, I created a middleware that checks whether JWT is valid, and if so, stores its information in req.usuario.
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
jwt.verify(req.headers['x-access-token'], process.env.JWT_SECRET, (err, decodedToken) => {
if (err) return res.status(401).json({ error: 'Você não tem autorização para continuar!' });
req.usuario = decodedToken;
return next();
});
};
In the code below, I created a middleware that checks the access level of req.usuario.
module.exports = (nivel) => {
return (req, res, next) => {
if (!req.usuario.nivel || req.usuario.nivel < nivel) return res.status(401).json({ error: 'Você não tem autorização para continuar!' });
return next();
};
};
If you want a full example, I have a repository that I use to study React.js, but I’ve already implemented the authentication part.
https://github.com/andreolvr/aprendendo-react
The codes you’re interested in are in server/middleware and app.js, to see how I apply this middleware to routes.