自定义回调 passportjs?
Custom callback passportjs?
我有一个订购单,用户需要先注册 he/she 才能订购,所以我可以创建一个帐户然后像这样处理订单。
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 文档中看到 Jared 在 get
路由中使用了这个自定义回调。
有人可以帮我做一个自定义回调吗?谁有更好的策略?
未定义,因为你没有定义,你可以这样定义:
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
}
);
我有一个订购单,用户需要先注册 he/she 才能订购,所以我可以创建一个帐户然后像这样处理订单。
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 文档中看到 Jared 在 get
路由中使用了这个自定义回调。
有人可以帮我做一个自定义回调吗?谁有更好的策略?
未定义,因为你没有定义,你可以这样定义:
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
}
);