2015-09-11 19 views
6

का उपयोग कर कस्टम त्रुटि संदेश मैं अपने एपीआई को सुरक्षित करने के लिए पासपोर्ट का उपयोग कर रहा हूं। मुझे समझने के लिए संघर्ष है कि मुझे त्रुटि के मामले में कस्टम संदेश वापस भेजने के लिए कैसे भेजा जाता है और मैं यहां एक उत्तर ढूंढने की उम्मीद कर रहा हूं। (पासपोर्ट बीयरर

Passport.use(new BearerStrategy(function(token, cb) { 
Token.findOne({token: token}, function(err, token){ 
    if (err){return cb(null, false);} 
    if (!token) { return cb(null, false); } 
    return cb(null, token); 
}); 
})); 

exports.BearerAuthenticated = Passport.authenticate('bearer', {session: false}); 

मेरे आवेदन विधि आवेदन:

यहाँ मैं क्या किया है:

एक मार्ग (server.js):

router.route('/Applications').get(authController.BearerAuthenticated, applicationController.getApplications); 

मेरे पासपोर्ट सामग्री (authController.js) .js)

exports.getApplications = function(req, res) { 
Application.find({userId:req.user._id}, function(err, apps) { 
if (err) 
    res.send(err); 
res.json(apps); 
}); 
}; 

यदि मेरे टोकन वैध है और वाहक विधि लौट

return cb(null, token); 

तब मैं अपने getApplications विधि डाल सकते हैं। यह समझ में आता है।

बात यह है कि टोकन मान्य नहीं है, मैं विधि (प्रवेश भी करता हूं) दर्ज नहीं करता हूं लेकिन मुझे निम्नलिखित संदेश के बजाय क्लाइंट को कस्टम संदेश वापस करने का कोई तरीका नहीं पता है डिफ़ॉल्ट रूप से।

Unauthorized 

क्या गलत कोड के साथ एक JSON वापस जाने के लिए ठीक से उपयोगकर्ता पता उसके टोकन मर चुका है या बस मौजूद नहीं है कि यह बताने के लिए एक तरीका क्या होगा?

आपके लिए धन्यवाद। :)

उत्तर

8

आप authenticate में कॉलबैक पास कर सकते हैं और वहां से त्रुटियों को संभाल सकते हैं। ध्यान दें कि इस मामले में आपको मैन्युअल रूप से डिफ़ॉल्ट लॉगिन जैसे उपयोगकर्ता लॉगिन इत्यादि करना होगा। here में अधिक।

exports.BearerAuthenticated = function(req, res, next){ 
    passport.authenticate('bearer', {session: false}, function(err, user, info) { 
     if (err) { return next(err); } 

     //authentication error 
     if (!user) { return res.json({error: info.message || 'Invalid Token'}) } 

     //success 
     req.logIn(user, function(err) { 
      if (err) { return next(err); } 
      return next(); 
     }); 

    })(req, res, next) 
} 
संबंधित मुद्दे