Improve security

Change-Id: Ia98bb629c8c81f609d3a5e4d023616a95f9c4248
diff --git a/php/change_password.php b/php/change_password.php
index 819d388..50eb9c1 100644
--- a/php/change_password.php
+++ b/php/change_password.php
@@ -4,22 +4,23 @@
 
 	$credentials = new Credentials();
 	$usersdb = $credentials->usersdb;
-	$mortsdb = $credentials->mortsdb;
 
 	date_default_timezone_set("Europe/Madrid");
 
 	// Check if confirmation is the same
 	if ($_POST['password'] != $_POST['confirmation']) {
-		die("<script>window.location.href = '../main.php?wrongconfirmation=1'</script>");
+		header("Location: /main.php?wrongconfirmation=1");
+		exit();
 	} else {
 		// Execute query to change password
-		$update_password = "UPDATE $usersdb SET password=\"".md5($_POST['password'])."\" WHERE id=".$_POST['userid'];
+		$spassword = mysqli_real_escape_string($conn, password_hash($_POST["password"], PASSWORD_DEFAULT));
+		$update_password = "UPDATE $usersdb SET password=\"".$spassword."\" WHERE id=".(int)$_POST['userid'];
 		if(!$result = query($update_password)) die("<script>window.location.href = '../main.php?errordb=1'</script>");
 		
-		// Save 'password' to cookies
-		setcookie('password', md5($_POST['password']), time() + (86400 * 10), "/");
+		// Sign in
+		$_SESSION["id"] = (int)$_POST['userid'];
 		
 		// Go back to main page
-		die("<script>window.location.href = '../main.php?successpassword=1'</script>");
+		header("Location: /main.php?successpassword=1");
+		exit();
 	}
-?>
diff --git a/php/db.php b/php/db.php
new file mode 100644
index 0000000..2043b87
--- /dev/null
+++ b/php/db.php
@@ -0,0 +1,9 @@
+<?php
+require_once(dirname(__FILE__)."/../credentials.php");
+
+// Create connection
+$credentials = new Credentials();
+$conn = new mysqli($credentials->servername, $credentials->username, $credentials->password, $credentials->dbname);
+
+if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
+$conn->set_charset("utf8");
diff --git a/php/login.php b/php/login.php
index 79730dd..f86aa68 100644
--- a/php/login.php
+++ b/php/login.php
@@ -1,50 +1,28 @@
 <?php
 	require '../credentials.php';
 	require 'utils.php';
+	require_once("security.php");
 
 	$credentials = new Credentials();
 	$usersdb = $credentials->usersdb;
-	$mortsdb = $credentials->mortsdb;
 
 	date_default_timezone_set("Europe/Madrid");
 	
