How to Refactor different Passport Strategies to their own files

147 Views Asked by At

At this point, I have one single file with multiple passport strategies for local and third-party authentication. I am now trying to refactor each Strategy to its own file but that throws a bunch of errors.

I tried this :

passport.use("local-signup", signupStrategy); //in the main file and 

const signupStrategy = require('passport-local').Strategy({//function}); //in the other file

But this throws 'authentication strategies must have a name' Error.

How do I fix this?

1

There are 1 best solutions below

0
On

This is how I abstract strategies into their own files. Also note that the strategy name given in passport.use('local-signup') must match the name in passport.authenticate('local-signup') on the route.

main.js

// Require your strategies
const LocalStrategy = require('passport-local').Strategy;
// Require all the strategy callbacks
const localSignUpStrategy = require('./strategies/localSignup');

// Strategy configurations
passport.use('local-signup', new LocalStrategy(localSignUpStrategy));

localSignup.js

const localSignUpStrategy = async (username, password, done) => {
  try {
    const { dataValues: user } = await User.findOne({ where: { username } }) || {};
    // Send found user ID
    return done(null, user);
  } catch (err) {
    return done(err);
  }
};

module.exports = localLoginStrategy;