Created
August 8, 2017 19:34
-
-
Save Chun-Yang/75c6ddc97317dd8cb5d2c056fb3cdb0e 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
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