且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

静态的RESTify Web服务器停止工作后,启用HTTP基本身份验证

更新时间:2022-05-05 15:40:10

如果您是的NodeJS最新足以支持 string.startsWith()

If your nodejs is up to date enough to support string.startsWith():

function verifyAuthorizedUser(req, res, next) {
    var path = req.path();
    // check if the path starts with /static/
    if (path.startsWith('/static/')) {
        return next();
    }

    var users;
    users = {
        foo: {
            id: 1,
            password: 'bar'
        }
    };

    if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
        // Respond with { code: 'NotAuthorized', message: '' }
        next(new restify.NotAuthorizedError());
    } else {
        next();
    }

    next();
}

如果您还没有startsWith(),一个很好的旧正则表达式会做什么:

If you don't have startsWith(), a good old regex will do:

if (path.match(/\/static\/.*/)) {
    return next();
}