编写带有和不带有重定向功能的用于检查admin的中间件的最佳方式

问题描述 投票:0回答:1

我已经编写了快速身份验证中间件。第一个使用app.all('*')的对象用于设置Flash对象,然后该Flash对象用于设置本地对象。 checkAdmin中间件允许路由继续进行,但是给了我一个本地变量,我可以在我的ejs中检入该变量以显示仅应由管理员查看的页面部分。但是,其他用户仍然可以访问此页面。他们只是看不到一切。因此,在我的checkAdmin()中间件中,无论用户是否是管理员,我都在使用return next()。

中间件功能:

app.all('*',middleware.checkAdmin)





middleware.isAdmin =function(req,res,next){
        //Check if the admin is set to true or not


        pool.query(`Select RoleID from userroles where UserID = ${req.user.id}`,function(err,rows,fields){
            if(err){
                console.log(err)
            }
            if(rows[0]){                  //This should not really happen, where the role is undefined. Every user should have a role, but checking it just in case
                if (rows[0].RoleID == 1){
                    return next()
                }
            }
            req.flash("message", "You need to have admin previledge to acccess this page")
            res.redirect('back');     //From express 4 onwards this should allow me to redirect to the same page the request came from.
        })

    }
middleware.checkAdmin=function(req,res,next){
        //Check if the admin is set to true or not

        if(req.user){
            pool.query(`Select RoleID from userroles where UserID = ${req.user.id}`,function(err,rows,fields){  
                if(err){
                    console.log(err)
                }
                if(rows[0]){                  //This should not really happen, where the role is undefined. Every user should have a role, but checking it just in case
                    if (rows[0].RoleID == 1){
                        req.flash("checkAdmin","admin")
                        return next()
                    }
                }
                return next()     
            })
        }else{
            return next()
        }

    }
app.use(function(req,res,next){

    res.locals.currentUser=req.user;
    res.locals.error=req.flash("error");
    res.locals.success=req.flash("success");
    res.locals.message=req.flash("message");
    res.locals.checkAdmin=req.flash("checkAdmin");   //I am using this so that I can show the admin navbar element only if the user is signed in as admin
    next()
})

我的isAdmin中间件用于以下路由:

router.get("/admin", middleware.isAdmin, function (req, res) {
    res.render("admin.ejs")
})

我无法在线找到可解决此问题的身份验证设置,因此我提出了此代码。但是我不确定这是否是实现此目的的最佳方法。

我已经编写了快速身份验证中间件。第一个使用app.all('*')的对象用于设置Flash对象,然后该Flash对象用于设置本地对象。 checkAdmin中间件允许...

node.js express
1个回答
1
投票

为什么不使用会话?然后,您可以在登录时设置角色,并可以编写如下中间件:

© www.soinside.com 2019 - 2024. All rights reserved.