I'm creating a blog using the latest MEAN Stack technologies. A logged in user can create a new user with the roles 'admin' and 'moderator.
Creating a new user with an admin role or moderator role
This route is protected and currently, only a logged in user can access it. Here is the middleware for checking if the user is authenticated or not.
//check_auth.js
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
jwt.verify(token, 'my_jwt_secret');
next();
} catch (error) {
res.status(401).json({ message: 'Auth failed!'});
}
};
I apply this middleware to protect unauthorized access to some of my routes. I want to create a similar middleware in which I check if the user is an administrator or not. So I can apply this middleware on the route for creating users, so only an authorized user and a user who has the role of 'admin' can create a new user.
I think this can help in creating the middleware. When a user logs in the id, email, and role is stored in the jwt.
router.post("/login", (req, res, next) => {
let fetchedUser;
User.findOne({ email: req.body.email })
.then(user => {
if (!user) {
return res.status(401).json({
message: "Auth failed"
});
}
fetchedUser = user;
return bcrypt.compare(req.body.password, user.password);
})
.then(result => {
if (!result) {
return res.status(401).json({
message: "Auth failed"
});
}
const token = jwt.sign(
{ email: fetchedUser.email, userId: fetchedUser._id, role: fetchedUser.role },
"my_jwt_secret",
{ expiresIn: "1h" }
);
res.status(200).json({
token: token,
expiresIn: 3600
});
})
.catch(err => {
return res.status(401).json({
message: "Auth failed"
});
});
});
The whole code can be found in my GitHub repository: https://github.com/rajotam/Eleven
Add a Route Handler to all endpoints that need verification and import it wherever needed. https://expressjs.com/en/guide/routing.html
ex.
router.post('/login', verify.isAdmin, (req, res, next) => {
//do something
})
//verify function in separate file
module.exports = {
isAdmin: (req, res, next) =>{
if(req.user.admin){
next();
}else{
res.status(403).send();
}
}
}
Full code examples:
https://medium.freecodecamp.org/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52