<?php

include 'lb.php';
include 'lang.php';
include 'forminput.php';
include 'bcrypt.php';

if (isset($usehttps)&&$usehttps) include 'https.php'; 
include 'connect.php';
include 'auth.php';
include 'xss.php';

include 'sendsms.php';

$salt2=$saltroot.$_SERVER['REMOTE_ADDR'].'-'.$_SERVER['O_IP'].date('Y-m-j-H',time()-3600);

xsscheck();

$login=SQET('login');

$query="select * from ".TABLENAME_USERS." left join gss on ".TABLENAME_USERS.".gsid=gss.gsid where login=? and active=1 and virtualuser=0";
$rs=sql_prep($query,$db,$login);  

$passok=0;

if ($myrow=sql_fetch_array($rs)){

	$passok=password_verify($dbsalt.$_POST['password'],$myrow['password']);
		
	$passreset=$myrow['passreset'];
	
	$needkeyfile=$myrow['needkeyfile'];
	$usesms=$myrow['usesms'];
	$smscell=$myrow['smscell'];
	if ($smscell=='') $usesms=0;
	if ($smskey=='') $usesms=0;
	
	$userid=$myrow['userid']+0;
	$needcert=$myrow['needcert'];

} else {
	password_hash($dbsalt.time(),PASSWORD_DEFAULT,array('cost'=>PASSWORD_COST));	
}

$tfas=array();
$foci=array();

if (!$passok){
	header('prevalidation: invalid credentials');
	die();
}

if ($passreset){
	header('prevalidation: reset bypass');
	die();	
}



if ($usesms){
	array_push($tfas,'sms');
	array_push($foci,'smscode');
	
	$code=rand(10000,99999);
	$codehash=md5($salt.$code);
	
	$query="update users set smscode=? where userid=?";
	sql_prep($query,$db,array($codehash,$userid));
	
	sendsms($smscell,'Your access code is: '.$code);	
}

if ($needkeyfile) {
	array_push($tfas,'keyfile');
}

if ($needcert){
	array_push($tfas,'cert');
}

if (count($tfas)>0){
	header('tfas: '.implode(',',$tfas));
	if (count($foci)>0){
		header('focalpoint: '.$foci[0]);	
	}
}

if ($needkeyfile){
?>
	<div>Key File:</div>
	<div style="padding-top:5px;padding-bottom:15px;">
		<input id="keyfile" type="file" name="keyfile">
		<input type="hidden" name="MAX_FILE_SIZE" value="4096">
	</div>
<?	
}
