refactor: improve passport strategy handling in async/await manner to prevent race conditions upon importing modules (#682)

This commit is contained in:
Danny Avila 2023-07-22 07:29:17 -07:00 committed by GitHub
parent e38483a8b9
commit 6943f1c2c7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 273 additions and 246 deletions

View file

@ -1,26 +1,26 @@
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const User = require('../models/User');
// JWT strategy
const jwtLogin = new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
},
async (payload, done) => {
try {
const user = await User.findById(payload.id);
if (user) {
done(null, user);
} else {
console.log('JwtStrategy => no user found');
done(null, false);
const jwtLogin = async () =>
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
},
async (payload, done) => {
try {
const user = await User.findById(payload.id);
if (user) {
done(null, user);
} else {
console.log('JwtStrategy => no user found');
done(null, false);
}
} catch (err) {
done(err, false);
}
} catch (err) {
done(err, false);
}
},
);
},
);
passport.use(jwtLogin);
module.exports = jwtLogin;