<?php
require_once('config.php');
$_SESSION['csrf']=$_SESSION['csrf']??bin2hex(random_bytes(32));
$error='';
if(isset($_SESSION['block_until'])&&time()<$_SESSION['block_until'])
$error=sprintf(__('Too many failed attempts. Please try again in %d minutes.'),ceil(($_SESSION['block_until']-time())/60));
if($_SERVER['REQUEST_METHOD']==='POST'&&!$error){
if(!hash_equals($_SESSION['csrf'],$_POST['csrf']??'')){http_response_code(403);exit('Forbidden');}
$user=trim($_POST['username']??'');
$pass=$_POST['password']??'';
if($user&&isset($USERS[$user])&&password_verify($pass,$USERS[$user]['pass'])){
if(($_POST['remember']??'')==='1'&&(is_dir($d=ABSPATH.'data/remember')||@mkdir($d,0700))){
$t=bin2hex(random_bytes(32));$h=hash('sha256',$t);
if(file_put_contents($f="$d/$h",json_encode(['user'=>$user,'created'=>time()]),LOCK_EX)!==false)chmod($f,0600);
setcookie('REMEMBER_TOKEN',$t,time()+86400*30,'/','',true,true);
}
unset($_SESSION['login_attempts'],$_SESSION['block_until']);
session_regenerate_id(true);
$_SESSION=['user'=>$user,'role'=>$USERS[$user]['role'],'csrf'=>bin2hex(random_bytes(32))];
header("Location:index.php");exit;
}
$_SESSION['login_attempts']=($_SESSION['login_attempts']??0)+1;
if($_SESSION['login_attempts']>=MAX_LOGIN_ATTEMPTS){
$_SESSION['block_until']=time()+BLOCK_TIME_SECONDS;
$error=sprintf(__('Too many failed attempts. Your access is restricted for %d minutes.'),ceil(BLOCK_TIME_SECONDS/60));
}else{usleep(200000);$error=__('The username or password is incorrect');}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title><?=ns(APP_NAME)?> - <?php _nsl('LOGIN');?></title>
<link rel="stylesheet" href="include/css/style.css">
<?php include('include/web/header.php');?>
</head>
<body>
<div id="login-container"><div class="login-box">
<img src="img/logo.png" alt="Logo">
<h2><?=ns(APP_NAME)?> - <?php _nsl('LOGIN');?></h2>
<?php if($error):?><div class="error-msg"><?=ns($error)?></div><?php endif;?>
<form method="post" action="login.php" autocomplete="off">
<input type="hidden" name="csrf" value="<?=$_SESSION['csrf']?>">
<label><?php _nsl('ID');?><input type="text" name="username" value="<?=isset($user)?ns($user):''?>" required autocomplete="username"></label>
<label><?php _nsl('PASSWORD');?><input type="password" name="password" required autocomplete="current-password"></label>
<label class="remember-me"><input type="checkbox" name="remember" value="1"><?php _nsl('Remember Me');?></label>
<button type="submit" class="btn-login"><?php _nsl('LOGIN');?></button>
</form>
</div></div>
<?php include('include/web/footer.php');?>
</body>
</html>
