Passport.js未经授权和错误请求的自定义错误

时间:2017-11-30 07:22:32

标签: node.js express error-handling jwt passport.js

已实施d3.select(".horizontalLable").text(); // return "Zombieland (9)Zombieland (9)" <text class="horizontalLable" text-anchor="end" alignment-baseline="hanging" style="font-size: 10px; alignment-baseline: hanging; font-family: Arial; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; fill: rgb(0, 0, 0);" transform="translate(365,2)">Zombieland (9)<title>Zombieland (9)</title></text> 并尝试在用户为false(电子邮件|密码为空“)时抛出自定义错误响应 如果用户未注册

api.js

passport-jwt

当我尝试与邮递员签约时,我没有得到任何回复

预期结果

const passport = require('passport');
const router = require('express-promise-router')();

const passportHelper = require('../helpers/passportHelper');
const authController = require('../controllers/authController');
const { badRequest } = require('../helpers/responseHelper');

const requireAuth = passport.authenticate('jwt', { session: false });
const requireSignin = passport.authenticate('local', { session: false }, (err, user, info) => {
    if(!user) {
        const err = new Error('please provide email and password.');
            err.status = 400;
            err.code = 'CP_SI_ValidationFailed';
            return err;
    }
});

router.post('/signup', authController.signup);
router.post('/signin', requireSignin, authController.signin);

module.exports = router;

有没有其他方法来处理badRequest并返回上面的共鸣,

谢谢

2 个答案:

答案 0 :(得分:2)

从passport.authenticate回调中返回错误是不够的。返回的值不是由护照处理的。如果要将自定义错误返回给客户端,则应编写自定义中间件。如果您将requireSignin方法更改为以下内容,它应该可以正常工作:

const requireSignin = function(req, res, next) {
    passport.authenticate('local', { session: false }, (err, user, info) => {
        if(err || !user) {
            const err = {};
            err.status = 400;
            err.code = 'CP_SI_ValidationFailed';

            return res.json(err); // send the error response to client
        } 
        return next(); // continue to next middleware if no error.
    });
});

答案 1 :(得分:0)

这是更新后的答案,确实会返回响应。

const requireSignin = (req, res, next) => {
  passport.authenticate('local', { session: false }, (err, user, info) => {
    if (err || !user) {
      const err = {};
      err.status = 400;
      err.code = 'CP_SI_ValidationFailed';

      return res.json(err); // send the error response to client
    }
    return next(); // continue to next middleware if no error.

  })(req, res, next); /* passport.authentication returns a function,
                         we invoke it with normal req..res arguments 
                         to override default functionality */ 
}