自定义回调passportjs?

时间:2015-02-01 00:31:34

标签: javascript node.js express passport.js

我有一个订购表格,用户需要在他/她可以订购之前注册,所以我可以创建一个帐户,然后像这样处理订单。

router.post('/project/new', passport.authenticate('local-signup'), function(req, res) {

  gateway.customer.find(req.user.id, function(err, customer) {

    if(customer) {

      // method for a customer inside the vault

    } else {

      // add a non existing customer to vault

    }

  });

});

问题是如果有人已登录并想要下订单。我需要检查他们是否已登录,如果是,那么我可以继续执行订单,如果他们不是,那么我需要进行身份验证然后登录。

所以这样的事情对我有意义。

//prefer this!!
router.post('/project/new', function(req, res) {

  if(req.user) {

    // do stuff for existing logged in user

  } else {

    // user is NOT logged in need passport
    passport.authenticate('local-signup', function(err, user, info) {

      // do stuff for new user

    })(req, res, next);

  }

});

问题在于我得到next is not defined,我在passportjs docs中看到Jared在get路由中使用了这个自定义回调。

有人可以帮我制作自定义回调吗?有没有人有更好的策略?

1 个答案:

答案 0 :(得分:1)

未定义,因为您尚未对其进行定义,您可以将其定义为:

router.post('/project/new', function(req, res, next){
 // rest of your code here
}

虽然在您的情况下,您最好将身份验证逻辑移至单独的中间件,如下所示:

router.post('/project/new', 
  function(req, res, next) {
    if (req.user) {
      next();
    } else {

      // do whatever to create a new user

    }
  },
  function(req, res) {
    // this function will be called after your auth logic is done
    // at this point, your req.user should be populated, respond with an error status if for some reason its not
    if (!req.user) return res.send(500);

    // the rest of your logic here

  }
);