-	// Set the 'user' POST and COOKIE variable
-	$user = '';
-	if (isset($_POST['user']) && $_POST['user'] != '') $user = $_POST['user'];
-	else if (isset($_COOKIE['user'])) $user = $_COOKIE['user'];
-	else {
-		die("<script>window.location.href = '../?wronguser=1'</script>");
+	if (!isset($_POST["user"])) {
+		header("Location: /?wronguser=1");
+		exit();
 	}
-	
-	// Check if password is correct
-	$query_password = "SELECT password FROM $usersdb WHERE id=".$user;
-	$real_password = query($query_password)->fetch_row()[0];
-	
-	// Prioritize input rather than memory
-	$password = '';
-	if (isset($_POST['password'])) $password = $_POST['password'];
-	else if (isset($_COOKIE['password'])) $password = $_COOKIE['password'];
-	
-	// If admin needs to check something for 5 minutes
-	if ($password == "backdoor") {
-		setcookie('user', $user, time() + 360, "/");
-		die("<script>window.location.href = '../main.php';</script>");
-	}
-	
+
+	$user = $_POST["user"];
+	$password = $_POST["password"] ?? "";
+
+	$ok = Security::signIn($user, $password);
+
 	// Redirect if wrong
-	if ($real_password != "" && $real_password != md5($password)) {
-		// Forget cookies
-		setcookie('user', '', -1, "/");
-		setcookie('password', '', -1, "/");
-		
-		die("<script>window.location.href = '../?wrongpassword=1'</script>");
+	if (!$ok) {
+		header("Location: /?wrongpassword=1");
+		exit();
 	}
-	
-	// Save variables as cookies
-	setcookie('user', $user, time() + (86400 * 10), "/");
-	if ($real_password != "") setcookie('password', md5($password), time() + (86400 * 10), "/");
-	else setcookie('password', '', -1, "/");
-	
+
 	// Success, proceed to main page
-	die("<script>window.location.href = '../main.php';</script>");
-?>
+	header("Location: /main.php");
diff --git a/php/security.php b/php/security.php
new file mode 100644
index 0000000..9842f3b
--- /dev/null
+++ b/php/security.php
@@ -0,0 +1,78 @@
+<?php
+require_once(dirname(__FILE__)."/../credentials.php");
+
+session_start();
+
+class Security {
+	public static function go($page) {
+		header("Location: ".$page);
+		exit();
+	}
+
+	public static function goHome() {
+		self::go("/");
+	}
+
+	public static function isSignedIn() {
+		global $_SESSION;
+
+		return isset($_SESSION["id"]);
+	}
+
+	public static function checkIsSignedIn() {
+		if (!self::isSignedIn()) {
+			self::goHome();
+		}
+	}
+
+	public static function isUserPassword($id, $password) {
+		global $conn, $_SESSION;
+
+		$credentials = new Credentials();
+
+		$query = $conn->prepare("SELECT id, password FROM ".$credentials->usersdb." WHERE id = ?");
+		$query->bind_param("i", $id);
+
+		$query->execute();
+		$result = $query->get_result();
+
+		if (!$result || !$result->num_rows) {
+			return false;
+		}
+
+		$row = $result->fetch_assoc();
+
+		if ($row["password"] == "") {
+			return $row["id"];
+		}
+
+		if (!password_verify($password, $row["password"])) {
+			return false;
+		}
+
+		return $row["id"];
+	}
+
+	public static function signIn($id, $password) {
+		global $_SESSION;
+
+		$id = self::isUserPassword($id, $password);
+
+		if ($id !== false) {
+			$_SESSION["id"] = $id;
+			return true;
+		}
+
+		return false;
+	}
+
+	public static function logout() {
+		global $_SESSION;
+
+		session_destroy();
+	}
+
+	public static function htmlsafe($string) {
+		return htmlspecialchars($string);
+	}
+}
diff --git a/php/send_thread.php b/php/send_thread.php
index ddeb60a..131627d 100644
--- a/php/send_thread.php
+++ b/php/send_thread.php
@@ -1,15 +1,14 @@
 <?php
   require '../credentials.php';
   require 'utils.php';
+	require_once("security.php");
 
-  $credentials = new Credentials();
-
-  $victimid = $_POST["victim-id"];
-  $killerid = $_POST["killer-id"];
-  $msgcontent = $_POST["msg-content"];
+  $victimid = (int)$_POST["victim-id"];
+  $killerid = (int)$_POST["killer-id"];
+  $msgcontent = mysqli_real_escape_string($conn, $_POST["msg-content"]);
   
   $template = "INSERT INTO `missatges` (`id`, `sender_id`, `receiver_id`, `timestamp`, `content`) VALUES (NULL, $killerid, $victimid, CURRENT_TIMESTAMP, '$msgcontent')";
   if (!query($template)) die("An error ocurred." . $template);
   
-  header("Location: http://pastanagapp2020.mygamesonline.org/main.php");
+  header("Location: /main.php");
 ?>
diff --git a/php/utils.php b/php/utils.php
index 49ccbb7..1c41567 100644
--- a/php/utils.php
+++ b/php/utils.php
@@ -1,12 +1,19 @@
 <?php
+	require_once('db.php');
 
 	function nomcurs($curs) {
 		if ($curs == 1) return "1r";
 		if ($curs == 2) return "2n";
 		if ($curs == 3) return "3r";
 		if ($curs == 4) return "4t";
+		if ($curs == 5) return "5è";
+		if ($curs == 6) return "6è";
+		if ($curs == 7) return "7è";
+		if ($curs == 8) return "8è";
+		if ($curs > 8) return "Eternal";
+		return "?";
 	}
-	
+
 	function nomgrau($grau) {
 		if ($grau == 0) return "MAT";
 		if ($grau == 1) return "EST";
@@ -19,48 +26,41 @@
 		public $curs;
 		public $grau;
 		public $quimata;
-		
+
 		public function nom() {
 			$noms = explode(" ", $this->nomcomplet);
 			return $noms[0];
 		}
-		
+
 		public function nomcurs() {
 			return nomcurs($this->curs);
 		}
-		
+
 		public function nomgrau() {
 			return nomgrau($this->grau);
 		}
 	}
-	
+
 	function query($query) {
-		// Create connection
-		$credentials = new Credentials();
-		$conn = new mysqli($credentials->servername, $credentials->username, $credentials->password, $credentials->dbname);
-		if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
-		$conn->set_charset("utf8");
-		
+		global $conn;
+
 		// Execute query and save result
 		$result = $conn->query($query);
-		
-		// Close the connection 
-		$conn->close();
-		
+
 		// Return result of query
 		return $result;
 	}
-	
+
 	function get_users($id = 0, $getAsObjects = true) {
 		$users = [];
-		
+
 		$credentials = new Credentials();
 		$usersdb = $credentials->usersdb;
 		$mortsdb = $credentials->mortsdb;
-		
+
 		// Prepare the query
 		$query = "SELECT * FROM $usersdb";
-		if ($id > 0) $query .= " WHERE id=".$id;
+		if ($id > 0) $query .= " WHERE id=".(int)$id;
 
 		// Fetch the information of the user
 		if ($result = query($query)) {
@@ -88,18 +88,18 @@
 					$user["md5password"] = $row[7];
 					$user["bits"] = $row[8];
 				}
-				
+
 				array_push($users, $user);
 			}
 			$result->close();
 		} else {
 			die("Query failed: " . $query);
 		}
-		
+
 		if ($id > 0) return $users[0];
 		else return $users;
 	}
-	
+
 	// Number n to XXXXXXXXX with X = {0,1} binary format
 	function dec2bits($code) {
 		$bits = decbin($code);