<?php
	error_reporting(E_ALL ^ E_NOTICE);

	include_once('../include/lucidAuth.functions.php');

	$proxyHeaders = array();
	foreach ($_SERVER as $key => $value) {
		if (strpos($key, 'HTTP_') === 0) {
			// Trim and then convert all headers to camelCase
			$proxyHeaders[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
		}
	}
	// Keep only headers relevant for proxying
	$proxyHeaders = array_filter($proxyHeaders, function ($key) {
		return substr($key, 0, 10) === 'XForwarded';
	}, ARRAY_FILTER_USE_KEY);
	
	// For debugging purposes - enable it in ../lucidAuth.config.php
	if ($settings->Debug['LogToFile']) {
		file_put_contents('../requestHeaders.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --- ' . (json_encode($proxyHeaders, JSON_FORCE_OBJECT)) . PHP_EOL, FILE_APPEND);
		file_put_contents('../requestHeaders.log', (new DateTime())->format('Y-m-d\TH:i:s.u') . ' --+ ' . (base64_encode(json_encode($proxyHeaders))) . PHP_EOL, FILE_APPEND);
	}

#	if (sizeof($proxyHeaders) == 0) {
	if (False) {
		// Non-proxied request; this is senseless, go fetch!
		header("HTTP/1.1 403 Forbidden");
		exit;
	}

	if ((!empty($_COOKIE['Exp']) && !empty($_COOKIE['Sub']) && !empty($_COOKIE['JWT'])) && validateToken([
		'Exp' => $_COOKIE['Exp'],
		'Sub' => $_COOKIE['Sub'],
		'JWT' => $_COOKIE['JWT']
	])['status'] == "Success") {
		// Valid authentication token found
		header("HTTP/1.1 202 Accepted");
		exit;
	} else {
		// No cookie containing valid authentication token found, redirecting to loginpage
		header("HTTP/1.1 401 Unauthorized");
		header("Location: lucidAuth.login.php?ref=" . base64_encode(json_encode($proxyHeaders)));
	}

?>