2016-06-21 73 views
0

我需要身體驗證和更好的錯誤處理沒有第一個驗證中間件。代碼工作得很好,但我想刪除第一個中間件並在第二個時間內進行驗證。Passport.js本地登錄與身體驗證和錯誤處理

路線/ auth.js

router.post('/signin', function(req, res, next){ 

    req.checkBody('email', 'Email is required.').notEmpty(); 
    req.checkBody('email', 'Invalid email format.').isEmail(); 
    req.checkBody('password', 'Password is required.').notEmpty(); 
    req.checkBody('password', 'The password length must be between 8 and 100.').isLength({min: 8, max: 100}); 

    var err = req.validationErrors(); 
    if (err) { 
     res.status(400).send({ success: false, error: err}); 
     return; 
    } 
    next(); 
}); 

router.post('/signin', passport.authenticate('local', { session: false }), function(req, res){ 
    var user = req.user; 
    return res.json({success: true, user: user}); 
}); 

至於錯誤處理,如果用戶不匹配,錯誤的是:

{ 
    "error": "Invalid email and/or password" 
} 

,我想這一點:

{ 
    "success":false, 
    "error": "Invalid email and/or password" 
} 

我該怎麼辦?

passport.js

passport.use(new LocalStrategy({ 
     usernameField: 'email', 
     passwordField: 'password' 
    }, 
    function(email, password, done) { 
     User.findOne({ email: email, password: password },'-password', function (err, user) { 
      if (err)return done(err); 
      if(!user){ 
       var err = new Error('Invalid email and/or password'); 
       err.status = 401; 
       return done(err, false); 
      } 

      return done(null, user); 
     }) 
    } 
)); 

感謝您的答覆。

回答

2

如果我理解正確,您希望驗證發生在LocalStrategy對象的驗證功能中。

在做到這一點之前,您首先需要訪問req對象。對於這一點,你需要啓用passReqToCallback選項策略:

passport.use(new LocalStrategy({ 
     usernameField  : 'email', 
     passwordField  : 'password', 
     passReqToCallback : true 
    }, 
    function(req, email, password, done) { ... }); 

從那裏,你可以使用相同的驗證碼在第一中間件:

function(req, email, password, done) { 
    req.checkBody('email', 'Email is required.').notEmpty(); 
    req.checkBody('email', 'Invalid email format.').isEmail(); 
    req.checkBody('password', 'Password is required.').notEmpty(); 
    req.checkBody('password', 'The password length must be between 8 and 100.').isLength({min: 8, max: 100}); 

    var err = req.validationErrors(); 
    if (err) { 
     return done(err, false, { success: false, error: err}); 
    } 
    User.findOne({...}); 
}); 

最後,你需要使用自定義的回調passport.authenticate()辦理驗證結果:

router.post('/signin', function(req, res, next) { 
    passport.authenticate('local', { session : false }, function(err, user, info) { 
    if (err) return next(err); 
    if (! user) { 
     return res.status(400).json(info); 
    } 
    return res.json({ success : true, user : req.user}); 
    })(req, res, next); 
}); 

info參數回調映射到日驗證處理程序中done()回調的第三個參數。

需要注意的一件事是,如果請求正文中的emailpassword爲空,Passport將不會調用本地策略處理程序,這使notEmpty驗證無效。