<?php
setlocale(LC_COLLATE, 'hu_HU.UTF-8');
date_default_timezone_set('Europe/Budapest');
include 'managers/dbconn.php';
include 'managers/code.php';

$coderclass = new coder;
$totp = new TOTP();

ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);
session_start();

$ServerLocalIP = trim(shell_exec('hostname -I | cut -d" " -f1'));

$userip = $_SERVER['REMOTE_ADDR'];

if (isset($_POST['login']) && $_POST['login'] == "islogin") {
  $usr = htmlspecialchars($_POST['usr']);
  $otc = htmlspecialchars($_POST['otc']);
  $pass = md5(htmlspecialchars($_POST['psw']));
  $anticsrf = htmlspecialchars($_POST['anticsrf']);

  if ($otc == "UNSET") {
    $otc = "";
  }

  $useragent = $_SERVER['HTTP_USER_AGENT'];

  $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
  $host = $_SERVER['HTTP_HOST'];
  $currentUrl = $protocol . $host;

  $getagent = json_decode(file_get_contents($currentUrl."/js/bot.php?j=1&a=".urlencode($useragent)));

  if ($anticsrf == $_SESSION['anticsrfid'] && $getagent->status == "ok") {

    $uname = $coderclass->encode($usr, "S1TU");
    $sql = mysqli_query($conn,"SELECT uid,upass,status,otphash,otptype FROM users WHERE uname = '$uname'");
    $user = mysqli_fetch_array($sql);

    if ($user != null && $user[2] < 1) {
      echo '{"result":"A megadott fiók jelenleg nem tud bejelentkezni."}';
      setcookie('auth_token', '', [ 'expires' => time() - 3600, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict']);
      exit();
    } else if ($user != null && $user[3] != "" && $otc == "" && ((!isset($_COOKIE['otpauth']) || $_COOKIE['otpauth'] != md5($user[3])) || ($user[4] == 1 || $user[4] == 3) )) {
      echo '{"result":"otp"}';
      setcookie('auth_token', '', [ 'expires' => time() - 3600, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict']);
      exit();
    } else if ($user[1] === $pass && $user != null) {
      if ($user[3] != "") {
        if ($totp->getOtp($coderclass->decode($user[3], "J57A")) == $otc || (isset($_COOKIE['otpauth']) && $_COOKIE['otpauth'] == md5($user[3]) && ($user[4] == 0 || $user[4] == 2))) {
          if ($user[4] == 0 || $user[4] == 2) {
            setcookie("otpauth", md5($user[3]), [
              'expires' => time() + (86400 * 7),
              'path' => "/",
              'domain' => $_SERVER['SERVER_NAME'],
              'secure' => true,
              'httponly' => true,
              'samesite' => 'Strict'
            ]);
          }

          echo '{"result":"ok"}';
          $auth_token = $coderclass->encode($user[0], $coderclass->today_private_key());
          setcookie("auth_token", $auth_token, [ 'expires' => time() + 3600, 'path' => "/", 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' ]);
          setcookie('auth_timer', time() + 3600, ['expires' => time() + 3610, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'],'secure' => true,'httponly' => false, 'samesite' => 'Strict']);
        } else {
          echo '{"result":"Hibás kétlépcsős hitelesítés!"}';
          setcookie('auth_token', '', [ 'expires' => time() - 3600, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict']);
        }
      } else {

        echo '{"result":"ok"}';
        $auth_token = $coderclass->encode($user[0], $coderclass->today_private_key());
        setcookie("auth_token", $auth_token, [ 'expires' => time() + 3600, 'path' => "/", 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' ]);
        setcookie('auth_timer', time() + 3600, ['expires' => time() + 3610, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'],'secure' => true,'httponly' => false, 'samesite' => 'Strict']);
      }

      exit();
    } else {
      echo '{"result":"A felhasználónév és a jelszó kombinációja helytelen."}';
      setcookie('auth_token', '', [ 'expires' => time() - 3600, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict']);
      exit();
    }
  } else {
    echo '{"result":"Biztonsági titkos Token hiba! Töltse újra az oldalt."}';
    setcookie('auth_token', '', [ 'expires' => time() - 3600, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict']);
    exit();
  }
} else if (!empty($_COOKIE['auth_token'] ?? '')) {
  header("Location: dashboard/");
  exit();
}

$anticsrfid = bin2hex(random_bytes(24));
$_SESSION["anticsrfid"] = $anticsrfid;

?>
<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Szaturnusz</title>
    <link rel="stylesheet" href="css/login.css">
    <script src="js/feather-icons.js"></script>
  </head>
  <?php
  if ($ServerLocalIP != '192.168.15.10') {
    echo '<style>
    :root {
      --bgcolorlight: #008000;
      --bgcolordark: #007a80;
    }
    </style>';
  }
  ?>
  <body>
    <div class="otcdiv deactive" id="otcdiv">
      <h1>Kétlépcsős hitelesítés</h1>
      <p>Kérjük, adja meg a hitelesítő alkalmazása által generált 6 számjegyű kódot!</p>
      <input type="text" id="otc" class="otc" name="otc" maxlength="6" autocomplete="off" oninput="this.value = this.value.replace(/[^0-9]/g, '');" onkeyup="checkLength(this);" onkeydown="if (event.key === 'Enter') {event.preventDefault(); document.getElementById('submit-otp').click();}">
      <input type="submit" id="submit-otp" name="submit" value="Belépés" onclick="login();" disabled>
    </div>
    <div class="bg"></div>
    <div class="protection" id="protection">
      <p>Biztonsági ellenőrzés</p>
      <img id="protection_img" src="img/protection.gif">
      <p id="protection_text" class="result">A Javascript engedélyezése kötelező!</p>
      <div class="hidden">
        <img src="img/shieldok.gif">
        <img src="img/shieldno.gif">
        <img src="img/protection.gif">
      </div>
      <div class="hp">
        <form id="hp">
          <input type="text" placeholder="Enter Username" name="unamehp" id="unamehp">
          <input type="password" placeholder="Enter Password" name="pswhp" id="pswhp">
          <button type="submit">LogIn</button>
        </form>
      </div>
    </div>
    <div class="container">
      <div class="login">
        <div class="mobilelogin">
          <h1>Szaturnusz</h1>
        </div>
        <div class="form">
          <i class="icon"><i data-feather="user"></i></i><input type="text" id="usr" name="usr" placeholder="Felhasználónév" autocomplete="off" autocapitalize="off" spellcheck="false" autocorrect="off" onkeydown="if (event.keyCode == 13) {login()}">
          <i class="icon"><i data-feather="key"></i></i><input type="password" id="psw" name="psw" placeholder="Jelszó" autocomplete="off" spellcheck="false" class="pass" autocapitalize="off" autocorrect="off" onkeydown="if (event.keyCode == 13) {login()}">
          <input type="hidden" id="anticsrf" name="anticsrf" value="<?php echo $anticsrfid;?>">
          <input type="submit" id="submit" name="submit" value="Belépés" onclick="login();">
        </div>
        <p class="errortext" id="errortext"></p>
      </div>
      <div class="info">
        <br><br><br>
        <h1>Szaturnusz</h1>
        <p>Kezelőfelület</p>
        <?php
        if ($ServerLocalIP != '192.168.15.10') {
          echo '<br><p>Teszt környezet</p>';
        }
        ?>
      </div>
      <section>
        <div class="wave wave1"></div>
        <div class="wave wave2"></div>
        <div class="wave wave3"></div>
        <div class="wave wave4"></div>
      </section>
    </div>

    <script type="text/javascript" src="js/default.js"></script>
    <script type="text/javascript">

      feather.replace();

      const protection = document.getElementById("protection");
      const protection_img = document.getElementById("protection_img");
      const protection_text = document.getElementById("protection_text");

      var TypingMax = 0;
      var isTyping = false;
      function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;}
      function SimulateTypingProtector(text, elementId, isEnd) {
        if (isTyping) {
          setTimeout(function() {
            if (isEnd) {protection_text.classList.add("result");} else {protection_text.classList.remove("result");}
            protection_text.innerHTML = "";
            SimulateTyping(text, elementId);
          }, TypingMax);
        } else {
          if (isEnd) {protection_text.classList.add("result");} else {protection_text.classList.remove("result");}
          protection_text.innerHTML = "";
          SimulateTyping(text, elementId);
        }
      }
      function SimulateTyping(text, elementId) {
        var element = document.getElementById(elementId);
        var delaymin = 20;
        var delaymax = 40;
        var index = 0;
        TypingMax = text.length * delaymax;
        isTyping = true;
        var timer = setInterval(function() {
          if (index < text.length) {
            var char = text.charAt(index);
            element.innerHTML += char;
            index++;
          } else {
            clearInterval(timer);
            element.innerHTML = text;
            isTyping = false;
          }
        }, getRandomNumber(delaymin, delaymax));
      }

      function editProtectionStatus() {
        BlockLogin();
      }

      function OpenOTP() {
        BlockLogin();
      }

      var lastlength = 0;
      function checkLength(input) {
        const loginButton = document.getElementById('submit-otp');
        if (input.value.length === 6) {
          loginButton.disabled = false;
          if (lastlength == 0) {
            login();
          }
        } else {
          loginButton.disabled = true;
        }
        lastlength = input.value.length;
      }

      var isSecure = false;
      var TryedToLogin = false;

      function CheckOutsideSec() {
        if (!isSecure && !TryedToLogin) {
          return true;
        }
        return false;
      }

      {
        function editProtectionStatus(text, isEnd = false, isSuccess = false, toHide = false) {
          if (isEnd && isSuccess) {
            protection_img.src = "img/shieldok.gif";
            if (toHide) { protection.classList.add("active"); setTimeout(function() {protection_img.src = "img/protection.gif";}, 2800); } else {protection.classList.remove("active"); }
            SimulateTypingProtector("Siker! Hozzáférés megadva.", "protection_text", isEnd);
          } else if (isEnd) {
            protection_img.src = "img/shieldno.gif";
            if (toHide) { protection.classList.add("active"); setTimeout(function() {protection_img.src = "img/protection.gif";}, 2800); } else {protection.classList.remove("active"); }
            SimulateTypingProtector(text, "protection_text", isEnd);
          } else {
            protection_img.src = "img/protection.gif";
            protection.classList.remove("active");
            SimulateTypingProtector(text, "protection_text", isEnd);
          }
        }

        editProtectionStatus("Böngésző ellenőrzése.");

        function OpenOTP() {
          editProtectionStatus("Kétlépcsős hitelesítés", false, false, false);
          document.getElementById("otc").value = "";
          document.getElementById('otcdiv').classList.remove("deactive");
          lastlength = 0;
        }

        let isSecure = false;
        let TryedToLogin = false;

        function BlockLogin() {
          isSecure = false;
          TryedToLogin = true;
        }

        function ProtectionChek() {

          let userAgent = navigator.userAgent;
          let userAgentLower = userAgent.toLowerCase();

          if (
            userAgentLower.indexOf('/') === -1 ||
            !/\d/.test(userAgentLower) ||
            userAgentLower.trim().split(/\s+/).length === 1 ||
            userAgentLower.includes('bot') ||
            userAgentLower.includes('http')
          ) {
            editProtectionStatus("BOT detektálva! Hozzáférés megtagadva!", true);
          } else {

            get_POST_information("js/bot.php?j=1", '', function(text) {
              let response = JSON.parse(text);
              if (response.status == "ok") {
                editProtectionStatus("", true, true, true);
                isSecure = true;
              } else {
                editProtectionStatus("BOT detektálva! Hozzáférés megtagadva!", true);
              }
            }, function() {
              document.getElementById("errortext").innerHTML = "Hálózati hiba. Próbálja újra.";
              editProtectionStatus("Hálózati hiba. Próbálja újra.", true, false, true);
              setTimeout(function() {protection_img.src = "img/protection.gif";}, 2800);
            });
          }

        }

        setTimeout(ProtectionChek(), getRandomNumber(3000, 5000));

        document.getElementById("hp").addEventListener("submit", function(event) {
          event.preventDefault();

          TryedToLogin = true;
          editProtectionStatus("Jogtalan bejelentkezési kísérlet!", true);
        });

        function login() {
          document.getElementById('otcdiv').classList.add("deactive");
          if (isSecure && !TryedToLogin && CheckOutsideSec()) {
            editProtectionStatus("Bejelentkezés folyamat.");

            setTimeout(function () {
              var usr = encodeURIComponent(document.getElementById("usr").value).replace(/%20/g, '+');
              var psw = encodeURIComponent(document.getElementById("psw").value).replace(/%20/g, '+');
              var anticsrf = encodeURIComponent(document.getElementById("anticsrf").value).replace(/%20/g, '+');
              var otp = encodeURIComponent(document.getElementById("otc").value).replace(/%20/g, '+');

              const body = 'login=islogin&anticsrf=' + anticsrf + '&psw=' + psw + '&usr=' + usr + '&otc=' + otp;
              get_POST_information("index.php", body, function(text) {
                document.getElementById("otc").value = "";
                let response = JSON.parse(text);
                if (response.result == "ok") {
                  editProtectionStatus("A bejelentkezés sikeres!", true, true, false);

                  setTimeout(function() {
                    if (<?php echo ($_GET['noredirect'] ?? '0') === '1' ? 'false' : 'true'; ?>) {
                      window.location.href = '<?php

                      $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
                      $host = $_SERVER['HTTP_HOST'];
                      $currentUrl = $protocol . $host;

                      $current_domain = $_SERVER['HTTP_HOST'];
                      if (isset($_SERVER['HTTP_REFERER'])) {
                        $referer = $_SERVER['HTTP_REFERER'];
                        $referer_host = parse_url($referer, PHP_URL_HOST);
                        $referer_path = parse_url($referer, PHP_URL_PATH);
                        if ($referer_host === $current_domain && strpos($referer_path, 'profile') === false) {
                          echo str_replace($currentUrl, "", $referer);
                        } else {echo 'dashboard/';}
                      } else {echo 'dashboard/';}

                      ?>';
                    }
                  }, 2500);
                } else if (response.result == "otp") {
                  OpenOTP();
                } else {
                  document.getElementById("errortext").innerHTML = response.result;
                  editProtectionStatus(response.result, true, false, true);
                  setTimeout(function() {protection_img.src = "img/protection.gif";}, 2800);
                }
              }, function() {
                document.getElementById("errortext").innerHTML = "Hálózati hiba. Próbálja újra.";
                editProtectionStatus("Hálózati hiba. Próbálja újra.", true, false, true);
                setTimeout(function() {protection_img.src = "img/protection.gif";}, 2800);
              });
            }, getRandomNumber(1000, 3000));

          } else {
            TryedToLogin = true;
            editProtectionStatus("Jogtalan bejelentkezési kísérlet!", true);
          }
        }

      }

    </script>

  </body>
</html>
