Saturday, May 29, 2021

getting the logged in user details

 In the router\users add below router to check the token and pass the information based on it.

router.get('/me',auth,async(req,res)=>{
 const user = (await User.findById(req.user._id)).isSelected('-password');// - means excluding the property 
});

the auth middleware is shared in the previous post and shown below again.

For logout, simplest is to implement logic to delete the token from browser of client.

middleware\auth.js

const jwt = require("jsonwebtoken");
const config = require("config");

function auth(reqresnext) {
  const token = req.header("x-auth-token");
  if (!tokenreturn res.status(401).send("Access denies, No token");
  try {
    const decoded = jwt.verify(tokenconfig.get("jwtPrivateKey"));
    req.user = decoded//whichever the payload in token gneeration, will be retrieved in decoded.
    next();
  } catch (ex) {
    res.status(400).send("Invalid token");
  }
}

module.exports = auth;

No comments:

Post a Comment