Skip to content

Instantly share code, notes, and snippets.

@buddyeorl
Created October 12, 2020 09:18
Show Gist options
  • Save buddyeorl/db3a0af436a5dae9a41390ed355dec74 to your computer and use it in GitHub Desktop.
Save buddyeorl/db3a0af436a5dae9a41390ed355dec74 to your computer and use it in GitHub Desktop.
const jwt = require('jsonwebtoken');
const User = require('mongoose').model('User');
const Task = require('mongoose').model('Task');
const config = require('../../config');
/**
* The Auth Checker middleware function.
*/
module.exports = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).end();
}
// get the last part from a authorization header string like "bearer token-value"
const token = req.headers.authorization.split(' ')[1];
// decode the token using a secret key-phrase
return jwt.verify(token, config.jwtSecret, (err, decoded) => {
// the 401 code is for unauthorized status
if (err) { return res.status(401).end(); }
const userId = decoded.sub;
// check if a user exists
return User.findById(userId, (userErr, user) => {
if (userErr || !user) {
return res.status(401).end();
}
// pass user details onto next route
req.user = user
return next();
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment