From d57f0a76266010c83212e1765a8248ef8cf8d0df Mon Sep 17 00:00:00 2001 From: Ryan Date: Sat, 22 Feb 2025 11:57:10 -0500 Subject: [PATCH] prevent remove self --- removeUser.php | 64 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/removeUser.php b/removeUser.php index fd30fbc..663742e 100644 --- a/removeUser.php +++ b/removeUser.php @@ -1 +1,63 @@ -{"error":"Unauthorized"} \ No newline at end of file + "Unauthorized"]); + exit; +} + +// Get input data from JSON +$data = json_decode(file_get_contents("php://input"), true); +$usernameToRemove = trim($data["username"] ?? ""); + +if (!$usernameToRemove) { + echo json_encode(["error" => "Username is required"]); + exit; +} + +// Prevent removal of the currently logged-in user +if (isset($_SESSION['username']) && $_SESSION['username'] === $usernameToRemove) { + echo json_encode(["error" => "Cannot remove yourself"]); + exit; +} + +// Read existing users from the file +if (!file_exists($usersFile)) { + echo json_encode(["error" => "Users file not found"]); + exit; +} + +$existingUsers = file($usersFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); +$newUsers = []; +$userFound = false; + +// Remove the user with the specified username +foreach ($existingUsers as $line) { + $parts = explode(':', trim($line)); + if (count($parts) < 3) { + continue; + } + $storedUser = $parts[0]; + if ($storedUser === $usernameToRemove) { + $userFound = true; + continue; // Skip this user + } + $newUsers[] = $line; +} + +if (!$userFound) { + echo json_encode(["error" => "User not found"]); + exit; +} + +// Write the updated list back to users.txt +file_put_contents($usersFile, implode(PHP_EOL, $newUsers) . PHP_EOL); +echo json_encode(["success" => "User removed successfully"]); +?>