# Store the secret hmac key value.  You may prefer to use a private
# edge dictionary to inject this value into your configuration
declare local var.secret STRING;
set var.secret = "iqFPeN2uZ0Lm5IrsKaOFKR";

# Extract the token from the URL or a cookie
declare local var.token STRING;
if (req.http.Cookie:token) {
  set var.token = req.http.Cookie:token;
} else if (subfield(req.url.qs, "token", "&")) {
  set var.token = subfield(req.url.qs, "token", "&");
} else {
  log "syslog :: Missing 'token' query param or cookie";
  error 403;
}

# Extract token expiration and signature
declare local var.expiryTime STRING;
declare local var.suppliedSig STRING;
declare local var.expectedSig STRING;
if (var.token ~ "^(\d+)_(\w+)$") {
  set var.expiryTime = re.group.1;
  set var.suppliedSig = re.group.2;
  set var.expectedSig = digest.hmac_sha1(
    var.secret,
    req.url.path var.expiryTime req.http.User-Agent
  );

  # Validate signature
  if (var.suppliedSig == var.expectedSig) {
    # Check that expiration time has not elapsed
    if (time.is_after(now, std.integer2time(std.atoi(var.expiryTime)))) {
      log "syslog :: Token has expired";
      error 410;
    }

    # Token is good!
  } else {
      log "syslog :: Token is incorrect, expected " + var.expectedSig;
      error 410;
  }
} else {
  log "syslog :: Token format is invalid";
  error 403;
}

# Remove the token from the URL before lookup, 
# preventing the cache from fragmenting
set req.url = regsuball(req.url, "([\?|&])token=[^&\s]*&?", "\1");
log "syslog :: Token is good";

# get rid of trailing & or ?
set req.url = regsuball(req.url, "[\?|&]+$", "");