Created
October 2, 2019 14:54
-
-
Save muddokon/74ff484114abb9e635af28448430f625 to your computer and use it in GitHub Desktop.
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) => { | |
const token = req.header('Authorization').replace('Bearer ', '') | |
const data = jwt.verify(token, process.env.JWT_KEY) | |
try { | |
const user = await User.findOne({ _id: data._id, 'tokens.token': token }) | |
if (!user) { | |
throw new Error() | |
} | |
req.user = user | |
req.token = token | |
next() | |
} catch (error) { | |
res.status(401).send({ error: 'No tiene autorización para ver este recurso' }) | |
} | |
} | |
module.exports = auth |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment