Skip to content

Instantly share code, notes, and snippets.

@Chun-Yang
Created August 8, 2017 19:34
Show Gist options
  • Save Chun-Yang/75c6ddc97317dd8cb5d2c056fb3cdb0e to your computer and use it in GitHub Desktop.
Save Chun-Yang/75c6ddc97317dd8cb5d2c056fb3cdb0e to your computer and use it in GitHub Desktop.
import { Strategy, ExtractJwt } from 'passport-jwt';
import passport from 'passport';
import { MongoClient } from 'mongodb';
function authenticateHOF({ mongoUrl, collectionName = 'users' }) {
const mongoPromise = MongoClient.connect(mongoUrl);
passport.use(new Strategy(
{
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: process.env.TOKEN_SECRET,
},
async (jwtPayload, done) => {
const mongo = await mongoPromise;
const user = await mongo.collection(collectionName).findOne({ _id: jwtPayload.id });
done(null, user || false);
},
));
function authenticate(req, res, next) {
// validate user token if there is one
// assign the user to req if valid token
passport.authenticate('jwt', { session: false }, (err, user) => {
if (user) {
req.user = user;
}
next();
})(req, res, next);
}
return authenticate;
}
export default authenticateHOF;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment