<?php
if (session_status() == PHP_SESSION_NONE) {
    if(!isset($_SESSION)) session_start();
}
require_once 'demosettings.php';
require_once("userCake/models/config.php");
require_once 'Authentication/JWT.php';
require_once 'Exceptions/SignatureInvalidException.php';
require_once 'Exceptions/BeforeValidException.php';
require_once 'Exceptions/ExpiredException.php';
require_once 'write_log.php';
require_once 'authorizations.php';

if(!array_key_exists("loggedIn", $_SESSION)) {
    $_SESSION["loggedIn"] = false;
}

if($_SESSION["loggedIn"] != "yes")
{
	//support JWT tokens
	if (array_key_exists("userToken", $_REQUEST))
	{
		//avoid writing jwtKey to log
		set_exception_handler(null);
		try{
			$decoded = JWT::decode($_REQUEST["userToken"], $jwtKey, array('HS256'));
			if ($decoded && array_key_exists("username", $decoded))
			{
				$_SESSION["username"] = $decoded->username;
				$_SESSION["loggedIn"] = "yes";
				write_to_log("TRACE", "$decoded->username logged in via userToken: $_REQUEST[userToken]");
			}
		}
		catch (Exception $ex)
		{
			write_to_log("ERROR", "Exception during jwt token decode: ". $ex->getMessage());
		}
		restore_exception_handler();
	}	
}
// IF we are not logged in BUT we are after the apache auth (right password, got a username as PHP_AUTH_USER
// if($_SESSION["loggedIn"] != "yes"){
//         //http_response_code(401);
// 	//redirect to login page in java
// 	//echo '<script type="text/javascript" src="js/ivcommon.js"></script>';
// 	//echo '<script language="javascript"  type="text/javascript">gotoPage("login", {});</script>';
// 	//die();
//         $_SESSION['username'] = "admin"; //allow default login as admin
//         $_SESSION["loggedIn"] = "yes";
        
//         //doesnt work well on v2
//         if(empty($_REQUEST['v2'])){
// 	        header("Location: login.php");
//         }
  
// }
if($_SESSION["loggedIn"] != "yes"){
//             $_SESSION['username'] = "admin"; //allow default login as admin
//             $_SESSION["loggedIn"] = "yes";
    $response = array("error"=>"User not logged in");
    echo json_encode($response);
    die();
}


