Implement a bunch of stuff

This commit is contained in:
Bruno Rybársky 2024-02-03 16:08:26 +01:00
parent e3722e3ef7
commit 15964cf109
15 changed files with 690 additions and 242 deletions

37
assets/script.js Normal file

@ -0,0 +1,37 @@
function doAction(requestData, successMessage, failureMessage) {
return fetch('https://home.adlerka.top/account', {
method: 'POST',
body: requestData,
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
handleResponse(data, successMessage, failureMessage);
return data; // Returning the response data for further processing
})
.catch((error) => {
console.error('Error:', error);
});
}
function handleResponse(data, SuccessMessage, failureMessage) {
const StatusMessageElement = document.getElementById("StatusMessage");
if (data.Status === 'Success') {
StatusMessageElement.innerText = SuccessMessage;
} else {
StatusMessageElement.innerText = failureMessage;
}
}
function logout() {
const data = new URLSearchParams();
data.append("action", "logout");
doAction(data, "Logout Successful!", "Logout failed.");
}

@ -1,31 +0,0 @@
function login(){
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
doLogin(email, password);
}
function doLogin(email, password) {
const data = new URLSearchParams();
data.append("action", "login");
data.append("email", email);
data.append("password", password);
// Assuming you use fetch API to send data to the server
fetch('https://home.adlerka.top/account', {
method: 'POST',
body: data,
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
document.getElementById("statusMessage").innerText = "Login successful!";
// Redirect or perform other actions after successful login
} else {
document.getElementById("statusMessage").innerText = "Login failed. Please check your credentials.";
}
})
.catch((error) => {
console.error('Error:', error);
});
}

@ -0,0 +1,3 @@

@ -4,33 +4,39 @@ require_once "lib/account.php";
function endpoint($endpoint_data): array function endpoint($endpoint_data): array
{ {
return match ($endpoint_data["action"]) { return match ($endpoint_data["action"]) {
//not logged in start
"login" => doLogin($endpoint_data["email"], $endpoint_data["password"]), "login" => doLogin($endpoint_data["email"], $endpoint_data["password"]),
"logout" => doLogout(),
"register" => doRegister( "register" => doRegister(
$endpoint_data["firstname"], $endpoint_data["firstname"],
$endpoint_data["lastname"], $endpoint_data["lastname"],
$endpoint_data["nickname"],
$endpoint_data["email"], $endpoint_data["email"],
$endpoint_data["password"], $endpoint_data["password"],
$endpoint_data["minecraftnick"],
$endpoint_data["activation_token"] $endpoint_data["activation_token"]
), ),
"change_password" => changePassword($endpoint_data["user_id"], $endpoint_data["new_password"]), //not logged in end
//logged in start
"logout" => doLogout(),
"change_password" => changePassword(
$endpoint_data["old_password"],
$endpoint_data["new_password"]
),
"update_user_profile" => updateUserProfile( "update_user_profile" => updateUserProfile(
$endpoint_data["user_id"],
$endpoint_data["first_name"], $endpoint_data["first_name"],
$endpoint_data["last_name"], $endpoint_data["last_name"],
$endpoint_data["nickname"], $endpoint_data["nickname"],
$endpoint_data["minecraft_nick"] $endpoint_data["minecraft_nick"]
), ),
"get_user_info" => getUserInfo($endpoint_data["user_id"]), "get_user_info" => getUserInfo(),
"is_email_available" => isEmailAvailable($endpoint_data["email"]), //logged in end
//admin start
"add_activation_codes" => addActivationCodes($endpoint_data["count"]), "add_activation_codes" => addActivationCodes($endpoint_data["count"]),
"list_users" => listUsers(), "list_users" => listUsers(),
"list_activation_codes" => listActivationCodes(), "list_activation_codes" => listActivationCodes(),
"delete_user" => deleteUser($endpoint_data["user_id"]), "delete_user" => deleteUser($endpoint_data["user_id"]),
"delete_activation_code" => deleteActivationCode($endpoint_data["activation_code"]), "delete_activation_code" => deleteActivationCode($endpoint_data["activation_code"]),
default => ["status" => "fail", "message" => "Invalid action"], //admin end
default => ["Status" => "Fail", "message" => "Invalid action"],
}; };
} }

