<?php

$a = session_id();
if ($a == '')
  session_start();

include_once("common/constants.inc");
include_once("common/db_utils.php");
include_once("common/segf.php");
include_once("smarty/Smarty_config.php");

if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(openssl_random_pseudo_bytes(32));
}

$smarty = new Smarty_config();


if (isset($_POST['username'])) {
  if (empty($_POST['csrf_token']) || empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    http_response_code(403);
    exit('Invalid CSRF token');
  }

  if (isset($_SESSION['user'])) {
    session_unset();
    session_destroy();
    session_start();
  }

  $_SESSION["timeout"] = time();

  $username = htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');
  $password = htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8');

  $user = login($username, $password);

  if (!isset($_SESSION["user"])) {
    $smarty->assign('name', '-');
    $smarty->assign('username', $username);
    $smarty->assign('password', $password);
    $smarty->assign('errormsg', ERRORLOGINNEVORPASSWORDSTR);
    $smarty->assign('version', VERSIONNUMBER);
    $smarty->assign('company', COMPANYNAME);
    $smarty->assign('csrf_token', $_SESSION['csrf_token']);
    $smarty->display('login.tpl');
  } else {
    if ($_SESSION["user"]["isadmin"])
      header("Location: /admin");
    else
      header("Location: /ragasztas");
  }
} else {
  $smarty->assign('name', '-');
  $smarty->assign('username', '');
  $smarty->assign('password', '');
  $smarty->assign('version', VERSIONNUMBER);
  $smarty->assign('company', COMPANYNAME);
  $smarty->assign('csrf_token', $_SESSION['csrf_token']);
  $smarty->display('login.tpl');
}

?>
