const BASIC_USER = "admin";
const BASIC_PASS = "123456";

async function handleRequest(request) {
    const url = new URL(request.url);
    if (url.pathname.endsWith("/logout")) {
        return new Response("Logged out.", { status: 401 });
    }

    const authorization = request.headers.get("Authorization");
    if (!authorization) {
        return new Response("You need to login.", {
        status: 401,
        headers: {
            // Prompts the user for credentials.
            "WWW-Authenticate": 'Basic realm="my scope", charset="UTF-8"',
        },
        });
    }
    const [scheme, encoded] = authorization.split(" ");

    // The Authorization header must start with Basic, followed by a space.
    if (!encoded || scheme !== "Basic") {
        return new Response("Malformed authorization header.", {
        status: 400,
        });
    }

    const credentials = atob(encoded);

    // The username & password are split by the first colon.
    //=> example: "username:password"
    const index = credentials.indexOf(":");
    const user = credentials.substring(0, index);
    const pass = credentials.substring(index + 1);

    if (BASIC_USER !== user || BASIC_PASS !== pass) {
        return new Response("You need to login.", {
        status: 401,
        headers: {
            // Prompts the user for credentials.
            "WWW-Authenticate": 'Basic realm="my scope", charset="UTF-8"',
        },
        });
    }

    const resp = await fetch(request);
    resp.headers.set('Cache-Control', 'no-store');

    let text = await resp.text();
    text = text.replace('<a href="index.html" class="nav-item nav-link">Home</a>', 
    '<a href="logout" class="nav-item nav-link">Logout</a>\n<a href="index.html" class="nav-item nav-link">Home</a>')

    return new Response(text, resp);
}
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})