"use strict";
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const basic_auth_1 = __importDefault(require("basic-auth"));
const password_hash_1 = require("password-hash");
const lodash_1 = require("lodash");
function isAuthenticated({ req, res, path, auth, }) {
    if (auth == null) {
        return true; // no authentication needed
    }
    // strip any /'s from beginning of path  (auth path's are assumed relative)
    while (path[0] === "/") {
        path = path.slice(1);
    }
    let authInfo = undefined;
    for (const p in auth) {
        if (path.startsWith(p)) {
            authInfo = auth[p];
            break;
        }
    }
    if (authInfo == null) {
        // don't need auth for this path
        return true;
    }
    if (!(0, lodash_1.isArray)(authInfo)) {
        // do a double check...
        res.statusCode = 401;
        res.end("auth is misconfigured  -- invalid auth field in the public_paths database.");
        return false;
    }
    const credentials = (0, basic_auth_1.default)(req);
    let fail = true;
    if (credentials?.name && credentials?.pass) {
        for (const { name, pass } of authInfo) {
            if (name == credentials.name) {
                if ((0, password_hash_1.verify)(credentials.pass, pass)) {
                    fail = false;
                }
                break;
            }
        }
    }
    if (fail) {
        res.statusCode = 401;
        res.setHeader("WWW-Authenticate", 'Basic realm="cocalc.com"');
        res.end("Access denied");
        return false;
    }
    // access granted
    return true;
}
exports.default = isAuthenticated;
//# sourceMappingURL=authenticate.js.map