Improve security

Change-Id: Ia98bb629c8c81f609d3a5e4d023616a95f9c4248
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);
+	}
+}