From 8ba1637176227d149135386bcbaec2938269076e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ryb=C3=A1rsky?= Date: Wed, 31 Jan 2024 23:07:12 +0100 Subject: [PATCH] Add some more account actions, Add return types, Add some stuff --- endpoints/global/account.php | 45 ++++++++----- index.php | 2 +- lib/account.php | 119 +++++++++++++++++++++++++++-------- lib/config.php | 8 ++- lib/endpoint.php | 2 +- lib/page.php | 62 +++++++++++++++++- pages/home/domov.html | 2 +- pages/memes/domov.html | 1 + pages/memes/info.html | 1 + pages/notes/domov.html | 1 + pages/smp/domov.html | 1 + pages/smp/info.html | 1 + templates/403.html | 6 ++ templates/404.html | 4 +- templates/skeleton.html | 2 +- 15 files changed, 210 insertions(+), 47 deletions(-) create mode 100644 templates/403.html diff --git a/endpoints/global/account.php b/endpoints/global/account.php index b876429..1604f3f 100644 --- a/endpoints/global/account.php +++ b/endpoints/global/account.php @@ -2,18 +2,35 @@ require_once "lib/account.php"; -function endpoint($endpoint_data) +function endpoint($endpoint_data): array { - switch ($endpoint_data["action"]){ - - case "login": - return doLogin($endpoint_data["email"], $endpoint_data["password"]); - - case "logout": - return doLogout(); - - case "register": - return doRegister($endpoint_data["firstname"], $endpoint_data["lastname"], $endpoint_data["nickname"], $endpoint_data["email"], $endpoint_data["password"], $endpoint_data["minecraftnick"], $endpoint_data["activation_token"]); - - } -} \ No newline at end of file + return match ($endpoint_data["action"]) { + "login" => doLogin($endpoint_data["email"], $endpoint_data["password"]), + "logout" => doLogout(), + "register" => doRegister( + $endpoint_data["firstname"], + $endpoint_data["lastname"], + $endpoint_data["nickname"], + $endpoint_data["email"], + $endpoint_data["password"], + $endpoint_data["minecraftnick"], + $endpoint_data["activation_token"] + ), + "change_password" => changePassword($endpoint_data["user_id"], $endpoint_data["new_password"]), + "update_user_profile" => updateUserProfile( + $endpoint_data["user_id"], + $endpoint_data["first_name"], + $endpoint_data["last_name"], + $endpoint_data["nickname"], + $endpoint_data["minecraft_nick"] + ), + "get_user_info" => getUserInfo($endpoint_data["user_id"]), + "is_email_available" => isEmailAvailable($endpoint_data["email"]), + "add_activation_codes" => addActivationCodes($endpoint_data["count"]), + "list_users" => listUsers(), + "list_activation_codes" => listActivationCodes(), + "delete_user" => deleteUser($endpoint_data["user_id"]), + "delete_activation_code" => deleteActivationCode($endpoint_data["activation_code"]), + default => ["status" => "fail", "message" => "Invalid action"], + }; +} diff --git a/index.php b/index.php index 30c22fd..3a03525 100644 --- a/index.php +++ b/index.php @@ -16,7 +16,7 @@ if(initRouter()) { session_set_cookie_params(0, '/', "." . $routerRequest["domain"] . "." . $routerRequest["tld"], true, true); session_start(); if($routerRequest["type"] == "api") { - echo getEndpoint($routerRequest["page_name"], $_REQUEST); + echo getEndpoint($routerRequest["page_name"]); }elseif ($routerRequest["type"] == "page") { /** @noinspection PhpArrayIsAlwaysEmptyInspection */ diff --git a/lib/account.php b/lib/account.php index 2a2f0b2..074d67e 100644 --- a/lib/account.php +++ b/lib/account.php @@ -34,8 +34,8 @@ function doLogin($email, $password): array { global $mysqli, $routerConfig; $found = false; - if(!empty($email) && !empty($password)){ - $stmt = $mysqli->prepare("SELECT ID, FirstName, LastName, Nickname, PasswordHash, MinecraftNick, privilegeLevel FROM Users WHERE EMAIL = ? AND isActive = 1"); + if (!empty($email) && !empty($password)) { + $stmt = $mysqli->prepare("SELECT ID, FirstName, LastName, Nickname, PasswordHash, MinecraftNick, PrivilegeLevel, LastLoginAt, LoginCount FROM Users WHERE Email = ? AND isActivated = 1"); $stmt->bind_param("s", $email); $stmt->execute(); @@ -46,14 +46,23 @@ function doLogin($email, $password): array $pwdhash = ""; $mcnick = ""; $privilegelevel = 0; - $stmt->bind_result($idcko, $fname, $lname, $nickname, $pwdhash, $mcnick, $privilegelevel); + $lastLoginAt = null; + $loginCount = 0; + $stmt->bind_result($idcko, $fname, $lname, $nickname, $pwdhash, $mcnick, $privilegelevel, $lastLoginAt, $loginCount); - if($stmt->num_rows() > 0){ + if ($stmt->num_rows() > 0) { $stmt->fetch(); - if (password_verify($password, $pwdhash) && $privilegelevel >= $routerConfig["logged_in_default_permission_level"]){ + if (password_verify($password, $pwdhash) && $privilegelevel >= $routerConfig["logged_in_default_permission_level"]) { $found = true; + + // Update LastLoginAt and LoginCount + $updateLoginStmt = $mysqli->prepare("UPDATE Users SET LastLoginAt = NOW(), LoginCount = LoginCount + 1 WHERE ID = ?"); + $updateLoginStmt->bind_param("i", $idcko); + $updateLoginStmt->execute(); + $updateLoginStmt->close(); } } + $_SESSION["ID"] = $idcko; $_SESSION["first_name"] = $fname; $_SESSION["last_name"] = $lname; @@ -78,12 +87,13 @@ function doLogout(): array function doRegister($firstname, $lastname, $nickname, $email, $password, $minecraftnick, $activationtoken): array { - global $mysqli; + global $mysqli, $routerConfig; $status = ["status" => "fail"]; - if (!empty($activationtoken)){ + if (!empty($activationtoken)) { $passwordHash = password_hash($password, PASSWORD_DEFAULT); - $stmt = $mysqli->prepare("UPDATE Users SET FirstName = ?, LastName = ?, Nickname = ?, Email = ?, PasswordHash = ?, MinecraftNick = ?, isAdmin = 0, isActivated = 1 WHERE isActivated = 0 AND ActivationToken = ?"); - $stmt->bind_param("sssssss", $firstname, $lastname, $nickname, $email, $passwordHash, $minecraftnick, $activationtoken); + $stmt = $mysqli->prepare("INSERT INTO Users (FirstName, LastName, Nickname, Email, PasswordHash, MinecraftNick, PrivilegeLevel, isActivated, ActivationToken, RegisteredAt) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NOW())"); + $privilegelevel = $routerConfig["logged_in_default_permission_level"]; + $stmt->bind_param("ssssssisi", $firstname, $lastname, $nickname, $email, $passwordHash, $minecraftnick, $privilegelevel, $activationtoken); $stmt->execute(); if ($stmt->affected_rows > 0) { $status["status"] = "success"; @@ -175,43 +185,102 @@ function isEmailAvailable($email): bool } -function addActivationCodes($adminID, $count): array +function addActivationCodes($count): array { - global $mysqli; + global $mysqli, $routerConfig; $activationCodes = []; - if (!empty($adminID) && is_numeric($count) && $count > 0) { - $stmt = $mysqli->prepare("INSERT INTO ActivationCodes (AdminID, Code) VALUES (?, ?)"); + + if (is_numeric($count) && $count > 0 && $_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { + $stmt = $mysqli->prepare("UPDATE Users SET ActivationCode = ?, CreatedAt = NOW(), CreatedBy = ? WHERE ID = ?"); + for ($i = 0; $i < $count; $i++) { $activationCode = generateActivationToken(); - $stmt->bind_param("is", $adminID, $activationCode); + $stmt->bind_param("sii", $activationCode, $_SESSION["ID"], $_SESSION["ID"]); $stmt->execute(); + if ($stmt->affected_rows > 0) { - $activationCodes[] = $activationCode; + $activationCodes[] = [ + "Code" => $activationCode, + "CreatedAt" => date("Y-m-d H:i:s"), + "CreatedBy" => $_SESSION["ID"] + ]; } } + $stmt->close(); } + return $activationCodes; } function listUsers(): array { - global $mysqli; - $users = []; - $result = $mysqli->query("SELECT ID, FirstName, LastName, Nickname, Email, MinecraftNick, privilegeLevel FROM Users"); - while ($row = $result->fetch_assoc()) { - $users[] = $row; + global $mysqli, $routerConfig; + $users = ["status" => "fail"]; // Default status is "fail" + + if ($_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { + $users = []; + $result = $mysqli->query("SELECT ID, FirstName, LastName, Nickname, Email, MinecraftNick, PrivilegeLevel, CreatedAt, RegisteredAt, LastLoginAt, LoginCount, CreatedBy FROM Users"); + + // Check if the query executed successfully + if ($result) { + while ($row = $result->fetch_assoc()) { + $users[] = $row; + } + } } + return $users; } function listActivationCodes(): array { - global $mysqli; - $activationCodes = []; - $result = $mysqli->query("SELECT Code FROM ActivationCodes"); - while ($row = $result->fetch_assoc()) { - $activationCodes[] = $row['Code']; + global $mysqli, $routerConfig; + $activationCodes = ["status" => "fail"]; // Default status is "fail" + + if ($_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { + $activationCodes = []; + $result = $mysqli->query("SELECT Code, CreatedAt, CreatedBy FROM Users"); + + // Check if the query executed successfully + if ($result) { + while ($row = $result->fetch_assoc()) { + $activationCodes[] = $row; + } + } } + return $activationCodes; } + +function deleteUser($userID): array +{ + global $mysqli, $routerConfig; + $status = ["status" => "fail"]; + if (!empty($userID) && $_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { + $stmt = $mysqli->prepare("DELETE FROM Users WHERE ID = ?"); + $stmt->bind_param("i", $userID); + $stmt->execute(); + if ($stmt->affected_rows > 0) { + $status["status"] = "success"; + } + $stmt->close(); + } + return $status; +} + +function deleteActivationCode($activationCode): array +{ + global $mysqli, $routerConfig; + $status = ["status" => "fail"]; + if (!empty($activationCode) && $_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { + $stmt = $mysqli->prepare("DELETE FROM Users WHERE ActivationToken = ?"); + $stmt->bind_param("s", $activationCode); + $stmt->execute(); + if ($stmt->affected_rows > 0) { + $status["status"] = "success"; + } + $stmt->close(); + } + return $status; +} \ No newline at end of file diff --git a/lib/config.php b/lib/config.php index 2b1f919..9acf7be 100644 --- a/lib/config.php +++ b/lib/config.php @@ -25,5 +25,11 @@ $routerConfig["moderator_permission_level"] = 4; - $routerConfig["adminpermissionlevel"] = 255; + $routerConfig["user_admin_permission_level"] = 254; + + $routerConfig["admin_permission_level"] = 255; + + $routerConfig["default_page_permission_level"] = 255; + + $routerConfig["default_page_secret"] = 1; } diff --git a/lib/endpoint.php b/lib/endpoint.php index 86106c6..a617001 100644 --- a/lib/endpoint.php +++ b/lib/endpoint.php @@ -10,7 +10,7 @@ function runEndpoint($endpoint_file): ?array } -function getEndpoint($endpoint_name): false|string +function getEndpoint($endpoint_name): string { $output = array(); $output["status"] = "fail"; diff --git a/lib/page.php b/lib/page.php index 7fba526..ee3b4c6 100644 --- a/lib/page.php +++ b/lib/page.php @@ -5,6 +5,31 @@ function renderDynamicPage($page_file): false|string return render(); } +function parsePageTag($input): array +{ + // Define the pattern for the tag + $pattern = '/]+)><\/page>/i'; + + // Check if the pattern matches the input + if (preg_match($pattern, $input, $matches)) { + // Extract parameters + $parameters = []; + if (preg_match_all('/(\w+)="([^"]+)"/', $matches[1], $paramMatches, PREG_SET_ORDER)) { + foreach ($paramMatches as $paramMatch) { + $parameters[$paramMatch[1]] = $paramMatch[2]; + } + } + + // Remove the tag from the input + $output = preg_replace($pattern, '', $input, 1); + + return ['parameters' => $parameters, 'output' => $output]; + } + + // If no match is found, return the original input + return ['parameters' => [], 'output' => $input]; +} + function getPage($page_name = null): array|false|string { global $routerConfig; @@ -38,6 +63,41 @@ function getPage($page_name = null): array|false|string else{ $page = file_get_contents($routerConfig["template_dir"] . "404.html"); } + + $pageMetadata = parsePageTag($page); + + $page = $pageMetadata["output"]; + + if(!empty($pageMetadata["parameters"]["minimal_permission_level"])){ + $page_required_permission = intval($pageMetadata["parameters"]["minimal_permission_level"]); + } + else{ + $page_required_permission = $routerConfig["default_page_permission_level"]; + } + + if(!empty($pageMetadata["parameters"]["secret"])){ + $is_secret_page = intval($pageMetadata["parameters"]["secret"]); + } + else{ + $is_secret_page = $routerConfig["default_page_secret"]; + } + + if($page_required_permission < $_SESSION["privilegelevel"]){ + if($is_secret_page == 1) { + $page = file_get_contents($routerConfig["template_dir"] . "404.html"); //fake 404 error + } + else{ + $page = file_get_contents($routerConfig["template_dir"] . "403.html"); //deny access if doesnt have permissions + } + } + + if(!empty($pageMetadata["parameters"]["page_title"])){ + $page_title = $pageMetadata["parameters"]["page_title"]; + } + else{ + $page_title = $page_name; + } + $navpages = generateNavigation(); $nav = str_replace("__NAV_PAGES__", $navpages, $nav); @@ -45,5 +105,5 @@ function getPage($page_name = null): array|false|string $out = $skeleton; $out = str_replace("__TEMPLATE__NAV__", $nav, $out); $out = str_replace("__TEMPLATE__PAGE__", $page, $out); - return str_replace("__TEMPLATE_PAGE_NAME__", $page_name, $out); + return str_replace("__TEMPLATE_PAGE_TITLE__", $page_title, $out); } \ No newline at end of file diff --git a/pages/home/domov.html b/pages/home/domov.html index 50c1065..32d3e1f 100644 --- a/pages/home/domov.html +++ b/pages/home/domov.html @@ -1,4 +1,4 @@ - +

Vitaj na tejto úžasnej stránke

Neoficiálna študentská stránka pre adlerku

diff --git a/pages/memes/domov.html b/pages/memes/domov.html index 24e5675..0115dbd 100644 --- a/pages/memes/domov.html +++ b/pages/memes/domov.html @@ -1,3 +1,4 @@ +

Adlerka Memes

Skoro ako r/adlerka - ale lepšie.

diff --git a/pages/memes/info.html b/pages/memes/info.html index 94278cd..33e7d6b 100644 --- a/pages/memes/info.html +++ b/pages/memes/info.html @@ -1 +1,2 @@ +

Vitaj na oficiálnej stránke Memeov o AdlerkaSMP

\ No newline at end of file diff --git a/pages/notes/domov.html b/pages/notes/domov.html index 08e2857..d2c6ad5 100644 --- a/pages/notes/domov.html +++ b/pages/notes/domov.html @@ -1,3 +1,4 @@ +

Adlerka Zošit


diff --git a/pages/smp/domov.html b/pages/smp/domov.html index 3a4f6e3..5d40742 100644 --- a/pages/smp/domov.html +++ b/pages/smp/domov.html @@ -1,3 +1,4 @@ +

Vitaj na oficiálnej AdlerkaSMP stránke

Najlepší Minecraft®™ server na Adlerke

diff --git a/pages/smp/info.html b/pages/smp/info.html index 94d6161..16e6ae9 100644 --- a/pages/smp/info.html +++ b/pages/smp/info.html @@ -1 +1,2 @@ +

Vitaj na oficiálnej stránke Informácii o AdlerkaSMP

\ No newline at end of file diff --git a/templates/403.html b/templates/403.html new file mode 100644 index 0000000..f0ceaff --- /dev/null +++ b/templates/403.html @@ -0,0 +1,6 @@ +
+

TY KÁR KAM TO DEŠ

+

403

+

Našli sme stránku ktorú hľadáš, ale nemáš práva na ňu pristupovať: __TEMPLATE_PAGE_NAME__.

+ SPÄŤ DOMOV +
\ No newline at end of file diff --git a/templates/404.html b/templates/404.html index eaafdd1..324a00a 100644 --- a/templates/404.html +++ b/templates/404.html @@ -1,6 +1,6 @@
-

TY KÁR KAM TO DEŠ

+

TY KÁR KAM TO DEŠ

404

-

Nenašli sme stránku ktorú hladáš: __TEMPLATE_PAGE_NAME__.

+

Nenašli sme stránku ktorú hľadáš: __TEMPLATE_PAGE_NAME__.

SPÄŤ DOMOV
\ No newline at end of file diff --git a/templates/skeleton.html b/templates/skeleton.html index d140646..d3cd4f2 100644 --- a/templates/skeleton.html +++ b/templates/skeleton.html @@ -7,7 +7,7 @@ - Adlerka __TEMPLATE_PAGE_NAME__ + Adlerka __TEMPLATE_PAGE_TITLE__ __TEMPLATE__NAV__