I'm trying to confirm a user is making a post request so that way any one can't just post to the URL and do something malicious. How can I do this using express-session? Or is there a better way to do it?
I've tried this but I guess session doesn't exist in req post.
router.post('/delete', function (req, res, next) {
if (req.session.user.role === 'owner') {
// Authorized
// delete user here then redirect
res.redirect('/admin');
} else {
// Unauthorized
return res.redirect('/');
}
})
This can be done in many ways. One way is to send tokens in headers. To perform authorization, can use middlewares. as follows
Authentication Middleware :-
const auth = (req, res, next) => {
const token = req.header('auth-token');
if(!token) return res.status(401).send('Access denied. No token provided.');
try{
const decoded = jwt.verify(token, 'PRIVATE KEY'); // decoding token
req.user = decoded; // add token details to req
next();
}catch (ex){
res.status(400).send('Invalid Token');
}
}
Authorization Middleware :-
const admin = (req, res, next) => {
if(!req.user.isAdmin) return res.status(403).send('Access denied.');
next();
}
in router you can simply use middleware which will take care of authentication and authorization
router.post('/delete', [auth, admin], function (req, res, next) {
// do required operation
})