Skip to content

Instantly share code, notes, and snippets.

@Daniel-Sogbey
Last active May 17, 2022 08:49
Show Gist options
  • Save Daniel-Sogbey/edc2c5027bdeba225e33db8bc494929c to your computer and use it in GitHub Desktop.
Save Daniel-Sogbey/edc2c5027bdeba225e33db8bc494929c to your computer and use it in GitHub Desktop.
const jwt = require("jsonwebtoken")
const User = require("../models/user")
const auth = async (req, res, next) => {
try {
const token = req.header("Authorization").replace("Bearer ", "")
const decode = jwt.verify(token, "thisismysecretkey")
const user = await User.findOne({ _id: decode._id, "tokens.token": token })
if (!user) {
throw new Error()
}
req.token = token
req.user = user
next()
} catch (error) {
res.status(401).send({ error: "Please authenticate" })
}
}
module.exports = auth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment