<?php
	require("./includes/botcheck.php");
	DEFINE("PEPPER", "hvgfHFDIUfds");
	DEFINE("COOKIE_CIPHER","aes-256-ctr");
	DEFINE("AES_KEY", "12345678901234567890123456789012");
	

	if(isset($_POST['user']) && isset($_POST['pass'])){
		session_set_cookie_params(["samesite" => "Lax"]);
		session_start();
		session_regenerate_id(true);
		if(!isset($_POST['captcha']) || !isset($_SESSION['captcha']) || $_POST['captcha']!=$_SESSION['captcha']){
			echo 'Invalid security code';
			exit;			
		}
		
		$user = $_POST['user'];
		$pass = $_POST['pass'];
	}
	/*else if(isset($_COOKIE['user']) && isset($_COOKIE['pass']) && isset($_COOKIE['aesiv'])){
		
		$user = openssl_decrypt($_COOKIE['user'], COOKIE_CIPHER, AES_KEY, 0, $_COOKIE['aesiv']);
		$pass = openssl_decrypt($_COOKIE['pass'], COOKIE_CIPHER, AES_KEY, 0, $_COOKIE['aesiv']);
		
	}*/
	else if(isset($_COOKIE['perm_token']) && isset($_COOKIE['var_token']) && isset($_COOKIE['aesiv'])){
		$perm_token = openssl_decrypt($_COOKIE['perm_token'], COOKIE_CIPHER, AES_KEY, 0, $_COOKIE['aesiv']);
		$var_token = openssl_decrypt($_COOKIE['var_token'], COOKIE_CIPHER, AES_KEY, 0, $_COOKIE['aesiv']);
		$link = @mysqli_connect("localhost", "loginform", "HFDERHGUSDFgfd", "osup2020");
		if(!$link){
			echo "Database maintenance. Please try again later.";
			exit;
		}		
		
		$sql = "SELECT user_tokens.uid AS uid, users.user AS user, user_tokens.var_token AS var_token
				FROM user_tokens JOIN users ON users.id = user_tokens.uid
				WHERE user_tokens.perm_token = UNHEX('".@mysqli_real_escape_string($link, $perm_token)."')";
		
		
		$result = @mysqli_query($link, $sql);
		$row = @mysqli_fetch_assoc($result);
		if(!isset($row['uid'])){
			setcookie("perm_token", "", time()-3600);
			setcookie("var_token", "", time()-3600);
			setcookie("aesiv", "", time()-3600);
			header("Location: index.php");
			exit;
		}

		if(!password_verify($var_token, $row['var_token'])){
			echo 'Акаунтът ви потенциално е бил хакнат. Обадете се на support!';
			exit;
		}
		
	
		session_start();
		session_regenerate_id(true);
		$_SESSION['id'] = $row['uid'];
		$_SESSION['user'] = $row['user'];
	
		$xsrftoken = hash("sha256", openssl_random_pseudo_bytes(32));
		$_SESSION['xsrftoken'] = $xsrftoken;
			
		
		$new_var_token = hash("sha256", openssl_random_pseudo_bytes(32));
		$sql = "UPDATE user_tokens
				SET var_token = '".password_hash($new_var_token, PASSWORD_ARGON2ID, ['memory_cost' => 3907, 'time_cost' => 50, 'threads' => 1])."'
				WHERE uid = ".$row['uid']."
						AND
					  perm_token = UNHEX('".@mysqli_real_escape_string($link, $perm_token)."')";
		$result = @mysqli_query($link, $sql);
		if($result && @mysqli_affected_rows($link)==1){
			setcookie("var_token", openssl_encrypt($new_var_token, COOKIE_CIPHER, AES_KEY, 0, $_COOKIE['aesiv']), time()+3600, "/", null, false, true);
		}
		header("Location: securearea.php");
		exit;
	}
	else{
		header("Location: index.php");
		exit;
	}
	
	
	
	// A-Za-z0-9, от 4 до 32 символа
	/*if(!preg_match("/^[a-zA-Z0-9]{4,32}$/", $user)){
		echo "Въвели сте невалиден символ в потребителското име";
		exit;
	}	*/
	
	
	
	$pass = hash("sha256", $pass.PEPPER);
	for($i=0; $i<100000; $i++){
		$pass = hash("sha256", $pass.$user);
	}
	
	$link = @mysqli_connect("localhost", "loginform", "HFDERHGUSDFgfd", "osup2020");

	//$user = @mysqli_real_escape_string($link, $user);
	
	if(!$link){
		echo "Database maintenance. Please try again later.";
		exit;
	}
	
	$sql = "SELECT id, user
			FROM users
			WHERE user = ? AND pass = UNHEX(SHA2(CONCAT(?, salt),256))";
	
	$statement = mysqli_stmt_init($link);
	mysqli_stmt_prepare($statement, $sql);
	mysqli_stmt_bind_param($statement, "ss", $user, $pass);
	mysqli_stmt_execute($statement);
	mysqli_stmt_bind_result($statement, $result_id, $result_user);
	mysqli_stmt_fetch($statement);
	if(!isset($result_id)){
		if(isset($_COOKIE['user'])){
			setcookie("perm_token", "", time()-3600);
			setcookie("var_token", "", time()-3600);
			setcookie("aesiv", "", time()-3600);
			header("Location: index.php");
			exit;
		}
		
		$link = @mysqli_connect("localhost", "loginform", "HFDERHGUSDFgfd", "osup2020");
		/* зад. 1
		$sql = "INSERT INTO login_logs_hash(ip)
				VALUES(INET6_ATON('".$_SERVER['REMOTE_ADDR']."'))
				ON DUPLICATE KEY UPDATE attempts = attempts+1";
				*/
		$sql = "INSERT INTO login_logs(ip, uid, last_attempt)
				VALUES(INET6_ATON('".$_SERVER['REMOTE_ADDR']."'), (SELECT id FROM users WHERE user='".@mysqli_real_escape_string($link, $_POST['user'])."'), NOW())
				ON DUPLICATE KEY UPDATE attempts = attempts+1, last_attempt=NOW()";

		$result = @mysqli_query($link, $sql);
		
		echo "Invalid username OR password";
		exit;
	}
	
	$_SESSION['id'] = $result_id;
	$_SESSION['user'] = $result_user;
	
	$xsrftoken = hash("sha256", openssl_random_pseudo_bytes(32));
	$_SESSION['xsrftoken'] = $xsrftoken;
	
	/*
	if(isset($_POST['remember'])){
		$ivlen = openssl_cipher_iv_length(COOKIE_CIPHER);
		$iv = openssl_random_pseudo_bytes($ivlen);
		
		setcookie("user", openssl_encrypt($_POST['user'], COOKIE_CIPHER, AES_KEY, 0, $iv), time()+3600, "/", null, false, true);
		setcookie("pass", openssl_encrypt($_POST['pass'], COOKIE_CIPHER, AES_KEY, 0, $iv), time()+3600, "/", null, false, true);
		setcookie("aesiv", $iv, time()+3600, "/", null, false, true);
	}
	*/
	if(isset($_POST['remember'])){
		
		$perm_token = hash("sha256", openssl_random_pseudo_bytes(32));
		$var_token = hash("sha256", openssl_random_pseudo_bytes(32));
		@mysqli_close($link);
		$link = @mysqli_connect("localhost", "loginform", "HFDERHGUSDFgfd", "osup2020");
		
		$sql = "INSERT INTO user_tokens(uid, perm_token, var_token, last_attempt)
				VALUES(".$result_id.", UNHEX('".$perm_token."'), 
						'".password_hash($var_token, PASSWORD_ARGON2ID, ['memory_cost' => 3907, 'time_cost' => 50, 'threads' => 1])."'
)";
		$result = @mysqli_query($link, $sql);
		if($result && @mysqli_affected_rows($link)==1){
			$ivlen = openssl_cipher_iv_length(COOKIE_CIPHER);
			$iv = openssl_random_pseudo_bytes($ivlen);
			
			setcookie("perm_token", openssl_encrypt($perm_token, COOKIE_CIPHER, AES_KEY, 0, $iv), time()+3600, "/", null, false, true);
			setcookie("var_token", openssl_encrypt($var_token, COOKIE_CIPHER, AES_KEY, 0, $iv), time()+3600, "/", null, false, true);
			setcookie("aesiv", $iv, time()+3600, "/", null, false, true);
		}
	}
	
	// DO NOT DO IT
	/*
	$link = @mysqli_connect("localhost", "loginform", "HFDERHGUSDFgfd", "osup2020");
	$sql = "DELETE FROM login_logs_hash
			WHERE ip= INET6_ATON('".$_SERVER['REMOTE_ADDR']."')";
	$result = @mysqli_query($link, $sql);
	*/
	
	// Вече do it
	$link = @mysqli_connect("localhost", "loginform", "HFDERHGUSDFgfd", "osup2020");
	$sql = "DELETE FROM login_logs
			WHERE ip= INET6_ATON('".$_SERVER['REMOTE_ADDR']."')
					AND
				  uid = ".$_SESSION['id'];
	$result = @mysqli_query($link, $sql);
	
	header("Location: securearea.php");		
	exit;
	/*
	$sql = "SELECT id, user
			FROM users
			WHERE user = '".$user."' AND pass = UNHEX(SHA2(CONCAT('".$pass."', salt),256))";
		
	$result = @mysqli_query($link, $sql);
	if(!$result){
		echo "Database maintenance. Please try again later.";
		exit;
	}
	
	$row = @mysqli_fetch_assoc($result);
	if(!isset($row['id'])){
		echo "Invalid username OR password";
		exit;
	}

	session_start();
	session_regenerate_id(true);
	$_SESSION['id'] = $row['id'];
	$_SESSION['user'] = $row['user'];
	header("Location: securearea.php");	
	*/
	
/*	if($_POST['user'] == "ivan" && $_POST['pass'] == "password"){
		session_start();
		session_regenerate_id(true);
		$_SESSION['user'] = "ivan";
		header("Location: securearea.php");
		exit;
	}
	else{
		echo "Invalid username OR password";
	}*/
?>