@ -5,181 +5,45 @@ use Random\RandomException;
function isLoggedIn(): bool function isLoggedIn(): bool
{ {
global $routerConfig; global $routerConfig;
return $_SESSION["ID"] > 0 && !empty($_SESSION["email"]) && $_SESSION["privilegelevel"] >= $routerConfig["logged_in_default_permission_level"]; return $_SESSION["ID"] > 0 && !empty($_SESSION["email"]) && $_SESSION["privilege_level"] >= $routerConfig["logged_in_default_permission_level"];
} }
function isVerified(): bool
function setDefaultSessionData(): void
{ {
global $routerConfig; global $routerConfig;
$_SESSION["ID"] = 0; return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["verified_permission_level"];
$_SESSION["first_name"] = "";
$_SESSION["last_name"] = "";
$_SESSION["nickname"] = "";
$_SESSION["email"] = "";
$_SESSION["mcnick"] = "";
$_SESSION["privilegelevel"] = $routerConfig["logged_out_permission_level"];
} }
function isTrustWorthy(): bool
{
global $routerConfig;
return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["trustworthy_permission_level"];
}
function isModerator(): bool
{
global $routerConfig;
return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["moderator_permission_level"];
}
function isUserAdmin(): bool
{
global $routerConfig;
return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["user_admin_permission_level"];
}
function isAdmin(): bool
{
global $routerConfig;
return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["admin_permission_level"];
}
function generateActivationToken(): string function generateActivationToken(): string
{ {
try { try {
return bin2hex(random_bytes(16)); return bin2hex(random_bytes(16));
} catch (RandomException $e) { } catch (RandomException) {
return "error_generating_code_because_of_$e";
} // Adjust the length of the token as needed
}
function verifyPassword($userID, $password): bool
{
global $mysqli;
$stmt = $mysqli->prepare("SELECT PasswordHash FROM Users WHERE ID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
$pwdhash = "";
$stmt->bind_result($pwdhash);
$stmt->fetch();
$stmt->close();
return !empty($pwdhash) && password_verify($password, $pwdhash);
}
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, LastLoginAt, LoginCount FROM Users WHERE Email = ? AND isActivated = 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$idcko = 0;
$fname = "";
$lname = "";
$nickname = "";
$pwdhash = "";
$mcnick = "";
$privilegelevel = 0;
$lastLoginAt = null;
$loginCount = 0;
$stmt->bind_result($idcko, $fname, $lname, $nickname, $pwdhash, $mcnick, $privilegelevel, $lastLoginAt, $loginCount);
if ($stmt->num_rows() > 0) {
$stmt->fetch();
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;
$_SESSION["nickname"] = $nickname;
$_SESSION["email"] = $email;
$_SESSION["mcnick"] = $mcnick;
$_SESSION["privilegelevel"] = $privilegelevel;
$stmt->close();
} }
return $found ? ["status" => "success"] : ["status" => "fail"];
}
function doLogout(): array
{
if(isLoggedIn()){
session_destroy();
return ["status" => "success"];
} else {
return ["status" => "fail"];
}
}
function doRegister($firstname, $lastname, $nickname, $email, $password, $minecraftnick, $activationtoken): array
{
global $mysqli, $routerConfig;
$status = ["status" => "fail"];
if (!empty($activationtoken)) {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$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";
}
$stmt->close();
}
return $status;
}
function changePassword($userID, $newPassword): array
{
global $mysqli, $routerConfig;
$status = ["status" => "fail"];
if(!empty($userID) && !empty($newPassword) && verifyPassword($userID, $newPassword) && $_SESSION["privilegelevel"] >= $routerConfig["logged_in_default_permission_level"]){
$passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
$stmt = $mysqli->prepare("UPDATE Users SET PasswordHash = ? WHERE ID = ?");
$stmt->bind_param("si", $passwordHash, $userID);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$status["status"] = "success";
}
$stmt->close();
}
return $status;
}
function updateUserProfile($userID, $firstName, $lastName, $nickname, $minecraftNick): array
{
global $mysqli;
$status = ["status" => "fail"];
if (!empty($userID)) {
$stmt = $mysqli->prepare("UPDATE Users SET FirstName = ?, LastName = ?, Nickname = ?, MinecraftNick = ? WHERE ID = ?");
$stmt->bind_param("ssssi", $firstName, $lastName, $nickname, $minecraftNick, $userID);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$status["status"] = "success";
}
$stmt->close();
}
return $status;
}
function getUserInfo($userID): array
{
global $mysqli;
$userInfo = [];
if (!empty($userID)) {
$stmt = $mysqli->prepare("SELECT ID, FirstName, LastName, Nickname, Email, MinecraftNick, privilegeLevel FROM Users WHERE ID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
$id = 0;
$firstName = "";
$lastName = "";
$nickname = "";
$email = "";
$minecraftNick = "";
$privilegeLevel = 0;
$stmt->bind_result($id, $firstName, $lastName, $nickname, $email, $minecraftNick, $privilegeLevel);
$stmt->fetch();
$stmt->close();
$userInfo = [
"ID" => $id,
"FirstName" => $firstName,
"LastName" => $lastName,
"Nickname" => $nickname,
"Email" => $email,
"MinecraftNick" => $minecraftNick,
"PrivilegeLevel" => $privilegeLevel
];
}
return $userInfo;
} }
function isEmailAvailable($email): bool function isEmailAvailable($email): bool
@ -196,13 +60,230 @@ function isEmailAvailable($email): bool
return $count === 0; return $count === 0;
} }
function setDefaultSessionData(): void
{
global $routerConfig;
$_SESSION["ID"] = 0;
$_SESSION["first_name"] = "";
$_SESSION["last_name"] = "";
$_SESSION["nickname"] = "";
$_SESSION["email"] = "";
$_SESSION["minecraft_nickname"] = "";
$_SESSION["privilege_level"] = $routerConfig["logged_out_permission_level"];
}
function verifyPassword($userID, $password): bool
{
global $mysqli;
$stmt = $mysqli->prepare("SELECT PasswordHash FROM Users WHERE ID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
$password_hash = "";
$stmt->bind_result($password_hash);
$stmt->fetch();
$stmt->close();
return !empty($password_hash) && password_verify($password, $password_hash);
}
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, LastLoginAt, LoginCount FROM Users WHERE Email = ? AND isActivated = 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$uid = 0;
$first_name = "";
$last_name = "";
$nickname = "";
$password_hash = "";
$minecraft_nickname = "";
$privilege_level = 0;
$lastLoginAt = null;
$loginCount = 0;
$stmt->bind_result($uid, $first_name, $last_name, $nickname, $password_hash, $minecraft_nickname, $privilege_level, $lastLoginAt, $loginCount);
if ($stmt->num_rows() > 0) {
$stmt->fetch();
if (password_verify($password, $password_hash) && $privilege_level >= $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", $uid);
$updateLoginStmt->execute();
$updateLoginStmt->close();
}
}
$_SESSION["ID"] = $uid;
$_SESSION["first_name"] = $first_name;
$_SESSION["last_name"] = $last_name;
$_SESSION["nickname"] = $nickname;
$_SESSION["email"] = $email;
$_SESSION["minecraft_nickname"] = $minecraft_nickname;
$_SESSION["privilege_level"] = $privilege_level;
$stmt->close();
}
return $found ? ["Status" => "Success"] : ["Status" => "Fail"];
}
function doLogout(): array
{
if(isLoggedIn()){
setDefaultSessionData();
return ["Status" => "Success"];
} else {
return ["Status" => "Fail"];
}
}
function doRegister($firstname, $lastname, $email, $password, $activation_token): array
{
global $mysqli, $routerConfig;
$status = ["Status" => "Fail"];
if (!empty($activation_token) && !empty($email) && !empty($password) && !empty($firstname) && !empty($lastname) && isEmailAvailable($email)) {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $mysqli->prepare("INSERT INTO Users (FirstName, LastName, Email, PasswordHash, PrivilegeLevel, isActivated, ActivationToken, RegisteredAt) VALUES (?, ?, ?, ?, ?, 1, ?, NOW())");
$privilege_level = $routerConfig["logged_in_default_permission_level"];
$stmt->bind_param("ssssis", $firstname, $lastname, $email, $passwordHash, $privilege_level, $activation_token);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$status["Status"] = "Success";
}
$stmt->close();
}
return $status;
}
function changePassword($oldPassword, $newPassword): array
{
global $mysqli;
$status = ["Status" => "Fail"];
$userID = $_SESSION["ID"];
if(!empty($oldPassword) && !empty($newPassword) && isLoggedIn() && verifyPassword($userID, $oldPassword)){
$passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
$stmt = $mysqli->prepare("UPDATE Users SET PasswordHash = ? WHERE ID = ?");
$stmt->bind_param("si", $passwordHash, $userID);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$status["Status"] = "Success";
}
$stmt->close();
}
return $status;
}
// Function to update user profile
function updateUserProfile($firstName, $lastName, $nickname, $minecraft_nickname): array
{
global $mysqli;
$status = ["Status" => "Fail"];
if (isLoggedIn() && !empty($firstName) && !empty($lastName) && !empty($nickname) && !empty($minecraft_nickname)) {
$userID = $_SESSION["ID"];
$stmt = $mysqli->prepare("UPDATE Users SET FirstName = ?, LastName = ?, Nickname = ?, MinecraftNick = ? WHERE ID = ?");
$stmt->bind_param("ssssi", $firstName, $lastName, $nickname, $minecraft_nickname, $userID);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$status["Status"] = "Success";
}
$stmt->close();
}
return $status;
}
// Function to update user email
function updateUserEmail($email): array
{
global $mysqli;
$status = ["Status" => "Fail"];
$validmail = false;
if (isLoggedIn() && !empty($email)) {
$userID = $_SESSION["ID"];
$stmt_email_check = $mysqli->prepare("SELECT Email FROM Users WHERE ID = ?");
$stmt_email_check->bind_param("i", $userID);
$old_email = "";
$stmt_email_check->bind_result($old_email);
$stmt_email_check->execute();
$stmt_email_check->fetch();
$stmt_email_check->close();
if ($email != $old_email) {
if (isEmailAvailable($email)) {
$validmail = true;
}
} else {
$validmail = true;
}
if ($validmail) {
$stmt = $mysqli->prepare("UPDATE Users SET Email = ? WHERE ID = ?");
$stmt->bind_param("si", $email, $userID);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$status["Status"] = "Success";
}
$stmt->close();
}
}
return $status;
}
function getUserInfo(): array
{
$output = ["Status" => "Fail"];
if(isLoggedIn()) {
global $mysqli;
$userID = $_SESSION["ID"];
$stmt = $mysqli->prepare("SELECT FirstName, LastName, Nickname, Email, MinecraftNick FROM Users WHERE ID = ?");
$stmt->bind_param("i", $userID);
$stmt->execute();
$firstName = "";
$lastName = "";
$nickname = "";
$email = "";
$minecraft_nickname = "";
$stmt->bind_result($firstName, $lastName, $nickname, $email, $minecraft_nickname);
$stmt->fetch();
$stmt->close();
$output = ["Status" => "Success"];
$output += [
"ID" => $userID,
"FirstName" => $firstName,
"LastName" => $lastName,
"Nickname" => $nickname,
"Email" => $email,
"MinecraftNick" => $minecraft_nickname
];
}
return $output;
}
function addActivationCodes($count): array function addActivationCodes($count): array
{ {
global $mysqli, $routerConfig; global $mysqli, $routerConfig;
$activationCodes = []; $activationCodes = [];
if (is_numeric($count) && $count > 0 && $_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { if (is_numeric($count) && $count > 0 && $_SESSION["privilege_level"] >= $routerConfig["user_admin_permission_level"] && isLoggedIn()) {
$stmt = $mysqli->prepare("UPDATE Users SET ActivationToken = ?, CreatedAt = NOW(), CreatedBy = ? WHERE ID = ?"); $stmt = $mysqli->prepare("UPDATE Users SET ActivationToken = ?, CreatedAt = NOW(), CreatedBy = ? WHERE ID = ?");
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
@ -228,13 +309,13 @@ function addActivationCodes($count): array
function listUsers(): array function listUsers(): array
{ {
global $mysqli, $routerConfig; global $mysqli, $routerConfig;
$users = ["status" => "fail"]; // Default status is "fail" $users = ["Status" => "Fail"]; // Default Status is "Fail"
if ($_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { if (isUserAdmin()) {
$users = []; $users = [];
$result = $mysqli->query("SELECT ID, FirstName, LastName, Nickname, Email, MinecraftNick, PrivilegeLevel, CreatedAt, RegisteredAt, LastLoginAt, LoginCount, CreatedBy FROM 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 // Check if the query executed Successfully
if ($result) { if ($result) {
while ($row = $result->fetch_assoc()) { while ($row = $result->fetch_assoc()) {
$users[] = $row; $users[] = $row;
@ -248,13 +329,13 @@ function listUsers(): array
function listActivationCodes(): array function listActivationCodes(): array
{ {
global $mysqli, $routerConfig; global $mysqli, $routerConfig;
$activationCodes = ["status" => "fail"]; // Default status is "fail" $activationCodes = ["Status" => "Fail"]; // Default Status is "Fail"
if ($_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { if (isUserAdmin()) {
$activationCodes = []; $activationCodes = [];
$result = $mysqli->query("SELECT ActivationToken, CreatedAt, CreatedBy FROM Users"); $result = $mysqli->query("SELECT ActivationToken, CreatedAt, CreatedBy FROM Users");
// Check if the query executed successfully // Check if the query executed Successfully
if ($result) { if ($result) {
while ($row = $result->fetch_assoc()) { while ($row = $result->fetch_assoc()) {
$activationCodes[] = $row; $activationCodes[] = $row;
@ -268,13 +349,13 @@ function listActivationCodes(): array
function deleteUser($userID): array function deleteUser($userID): array
{ {
global $mysqli, $routerConfig; global $mysqli, $routerConfig;
$status = ["status" => "fail"]; $status = ["Status" => "Fail"];
if (!empty($userID) && $_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { if (!empty($userID) && isUserAdmin()) {
$stmt = $mysqli->prepare("DELETE FROM Users WHERE ID = ?"); $stmt = $mysqli->prepare("DELETE FROM Users WHERE ID = ?");
$stmt->bind_param("i", $userID); $stmt->bind_param("i", $userID);
$stmt->execute(); $stmt->execute();
if ($stmt->affected_rows > 0) { if ($stmt->affected_rows > 0) {
$status["status"] = "success"; $status["Status"] = "Success";
} }
$stmt->close(); $stmt->close();
} }
@ -284,13 +365,13 @@ function deleteUser($userID): array
function deleteActivationCode($activationCode): array function deleteActivationCode($activationCode): array
{ {
global $mysqli, $routerConfig; global $mysqli, $routerConfig;
$status = ["status" => "fail"]; $status = ["Status" => "Fail"];
if (!empty($activationCode) && $_SESSION["privilegelevel"] >= $routerConfig["user_admin_permission_level"]) { if (!empty($activationCode) && isUserAdmin()) {
$stmt = $mysqli->prepare("DELETE FROM Users WHERE ActivationToken = ?"); $stmt = $mysqli->prepare("DELETE FROM Users WHERE ActivationToken = ?");
$stmt->bind_param("s", $activationCode); $stmt->bind_param("s", $activationCode);
$stmt->execute(); $stmt->execute();
if ($stmt->affected_rows > 0) { if ($stmt->affected_rows > 0) {
$status["status"] = "success"; $status["Status"] = "Success";
} }
$stmt->close(); $stmt->close();
} }

@ -13,7 +13,7 @@ function runEndpoint($endpoint_file): ?array
function getEndpoint($endpoint_name): string function getEndpoint($endpoint_name): string
{ {
$output = array(); $output = array();
$output["status"] = "fail"; $output["Status"] = "Fail";
global $routerConfig; global $routerConfig;
global $routerRequest; global $routerRequest;

@ -39,20 +39,20 @@ function generateNavigation(): string
$navpages = ""; $navpages = "";
foreach ($pages_dir as $page_file) { foreach ($pages_dir as $page_file) {
$page_dir_tmp = explode(".", $page_file); $page_file_tmp = explode(".", $page_file);
$page_dir = $page_dir_tmp[0]; $page_basename = $page_file_tmp[0];
$page_class = "class=\"navpage_link\""; $page_class = "class=\"navpage_link\"";
if ($routerRequest["subdomain"] == $site_dir && $routerRequest["page_name"] == $page_dir) { if ($routerRequest["subdomain"] == $site_dir && $routerRequest["page_name"] == $page_basename) {
$page_class = "class=\"navpage_link active\""; $page_class = "class=\"navpage_link active\"";
} }
$page_location = $routerConfig["protocol"] . $site_subdomain . $routerRequest["domain"] . "." . $routerRequest["tld"] . "/" . $page_dir; $page_location = $routerConfig["protocol"] . $site_subdomain . $routerRequest["domain"] . "." . $routerRequest["tld"] . "/" . $page_basename;
$page_name = str_replace("_", " ", $page_dir); $page_name = str_replace("_", " ", $page_basename);
$page_name = explode(".", $page_name)[0]; $page_name = explode(".", $page_name)[0];
$page_name = ucfirst($page_name); $page_name = ucfirst($page_name);
$page_file_path = $routerConfig["page_dir"] . $site_dir . "/" . $page_file ; $page_file_path = $routerConfig["page_dir"] . $site_dir . "/" . $page_file ;
if($page_dir_tmp[1] == "html"){ if($page_file_tmp[1] == "html"){
$page_tmp = file_get_contents($page_file_path); $page_tmp = file_get_contents($page_file_path);
$pageMetadata = parsePageTag($page_tmp); $pageMetadata = parsePageTag($page_tmp);
@ -63,19 +63,19 @@ function generateNavigation(): string
$page_required_permission = $routerConfig["default_page_permission_level"]; $page_required_permission = $routerConfig["default_page_permission_level"];
} }
} }
elseif($page_dir_tmp[1] == "php"){ elseif($page_file_tmp[1] == "php"){
$page_required_permission = getDynamicPermission($page_file_path); $page_required_permission = getDynamicPermission($page_file_path);
} }
else{ else{
$page_required_permission = $routerConfig["default_page_permission_level"]; $page_required_permission = $routerConfig["default_page_permission_level"];
} }
if($page_required_permission <= $_SESSION["privilegelevel"]) { if($page_required_permission <= $_SESSION["privilege_level"]) {
$navpages .= "<li class='navpage_item'><a href='$page_location' $page_class>$page_name</a></li>"; $navpages .= "<li class='navpage_item' data-page='$page_basename'><a href='$page_location' $page_class>$page_name</a></li>";
} }
} }
if(!empty($navpages)){ if(!empty($navpages)){
$nav_out .= "<li class='navsite_item'><a href='$site_location' $site_class>$site_name</a><ul class='navpage_list'>$navpages</ul></li>"; $nav_out .= "<li class='navsite_item' data-site='$site_dir'><a href='$site_location' $site_class>$site_name</a><ul class='navpage_list'>$navpages</ul></li>";
} }
} }

@ -89,7 +89,7 @@ function getPage($page_name = null): array|false|string
} }
if($page_required_permission > $_SESSION["privilegelevel"]){ if($page_required_permission > $_SESSION["privilege_level"]){
if($is_secret_page == 1) { if($is_secret_page == 1) {
$page_tmp = file_get_contents($routerConfig["template_dir"] . "404.html"); $page_tmp = file_get_contents($routerConfig["template_dir"] . "404.html");
$pageMetadata = parsePageTag($page_tmp); $pageMetadata = parsePageTag($page_tmp);

@ -57,7 +57,7 @@ function initRouter(): bool
} }
else{ else{
if($_SERVER["REQUEST_METHOD"] == "POST"){ if($_SERVER["REQUEST_METHOD"] == "POST"){
$routerRequest["type"] = "api"; $routerRequest["type"] = "api";
} }
if(empty($routerRequest["type"])){ if(empty($routerRequest["type"])){
$routerRequest["type"] = "page"; $routerRequest["type"] = "page";

@ -1,10 +1,11 @@
<?php <?php
require_once "lib/router.php"; require_once "lib/router.php";
require_once "lib/account.php";
function get_parameters():array function get_parameters():array
{ {
return ["minimal_permission_level" => 1, "secret" => "no", "page_title" => "Domov"]; return ["minimal_permission_level" => 1, "secret" => "no", "page_title" => "Account"];
} }
function render(): string function render(): string
@ -13,12 +14,10 @@ function render(): string
ob_start(); ob_start();
if ($_SESSION["ID"] > 0) { if (isLoggedIn()) {
$account_template = file_get_contents($routerConfig["template_dir"] . "home.html"); echo file_get_contents($routerConfig["template_dir"] . "dashboard.html");
echo $account_template;
} else { } else {
$login_template = file_get_contents($routerConfig["template_dir"] . "login.html"); echo file_get_contents($routerConfig["template_dir"] . "login.html");
echo $login_template;
} }
return ob_get_clean(); return ob_get_clean();

24
pages/home/settings.php Normal file

@ -0,0 +1,24 @@
<?php
require_once "lib/router.php";
require_once "lib/account.php";
function get_parameters():array
{
return ["minimal_permission_level" => 2, "secret" => "no", "page_title" => "Settings"];
}
function render(): string
{
global $routerConfig;
ob_start();
if (isUserAdmin()) {
echo file_get_contents($routerConfig["template_dir"] . "adminActions.html");
} else {
echo file_get_contents($routerConfig["template_dir"] . "userActions.html");
}
return ob_get_clean();
}

124
templates/adminActions.html Normal file

@ -0,0 +1,124 @@
<script>
function addActivationCodes() {
const count = document.getElementById("activationCodeCount").value;
const data = new URLSearchParams();
data.append("action", "add_activation_codes");
data.append("count", count);
doAction(data, "Activation codes added Successfully!", "Activation codes addition failed.");
}
async function listUsers() {
const data = new URLSearchParams();
data.append("action", "list_users");
const result = await doAction(data, "User list retrieved Successfully!", "User list retrieval failed.");
if (result && result.Status === "Success") {
displayUserList(result.Users);
}
}
function displayUserList(users) {
const tableContainer = document.getElementById("userListTable");
tableContainer.innerHTML = ""; // Clear previous content
const table = document.createElement("table");
table.border = "1";
// Create header row
const headerRow = table.insertRow(0);
for (const key in users[0]) {
const th = document.createElement("th");
th.appendChild(document.createTextNode(key));
headerRow.appendChild(th);
}
// Create data rows
for (const user of users) {
const dataRow = table.insertRow();
for (const key in user) {
const td = document.createElement("td");
td.appendChild(document.createTextNode(user[key]));
dataRow.appendChild(td);
}
}
tableContainer.appendChild(table);
}
function listActivationCodes() {
const data = new URLSearchParams();
data.append("action", "list_activation_codes");
doAction(data, "Activation code list retrieved Successfully!", "Activation code list retrieval failed.");
}
function deleteUser() {
const userId = document.getElementById("userId").value;
const data = new URLSearchParams();
data.append("action", "delete_user");
data.append("user_id", userId);
doAction(data, "User deleted Successfully!", "User deletion failed.");
}
function deleteActivationCode() {
const activationCode = document.getElementById("activationCode").value;
const data = new URLSearchParams();
data.append("action", "delete_activation_code");
data.append("activation_code", activationCode);
doAction(data, "Activation code deleted Successfully!", "Activation code deletion failed.");
}
</script>
<div class="form-container" id="addActivationCodesForm">
<h1>Add Activation Codes</h1>
<form>
<label for="activationCodeCount">Activation Code Count:</label>
<input type="text" id="activationCodeCount" name="activationCodeCount" required>
<button type="button" onclick="addActivationCodes()">Add Activation Codes</button>
</form>
</div>
<div class="form-container" id="listUsersForm">
<h1>List Users</h1>
<form>
<button type="button" onclick="listUsers()">List Users</button>
</form>
</div>
<div class="form-container" id="listActivationCodesForm">
<h1>List Activation Codes</h1>
<form>
<button type="button" onclick="listActivationCodes()">List Activation Codes</button>
</form>
</div>
<div class="form-container" id="deleteUserForm">
<h1>Delete User</h1>
<form>
<label for="userId">User ID:</label>
<input type="text" id="userId" name="userId" required>
<button type="button" onclick="deleteUser()">Delete User</button>
</form>
</div>
<div class="form-container" id="deleteActivationCodeForm">
<h1>Delete Activation Code</h1>
<form>
<label for="activationCode">Activation Code:</label>
<input type="text" id="activationCode" name="activationCode" required>
<button type="button" onclick="deleteActivationCode()">Delete Activation Code</button>
</form>
</div>
<!-- Centralized Status Message -->
<p id="StatusMessage"></p>

@ -1,13 +1,32 @@
<div class="login-container"> <script>
function login() {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
doLogin(email, password);
}
function doLogin(email, password) {
const data = new URLSearchParams();
data.append("action", "login");
data.append("email", email);
data.append("password", password);
doAction(data, "Login Successful!", "Login failed. Please check your credentials.");
}
</script>
<div class="form-container" id="loginForm">
<h1>Login</h1> <h1>Login</h1>
<form id="loginForm"> <form>
<label for="email">Email:</label> <label for="email">Email:</label>
<input type="email" id="email" name="email" required> <input type="text" id="email" name="email" required>
<label for="password">Password:</label> <label for="password">Password:</label>
<input type="password" id="password" name="password" required> <input type="password" id="password" name="password" required>
<button type="button" onclick="login()">Login</button> <button type="button" onclick="login()">Login</button>
</form> </form>
<p id="statusMessage"></p>
</div> </div>
<!-- Centralized Status Message -->
<p id="StatusMessage"></p>

58
templates/register.html Normal file

@ -0,0 +1,58 @@
<script>
function register() {
const firstName = document.getElementById("firstName").value;
const lastName = document.getElementById("lastName").value;
const nickname = document.getElementById("nickname").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
const minecraftNick = document.getElementById("minecraftNick").value;
const activationToken = document.getElementById("activationToken").value;
const data = new URLSearchParams();
data.append("action", "register");
data.append("firstname", firstName);
data.append("lastname", lastName);
data.append("nickname", nickname);
data.append("email", email);
data.append("password", password);
data.append("minecraftnick", minecraftNick);
data.append("activation_token", activationToken);
doRegister(data);
}
function doRegister(requestData) {
doAction(requestData, "Registration Successful!", "Registration failed.");
}
</script>
<div class="form-container" id="registerForm">
<h1>Register</h1>
<form>
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required>
<label for="nickname">Nickname:</label>
<input type="text" id="nickname" name="nickname" required>
<label for="email">Email:</label>
<input type="text" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="minecraftNick">Minecraft Nick:</label>
<input type="text" id="minecraftNick" name="minecraftNick" required>
<label for="activationToken">Activation Token:</label>
<input type="text" id="activationToken" name="activationToken" required>
<button type="button" onclick="register()">Register</button>
</form>
</div>
<!-- Centralized Status Message -->
<p id="StatusMessage"></p>

128
templates/userActions.html Normal file

@ -0,0 +1,128 @@
<script>
function changePassword() {
const userId = document.getElementById("changeUserId").value;
const newPassword = document.getElementById("changeNewPassword").value;
const data = new URLSearchParams();
data.append("action", "change_password");
data.append("user_id", userId);
data.append("new_password", newPassword);
doChangePassword(data, "Password change Successful!", "Password change failed.");
}
function doChangePassword(requestData, successMessage, failureMessage) {
doAction(requestData, successMessage, failureMessage);
}
function updateUserProfile() {
const userId = document.getElementById("updateUserIdProfile").value;
const firstName = document.getElementById("updateFirstName").value;
const lastName = document.getElementById("updateLastName").value;
const nickname = document.getElementById("updateNickname").value;
const minecraftNick = document.getElementById("updateMinecraftNick").value;
const data = new URLSearchParams();
data.append("action", "update_user_profile");
data.append("user_id", userId);
data.append("first_name", firstName);
data.append("last_name", lastName);
data.append("nickname", nickname);
data.append("minecraft_nick", minecraftNick);
doAction(data, "Profile update Successful!", "Profile update failed.");
}
async function getUserInfo() {
const userId = document.getElementById("getUserInfoId").value;
const data = new URLSearchParams();
data.append("action", "get_user_info");
data.append("user_id", userId);
const result = await doAction(data, "User info retrieved Successfully!", "User info retrieval failed.");
if (result && result.Status === "Success") {
displayUserInfo(result);
}
}
function displayUserInfo(userData) {
const tableContainer = document.getElementById("userInfoTable");
tableContainer.innerHTML = ""; // Clear previous content
const table = document.createElement("table");
table.border = "1";
const headerRow = table.insertRow(0);
for (const key in userData) {
const th = document.createElement("th");
th.appendChild(document.createTextNode(key));
headerRow.appendChild(th);
}
const dataRow = table.insertRow(1);
for (const key in userData) {
const td = document.createElement("td");
td.appendChild(document.createTextNode(userData[key]));
dataRow.appendChild(td);
}
tableContainer.appendChild(table);
}
</script>
<div class="form-container" id="changePasswordForm">
<h1>Change Password</h1>
<form>
<label for="changeUserId">User ID:</label>
<input type="text" id="changeUserId" name="changeUserId" required>
<label for="changeOldPassword">Old Password:</label>
<input type="password" id="changeOldPassword" name="changeOldPassword" required>
<label for="changeNewPassword">New Password:</label>
<input type="password" id="changeNewPassword" name="changeNewPassword" required>
<button type="button" onclick="changePassword()">Change Password</button>
</form>
</div>
<div class="form-container" id="updateUserProfileForm">
<h1>Update User Profile</h1>
<form>
<label for="updateUserIdProfile">User ID:</label>
<input type="text" id="updateUserIdProfile" name="updateUserIdProfile" required>
<label for="updateFirstName">First Name:</label>
<input type="text" id="updateFirstName" name="updateFirstName" required>
<label for="updateLastName">Last Name:</label>
<input type="text" id="updateLastName" name="updateLastName" required>
<label for="updateNickname">Nickname:</label>
<input type="text" id="updateNickname" name="updateNickname" required>
<label for="updateMinecraftNick">Minecraft Nick:</label>
<input type="text" id="updateMinecraftNick" name="updateMinecraftNick" required>
<button type="button" onclick="updateUserProfile()">Update Profile</button>
</form>
</div>
<div class="form-container" id="getUserInfoForm">
<h1>Get User Info</h1>
<form>
<label for="getUserInfoId">User ID:</label>
<input type="text" id="getUserInfoId" name="getUserInfoId" required>
<button type="button" onclick="getUserInfo()">Get User Info</button>
</form>
</div>
<button type="button" onclick="logout()">Logout</button>
<!-- Include other user action forms similarly -->
<!-- Centralized Status Message -->
<p id="StatusMessage"></p>