0

我想將兩個身份驗證控制器添加到一個路由。例如,這基本上就是我試圖做:一個路由上的多個身份驗證控制器

router.route('/employees') 
     .get(authController1.isAuthenticated, myController1.get1) 
     .get(authController2.isAuthenticated, myController2.get2); 

的isAuthenticated功能如下:

exports.isAuthenticated = passport.authenticate('basic', { 
    session: false 
}); 

有誰知道這將是可能的嗎?

感謝, 丹尼爾

+0

你不能有兩個相同的端點GET方法?如果你想添加兩個認證方法,用逗號分開它們。 '.get(authController1.isAuthenticated,authController2.isAuthenticated,myController1.get1)' – 2015-04-01 12:32:49

+0

@RichardMacarthy我只是想表達功能。謝謝,但我怎麼能區分哪個authController負責調用.get1? – DVassilev 2015-04-01 13:32:40

+0

看到我的答案,這會爲你工作嗎? – 2015-04-01 13:52:41

回答

0

路線:

router.route('/employees') 
     .get(authController.isAuthenticated1, authController.isAuthenticated2, myController1.get1) 

authController:

exports.isAuthenticated = function(req, res, next) { 
    // Authentication code 
    if (!req.isAuthenticated) { 
     // Not authenticated 
     return res.status(401).send({ 
      message: 'User is not authenticated' 
     }); 
    } 
    next(); 
}; 

exports.isAuthenticated2 = function(req, res, next) { 
    // Authentication2 code 
    if (!req.isAuthenticated2) { 
     // Not authenticated 
     return res.status(401).send({ 
      message: 'User is not authenticated' 
     }); 
    } 
    next(); 
}; 

myController的

exports.get1 = function(req, res) { 
    // Both are authenticated so we can proceed. 
} 
+0

嗯,再次感謝你,但不是我所需要的。我需要能夠確定哪個驗證器導致'get1'函數。兩種類型的用戶(因此是兩個認證),並取決於我需要執行不同功能的用戶類型。這就是爲什麼我最初有.get1和.get2。如果我能夠識別它是哪種類型的用戶,我可以使用.get1。 – DVassilev 2015-04-01 14:27:52

+0

也許像新的答案? – 2015-04-01 14:33:43

0

也許東西升這個嗎?

exports.isAuthenticated = function(req, res, next) { 
    req.user == 'type1' ? fnType1(req, res, next) : fnType2(req, res, next); // Do check and call method. 
}; 

function fnType1(req, res, next) { 
    //Authentication code 
    // Attach type to req 
    req.userType = 1; 
    next(); 
} 

function fnType2(req, res, next) { 
    //Authentication code 
    // Attach type to req 
    req.userType = 2; 
    next(); 
} 

exports.get1 = function(req, res) { 
    // Both are authenticated so we can proceed. 
    if(req.userType = 1){ 
     // Do something 
    } else { 
     // Do something else 
    } 
} 
+0

嗯,不完全。這兩種方法是我認爲必須保持獨立的認證方法,因爲它爲每種「類型」的用戶使用兩種不同的模型。因此,根據哪個authController返回true,必須調用特定的函數(或者通過某種方式告訴哪個authController調用它)。 – DVassilev 2015-04-01 14:55:38

+0

編輯答案。 – 2015-04-01 15:07:03