Last active
March 6, 2020 16:39
-
-
Save heytulsiprasad/e029c7372d64bf68b7acb0c845db0db2 to your computer and use it in GitHub Desktop.
design a middleware for a minimalistic application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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