declare local var.credential STRING;
declare local var.username STRING;
declare local var.password STRING;
declare local var.hashedpassword STRING;

# The condition ensures this logic is only run on edge nodes.
if (fastly.ff.visits_this_service == 0 && req.restarts == 0) {
  if (req.http.Authorization ~ "(?i)^Basic ([a-z0-9_=]+)$") {
    set var.credential = digest.base64_decode(re.group.1);
    set var.username = if(var.credential ~ "^(.+?):.+$", re.group.1, "");
    set var.password = if(var.credential ~ "^.+?:(.+)$", re.group.1, "");
    set var.hashedpassword = table.lookup(user2hashedpass, var.username, "NOTFOUND");

    if (var.hashedpassword == "NOTFOUND") {
      error 401 "Restricted";
    } else if (!digest.secure_is_equal(digest.hash_md5(var.password), var.hashedpassword)) {
      error 401 "Restricted";
    }
    # Unset the Auth header to avoid exposing this as a response header.
    unset req.http.Authorization;
    set req.http.Auth-User = var.username;
  } else {
    error 401 "Restricted";
  }
}