Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Created July 12, 2020 06:34
Show Gist options
  • Select an option

  • Save heytulsiprasad/279c1b9ec2b695c7e925024c7aa89290 to your computer and use it in GitHub Desktop.

Select an option

Save heytulsiprasad/279c1b9ec2b695c7e925024c7aa89290 to your computer and use it in GitHub Desktop.
Middleware to verify a route is authenticated or not

401

This means, authorization is denied.

400

This means, authorization can't be completed due to something wrong in the client side.

const jwt = requier("jsonwebtoken")
function auth(req, res, next) {
const token = req.header("x-auth-token")
// Check for token
if (!token) res.status(401).json({msg: "No token, authorization denied"})
try {
// Verify token
const deciphered = jwt.verify(token, process.env.JWT_SECRET); // returns payload
// Add user from payload (to req object)
req.user = deciphered;
next();
} catch (error) {
res.status(400).json({msg: "Bad Token, Token is not valid."})
}
}
module.exports = auth;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment