Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Last active March 6, 2020 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heytulsiprasad/e029c7372d64bf68b7acb0c845db0db2 to your computer and use it in GitHub Desktop.
Save heytulsiprasad/e029c7372d64bf68b7acb0c845db0db2 to your computer and use it in GitHub Desktop.
design a middleware for a minimalistic application
const jwt = require("jsonwebtoken")
const User = require("../models/user")
const auth = async (req, res, next) => {
try {
const token = req.header("Authorization").replace("Bearer", "")
const decoded = jwt.verify(token, "thegivensecret")
const user = await User.findOne({
_id: decoded._id,
"tokens.token": token
})
if (!user) {
throw new Error();
}
req.token = token;
req.user = user;
next();
} catch (e) {
res.status(401).send({"Please authenticate"});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment