<?php
// Purple 2023-04-09
require_once("auth.inc");
require_once("util.inc");
require_once("functions.inc");
require_once("captiveportal.inc");

header("Expires: 0");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Connection: close");

function redirect_to_splash($error = false) {
	global $config, $cpzone;
	$portalconf = $config['captiveportal'][$cpzone];
	$redirecturl = $portalconf['preauthurl'];
	$pfsmac = $portalconf['radiusnasid'];
	$clientip = $_SERVER['REMOTE_ADDR'];
	$clientmac = pfSense_ip_to_mac($clientip);
	$clientmac = $clientmac['macaddr'];
	$protocol = (isset($portalconf['httpslogin'])) ? 'https://' : 'http://';
	$hostname = portal_hostname_from_client_ip($clientip);
	$action = $protocol.$hostname."/index.php?zone=".$cpzone;
	
	$url = $redirecturl."?";
	
	if ($error) {
		$url .= "res=error&";
	}
	$url .= "login_url=".$action."&pfsmac=".$pfsmac."&client_mac=".$clientmac."&client_ip=".$clientip;
	
	//echo $url; exit;
	header("Location: ".$url);
}

function redirect_to_success($postauthurl) {
	header("Location: ".$postauthurl);
}

if (isset($_GET['username']) && isset($_GET['password'])) {
	global $config, $cpzone;
	$portalconf = $config['captiveportal'][$cpzone];
	$postauthurl = $portalconf['redirurl'];
	$username = $_GET['username'];
	$password = $_GET['password'];
	$clientip = $_SERVER['REMOTE_ADDR'];
	$clientmac = pfSense_ip_to_mac($clientip);
	$clientmac = $clientmac['macaddr'];

	$auth_result = captiveportal_authenticate_user($username, $password, $clientmac, $clientip, 0, 'first');
	
	if ($auth_result['result']) {
		captiveportal_logportalauth($username, $clientmac, $clientip, $auth_result['login_status']);
		portal_allow($clientip, $clientmac, $username, $password, $postauthurl, $auth_result['attributes'], null, $auth_result['auth_method'], 'first');
		redirect_to_success($postauthurl);
	} else {
		redirect_to_splash(true);
	}
} else {
	redirect_to_splash();
}

?>