Skip to content

Instantly share code, notes, and snippets.

@Bilguun132
Last active March 18, 2019 13:04
Show Gist options
  • Select an option

  • Save Bilguun132/048faba84ae0cb80445bd4fa4ae84a64 to your computer and use it in GitHub Desktop.

Select an option

Save Bilguun132/048faba84ae0cb80445bd4fa4ae84a64 to your computer and use it in GitHub Desktop.
nodejs-auth-Tutorial-auth.js
const jwt = require("jsonwebtoken");
const config = require("config");
module.exports = function(req, res, next) {
//get the token from the header if present
const token = req.headers["x-access-token"] || req.headers["authorization"];
//if no token found, return response (without going to the next middelware)
if (!token) return res.status(401).send("Access denied. No token provided.");
try {
//if can verify the token, set req.user and pass to next middleware
const decoded = jwt.verify(token, config.get("myprivatekey"));
req.user = decoded;
next();
} catch (ex) {
//if invalid token
res.status(400).send("Invalid token.");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment