【问题标题】:Node.js middleware authentication with variable带变量的 Node.js 中间件身份验证
【发布时间】:2015-06-06 01:10:25
【问题描述】:

在路由和呈现网站之前,我想检查用户是否经过身份验证并且属于某种类型。 “中间件”如下所示:

function isAuthenticated(req,res,next,required_type){
if(Parse.User.current()){
    Parse.User.current().fetch().then(function(fetchedUser){
        var type = fetchedUser.get("type");            
        if(type == required_type){
            return next();
        }else{
            res.redirect("/login");
        }

    }, function(error){
        res.redirect("/login");
    });
}else{
    res.redirect("/login");
}
}

这部分看起来很公平和容易。这是我在路由之前尝试使用中间件的方法:

app.get('/dashboard_client',isAuthenticated, dashboard_client_view_controller.displayView);

我的问题是,我如何设置 required_type 变量,因为 Node.js 不知何故知道如何获取和查找 req、res 和 next 变量。感谢您如此愚蠢地回答,我想很明显可以解决问题。

【问题讨论】:

  • app.get('/dashboard_client/:requiredtype',isAuthenticated, dashboard_client_view_controller.displayView); 然后调用 GET /dashboard_client/requiredtype 其中 requiredtype 是您的类型。

标签: node.js express routes middleware


【解决方案1】:

你可以试试这个方法:

//中间件:

function isAuthenticated(required_type) {
    return function(req, res, next) {
        if (Parse.User.current()) {
            Parse.User.current().fetch().then(function (fetchedUser) {
                var type = fetchedUser.get("type");
                if (type == required_type) {
                    return next();
                } else {
                    res.redirect("/login");
                }

            }, function (error) {
                res.redirect("/login");
            });
        } else {
            res.redirect("/login");
        }
    }

};

//路线

app.get('/dashboard_client',isAuthenticated('admin'), dashboard_client_view_controller.displayView);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2019-07-23
    • 2019-03-15
    相关资源
    最近更新 更多