Node.js Express - prevent access to certain URLs

依然范特西╮ 提交于 2020-01-06 17:26:51

问题


I want to prevent access to someone not logged-in to any url that starts with '/users'

Here's my current code:

app.use('/^users*',function (req, res, next) {
    if (checkAuth(req)) { 
        console.log('authorization OK');
        next(); 
    } else {
        console.log('authorization failed');
        res.redirect('/login');
    }

});

function checkAuth(req) {
    console.log('req',req.url);
    if (!req.session.user_id && req.url !== '/login' && req.url !== '/') {
        return false;
    }
    return true;
};

but the regular expression I have is not right. I can't find a regular expression for expression that matches "everything that starts with 'user'". This should be easy, but is proving more difficult than expected.

According to the Express API documentation:

// will match paths starting with /abcd
app.use('/abcd', function (req, res, next) {
  next();
})

回答1:


app.all('*/users/*', requireAuthentication, function (req, res, next){

});

Above route will catch all kind of requests starting from users, will through requireAuthentication function, then following function on next().




回答2:


Try app.use('/users/?*', function(){}); That should match all routes starting with /users




回答3:


Do not use single quote marks '/^users*' use /^\/users*. That is for all strings beginning with '/users'.

But if just want it to be hierarchial as '/users/foo' you do not need regex you could use:

app.use('/users/*',function (req, res, next)

app.use express API reference



来源:https://stackoverflow.com/questions/27466468/node-js-express-prevent-access-to-certain-urls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!