declare local var.plainCred STRING;

# Don't allow end users to pass their own threat intel result :-)
if (req.restarts == 0) {
  unset req.http.Threat-Intel-Result;
}

# If we are seeing a login, pause it and do a threat assessment
if (req.url == "/post" && req.method == "POST") {
  set req.backend = F_origin_1;
  set req.http.Orig-URL = req.url;
  set req.http.Orig-Method = req.method;
  set var.plainCred = subfield(req.postbody, "password", "&");
  set req.http.Threat-Intel-Key = digest.hash_sha1(var.plainCred);
  set req.url = "/threatIntelPOC?key=" substr(req.http.Threat-Intel-Key, 0, std.atoi(table.lookup(config, "prefix-length")));
  set req.method = "GET";
  log "Checking for threat intelligence on credential '" + var.plainCred + "' using key " + req.http.Threat-Intel-Key;
}

# If we're in the process of doing a threat assessment already,
# complete it, by restoring the original request, or by throwing
# an error.
if (req.http.Threat-Intel-Result) {
  if (req.http.Threat-Intel-Result != "PASS") {
    unset req.http.Threat-Intel-Key;
    unset req.http.Threat-Intel-Result;
    unset req.http.Orig-URL;
    unset req.http.Orig-Method;
    error 403 "Threat detected";
  } else {
    set req.url = req.http.Orig-URL;
    set req.method = req.http.Orig-Method;
    unset req.http.Threat-Intel-Key;
    unset req.http.Threat-Intel-Result;
    unset req.http.Orig-URL;
    unset req.http.Orig-Method;
  }
  return (lookup);
}