一条路由上有多个认证控制器

时间:2015-04-01 11:09:19

标签: node.js authentication express passport.js basic-authentication

我正在尝试将两个身份验证控制器添加到一个路由。例如,这基本上就是我想要做的:

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

isAuthenticated功能如下:

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

有谁知道这怎么可能?

谢谢, 丹尼尔

2 个答案:

答案 0 :(得分: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.
}

答案 1 :(得分: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
    }
}