Assignment: Creating an auth middleware
Course: Authentication - chapter 10
Can you try creating a middleware called auth that verifies if a user is logged in and ends the request early if the user isn’t logged in?
Solution
function auth(req, res, next) { const token = req.headers.authorization;
if (token) { jwt.verify(token, JWT_SECRET, (err, decoded) => { if (err) { res.status(401).send({ message: "Unauthorized" }) } else { req.user = decoded; next(); } }) } else { res.status(401).send({ message: "Unauthorized" }) }}
app.get("/me", auth, (req, res) => { const user = req.user;
res.send({ username: user.username })})