<!DOCTYPE html>
<!--
  Copyright (C) 2022, 2024  Double Bastion LLC

  This file is part of Roundpin, which is licensed under the
  GNU Affero General Public License Version 3.0. The license terms
  are detailed in the "LICENSE.txt" file located in the root directory.

  This is a modified version of the original file "index.html",
  first modified in 2020. The copyright notice for the original
  content follows:

  Copyright (c) 2019 by Daniel Zawadzki (https://codepen.io/danzawadzki/pen/EgqKRr)
  License: The MIT License
-->

<head>
   <meta charset="utf-8">
   <title>Roundpin</title>
   <link rel="stylesheet" href="css/login.css"/>
   <link rel="stylesheet" href="css/inter.min.css"/>
   <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
   <script type="text/javascript" src="js/roundpin-login.js"></script>
   <link rel="shortcut icon" type="image/svg" href="images/favicon.svg" />
</head>
<body>

<div class="wrapper">
  <div id="formContent">

    <!-- Tabs Titles -->
    <a href="login.php"><h2 id="signintab" class="active underlineHover">Log In</h2></a>
    <a id="signupsec" href="src/roundpin-signup.php"><h2 id="signuptab" class="underlineHover">Sign Up</h2></a>

    <!-- Icon -->
    <div id="logosection">
      <img src="images/login-logo.svg" id="login-logo" alt="Roundpin logo" />
    </div>

    <div id="submitmessage"></div>

    <!-- Login Form -->
    <form id="loginform" method="POST">
      <div id="usernameLabel" class="fadeInSpec">Username</div>
      <input type="text" id="loginname" name="loginname" placeholder="Username" />
      <div id="passwordLabel" class="fadeInSpec">Password</div>
      <input type="password" id="password" name="password" placeholder="Password"/>
      <input type="submit" id="signinbutton" name="signinbutton" value="Log In"/>
    </form>

    <!-- Remind Passowrd -->
    <div id="formFooter">
      <a id="forgotpass" class="underlineHover" href="src/forgot-password.php">Forgot Password?</a>
    </div>

  </div>
</div>

<?php

define('ACCESSCONST', TRUE);
define('RESTRICTED', TRUE);

require 'src/db-connect.php';

// Extract the sign up parameter from 'src/install-signup-check.php' to activate or deactivate the 'Sign Up' tab
if (is_file(dirname(__FILE__) . '/src/install-signup-check.php')) {

    $setupfile = file(dirname(__FILE__) . '/src/install-signup-check.php');
    $signup_check = 'false';

    foreach ($setupfile as $keyfile => $valuefile) {
         if ((strpos($valuefile, "\$signupcheck") !== false) && (strpos($valuefile, "//") === false)) {
              $signup_init = explode("=", $valuefile);
              $firsttwo_init = str_replace(" ","", $signup_init[0]);
              $signup_sec = explode(";", $signup_init[1]);
              $signup_check = str_replace(" ","", $signup_sec[0]);
              break;
         }
    }

    ?>
    <script type="text/javascript">
          var signupCheck = "<?php print_r($signup_check); ?>";
    </script>
    <?php


 if (isset($_POST['signinbutton'])) {

    $signinusername = $_POST['loginname'];
    $signinpassword = $_POST['password'];

    if ($_POST['loginname'] != '' && $_POST['password'] != '') {

      // Get password for current user from database
      $enabled = 1;
      $sqlquery = $mysqli->prepare("SELECT username, password, registered, enabled FROM app_users WHERE BINARY username=? and enabled=?");
      $sqlquery->bind_param("si", $signinusername, $enabled);
      $sqlquery->execute();
      $fetchdata = $sqlquery->get_result();
      $fetchresult = $fetchdata->fetch_row();

      if ($fetchresult != '') {

	      $signinpassfromdb = $fetchresult[1];
	      $registered = $fetchresult[2];
	      $sqlquery->close();

	      // Verify given password
	      $signinpswdverify = password_verify($signinpassword, $signinpassfromdb);

		if ($registered == '0') {
		   ?>
		   <script type="text/javascript">
		       $("#submitmessage").append("<span>Your account hasn't been activated yet. Please check your email account used at registration and click on the activation link to activate your account !</span>");
		       $("#submitmessage").css("color", "#AC1F23");
		   </script>
		   <?php
		} elseif ($signinpswdverify && $registered == '1') {

		    session_start();
                    header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

		    $_SESSION['loginname'] = $signinusername;
		    $_SESSION['loggedtoroundpin'] = true;

		    // Generate a random string to prevent direct access to different PHP files
		    function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
		       $pieces = [];
		       $max = mb_strlen($keyspace, '8bit') - 1;

		       for ($i = 0; $i < $length; ++$i) {
			    $pieces []= $keyspace[random_int(0, $max)];
		       }
		       return implode('', $pieces);
		    }

		    $_SESSION['validate_s_access'] = random_str(40);

		    ?>
                       <script type="text/javascript">
                               window.open('https://' + window.location.host + '/index.php', '_self');
                       </script>
                    <?php

		} else {
		   ?>
		   <script type="text/javascript">
		       $("#submitmessage").append("<span>Incorrect username and/or password !</span>");
		       $("#submitmessage").css("color", "#AC1F23");
		   </script>
		   <?php
		  }
      } else {
		   ?>
		   <script type="text/javascript">
		       $("#submitmessage").append("<span>Incorrect username and/or password !</span>");
		       $("#submitmessage").css("color", "#AC1F23");
		   </script>
		   <?php
        }

    } else {
           ?>
           <script type="text/javascript">
               $("#submitmessage").append("<span>Please enter both your username and password!</span>");
               $("#submitmessage").css("color", "#AC1F23");
           </script>
           <?php
    }
 }
}

?>

</body>
</html>

