# If we are restarting to execute a paywall preflight, extract
# the paywall service URL, and set the correct backend and path
if (req.http.paywallCheckPending ~ {"^https?:\/\/([^\/].*?)(\/.*)$"}) {
  if (re.group.1 == "fiddle-paywall.glitch.me") {
    set req.backend = F_origin_1; /* Paywall backend */
  }
  unset req.http.paywallCheckPending;
  set req.http.paywallOrigUrl = req.url;
  set req.url = re.group.2;

# If we restarted following a paywall check and the result is BLOCK,
# throw an error to display the paywall.  Another option here would
# be to redirect, or to request a different piece of backend content
} elseif (req.http.Paywall-Result == "BLOCK") {
  error 602;

# Otherwise we're executing a normal request, which may also
# need to reset the URL after a paywall preflight
} else {
  if (req.http.paywallOrigUrl) {
    set req.url = req.http.paywallOrigUrl;
  }
  set req.backend = F_origin_0; /* Content backend */
}

# Getting a session ID from a cookie is rather simplistic in this
# demo.  For a more advanced solution, combine the paywall pattern
# with a JSON web token verification at the edge
if (req.http.Cookie:sessionid) {
  set req.http.auth-sessionid = req.http.Cookie:sessionid;
}

unset req.http.Cookie;