Alexander Mills
Alexander Mills

Reputation: 99970

Node.js Express - prevent access to certain URLs

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();
})

Upvotes: 0

Views: 3884

Answers (3)

Palak Bhansali
Palak Bhansali

Reputation: 731

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().

Upvotes: 3

Mass010
Mass010

Reputation: 11

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

Upvotes: 1

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

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

Upvotes: 1

Related Questions