all files / blackbird/modules/middleware/ basicAuth.js

94.12% Statements 16/17
70% Branches 7/10
100% Functions 4/4
94.12% Lines 16/17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33                                  
module.exports = (function (mach, Promise, R) {
    "use strict";
    mach.extend(require("../extensions/server"));
    function basicAuth(app, options) {
        Eif (R.is(Function, options)) {
            options = {validate: options};
        }
        const realm = options.realm || "Authorization Required";
        return function (conn) {
            Iif (conn.remoteUser) {
                return conn.run(app); // Don't overwrite existing remoteUser.
            }
 
            const [username, password] = conn.auth.split(":", 2);
 
            return Promise.resolve(options.validate(username, password)).then(function (user) {
                if (user) {
                    conn.remoteUser = user === true ? username : user;
                    return conn.run(app);
                }
 
                conn.response.headers["WWW-Authenticate"] = `Basic realm="${realm}"`;
                conn.text(401, "Not Authorized");
            });
        };
    }
    return basicAuth;
}(
    require("../index"),
    require("bluebird"),
    require("ramda")
));