passport.authenticate() using a Promise instead of a Custom Callback

寵の児 提交于 2021-01-27 12:14:07

问题


passport.authenticate(), how can I define a Promise instead of using a Custom Ballback?

How to used passport.authenticate() is referenced within here: http://www.passportjs.org/docs/authenticate/

Within this page, there is a section Custom Ballback:

If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

The Custom Callback is defined as:

function(err, user, info){...}

What I wish to do is replace this Custom Callback with a Promise.

[Promise](resolve, reject)
.then(res => {
})
.catch(err => {
})

How can I do this? Thank you.


回答1:


You can use the es6-promisify package. It is very easy to use, here is an example:

const {promisify} = require("es6-promisify");

// Convert the stat function
const fs = require("fs");
const stat = promisify(fs.stat);

// Now usable as a promise!
stat("example.txt").then(function (stats) {
    console.log("Got stats", stats);
}).catch(function (err) {
    console.error("Yikes!", err);
});



回答2:


Thanks all for your helpful responses @sterling-archer and @el-finito

I had found a related issue within Passport.js Github repository helpful for using Passport to handle passport.authenticate() callback: "Using node's promisify with passport"

export const authenticate = (req, res) =>
  new Promise((resolve, reject) => {
    passport.authenticate(
      [passport strategy],
      { session: false },
      (err, user) => {
        if (err) reject(new Error(err))
        else if (!user) reject(new Error('Not authenticated'))
        resolve(user)
      })(req, res)
    })


来源:https://stackoverflow.com/questions/55328833/passport-authenticate-using-a-promise-instead-of-a-custom-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!