14

I've been failing to get passport.authenticate to work at all inside of an async/await or promise pattern. Here is an example I feel should work, but it fails to execute passport.authenticate().

const passport = require("passport");

let user;

try {
    user = await __promisifiedPassportAuthentication();

    console.log("You'll never have this ", user);
} catch (err) {
    throw err;
}

function __promisifiedPassportAuthentication() {
    return new Promise((resolve, reject) => {

        console.log("I run");

        passport.authenticate('local', (err, user, info) => {

            console.log("I never run");

            if (err) reject(err);
            if (user) resolve(user);
        }
    }
}

Any sage words of wisdom would be greatly appreciated.

Kyle Richardson
  • 5,567
  • 3
  • 17
  • 40

1 Answers1

21

Just incase any other tired programmer out there encounters this..

function __promisifiedPassportAuthentication() {
    return new Promise((resolve, reject) => {
        passport.authenticate('local', (err, user, info) => {
            ...
        })(req, res) // <-- that guy right there
    }
}
Kyle Richardson
  • 5,567
  • 3
  • 17
  • 40
  • Missing a `)` before `(req, res)` – Raul Rene Aug 31 '17 at 12:32
  • 5
    Shouldn't `req` and `res` be passed to `promisifiedPassportAuthentication`? – lolbas Feb 08 '18 at 15:35
  • Wow, I was stuck on this for ages. Thanks a lot! – Jean-Paul Dec 19 '18 at 21:14
  • upvoted! cant you use util.promisify on this instead of duplicating the entire method inside a promise? – PirateApp Dec 28 '19 at 16:28
  • I'm running the following and I'm getting "Reference error: req is not defined" ------- function promisifiedPassportAuthentication() { return new Promise((resolve, reject) => { passport.authenticate('spotify', { failureRedirect: '/login' }, (err, user, info) => { if (err) reject(err); if (user) resolve(user); })(req, res) }) } – Alexander Feb 03 '21 at 17:18
  • without passing "next", (req, res, next) it does not work for me, because it doesn't log you in. – TodorBalabanski Feb 17 '22 at 14:13