Passport JWT Node + Passport + Express code example

Example 1: express passport js

// my github https://github.com/restuwahyu13
const { AuthSchema } = require('../models/model.auth')
const passport = require('passport')
const JwtStrategy = require('passport-jwt').Strategy
const ExtractJwt = require('passport-jwt').ExtractJwt
const LocalStrategy = require('passport-local').Strategy

exports.passportSerialize = () => {
  return passport.serializeUser(async (user, done) => {
    if (user) {
      const { _id } = user
      const result = await AuthSchema.findById(_id).lean()
      if (!result) return done(null, false)
      return done(null, result._id)
    }
    return done(null, false)
  })
}

exports.passportDeserialize = () => {
  return passport.deserializeUser(async (id, done) => {
    if (id) {
      const user = await AuthSchema.findById(id).lean()
      if (!user) return done(null, false)
      return done(null, user)
    }
    return done(null, false)
  })
}

// passport local
exports.passportLocalStrategy = () => {
  passport.use(
    'local',
    new LocalStrategy(async (username, password, done) => {
      if (username && password) {
        const user = await AuthSchema.find({ $or: [{ username }, { email: username }] }).lean()
        const verify = AuthSchema.verifyPassword(password, user[0].password)

        if (!verify) return done(null, false)
        return done(null, user[0])
      }
      return done(null, false)
    })
  )
}

// passport jwt
exports.passportJwtStrategy = () => {
  passport.use(
    'jwt',
    new JwtStrategy(
      {
        secretOrKey: process.env.JWT_SECRET,
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
      },
      async ({ _id }, done) => {
        try {
          const user = await AuthSchema.findById(_id).lean()
          if (!user) done(null, false)
          done(null, user)
        } catch (err) {
          done(err, false)
        }
      }
    )
  )
}

Example 2: express passport js

// my github https://github.com/restuwahyu13

const { AuthSchema } = require('../models/model.auth')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const FacebookStrategy = require('passport-facebook').Strategy
const GithubStrategy = require('passport-github').Strategy

// passport facebook
exports.passportFacebook = () => {
   return passport.use(
      new FacebookStrategy(
         {
            clientID: process.env.FACEBOOK_ID,
            clientSecret: process.env.FACEBOOK_SECRET,
            callbackURL: "http://localhost:3000/auth/facebook/callback",
            profileFields: ["id", "displayName", "gender", "email", "photos"],
            enableProof: true,
         },
         (accessToken, refreshToken, profile, done) => {
            authSocialSchema.findOne({idSocial: profile.id}, (err, user) => {
               if (err) return done(err, false);
               if (!user) {
                  authSocialSchema.findOrCreate(
                     {
                        idSocial: profile.id,
                        fullname: profile.displayName,
                        email: profile.email,
                        gender: profile.gende,
                        avatar: profile.photos[0]["value"],
                        provider: profile.provider,
                        created_at: Date.now(),
                     },
                     (err, user) => {
                        if (err) return done(err, false);
                        return done(null, user);
                     }
                  );
               } else {
                  return done(null, user);
               }
            });
         }
      )
   );
}

// passport google
exports.passportGoogle = () => {
   return passport.use(
      new GoogleStrategy(
         {
            clientID: process.env.GOOGLE_ID,
            clientSecret: process.env.GOOGLE_SECRET,
            callbackURL: "http://localhost:3000/auth/google/callback",
         },
         (accessToken, refreshToken, profile, done) => {
            authSocialSchema.findOne({idSocial: profile.id}, (err, user) => {
               if (err) return done(err, false);
               if (!user) {
                  authSocialSchema.findOrCreate(
                     {
                        idSocial: profile.id,
                        fullname: profile.displayName,
                        email: profile.emails[0]["value"],
                        avatar: profile.photos[0]["value"],
                        provider: profile.provider,
                        created_at: Date.now(),
                     },
                     (err, user) => {
                        if (err) return done(err, false);
                        return done(null, user);
                     }
                  );
               } else {
                  return done(null, user);
               }
            });
         }
      )
   );
}

// passport passport github
exports.passportGithub = () => {
   return passport.use(
      new GithubStrategy(
         {
            clientID: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
            callbackURL: "http://localhost:3000/auth/github/callback",
         },
         (accessToken, refreshToken, profile, done) => {
            authSocialSchema.findOne({idSocial: profile.id}, (err, user) => {
               if (err) return done(err, false);
               if (!user) {
                  authSocialSchema.findOrCreate(
                     {
                        idSocial: profile.id,
                        username: profile.username,
                        fullname: profile.displayName,
                        avatar: profile.photos[0]["value"],
                        provider: profile.provider,
                        created_at: Date.now(),
                     },
                     (err, user) => {
                        if (err) return done(err, false);
                        return done(null, user);
                     }
                  );
               } else {
                  return done(null, user);
               }
            });
         }
      )
   );
}