How to get the value from a promise based passport-local strategy? How to get the value from a promise based passport-local strategy? express express

How to get the value from a promise based passport-local strategy?


The main thing you need to note is that Strategy's API doesn't deal in Promises. You'll have to deal with the callback argument that it wants. You can see the function signature here: Configure Strategy. In my implementation, my User deals with Promises and just calls the callback from within the then() of the Promise.

Since you have to hand the Strategy that you want to use to passport, and passport expects something with the callback convention, you'll have to follow its API. As of right now, passport does not really support Promises within its API. I'd say take a look at the passport issue Add support promises flow and add support for integrating with promises. I don't think it'll happen until express migrates as well though.

This is the way that I use Strategys to deal with async login:

const express = require("express"),    passport = require("passport"),    Strategy = require("passport-local").Strategy,    User = require("../models/user"),    router = express.Router();// Strategy to authenticate a userconst localStrategy = new Strategy((username, password, cb) => {    User.authenticate(username, password).then((result) => {        if (result.success) {            cb(null, result.user);        } else {            cb(null, false);        }    }, cb);});function ensureLoggedIn(req, res, next) {    if (req.isAuthenticated()) {        return next();    }    res.redirect("/login");}// Utilize the strategypassport.use(localStrategy);router.use(require("./passify"));router.use("/profile", ensureLoggedIn, require("./profile"));