node.js - NodeJs, Mongoose: what's the best way to check auth before update? -
i want check if logged-in user(req.user) same person made post(post.author, it's objectid refering user) before update data. restrict route update form i'm double checking in case.
this code working, want know if there simpler or better way this.
app.put('/posts/:id', isloggedin, function(req,res){ post.findbyid(req.params.id, function (err,post) { if(!req.user._id.equals(post.author)) return res.json({success:false, message:"unauthrized attempt"}); post.findbyidandupdate(req.params.id, req.body.post, function (err,post) { res.redirect('/posts/'+req.params.id); }); }); });
i found better way.
app.put('/posts/:id', isloggedin, function(req,res){ post.findoneandupdate({_id:req.params.id,author:req.user._id}, req.body.post, function (err,post) { res.redirect('/posts/'+req.params.id); }); });
Comments
Post a Comment