AddUserAction.class.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. class AddUserAction implements IAction {
  3. public function execute() {
  4. if(!Authorize::isLoggedIn() || !Authorize::hasPermission()) {
  5. return array("error" => "Access not authorized");
  6. }
  7. $username = $_POST['username'] ?? $_GET['username'] ?? "";
  8. $displayName = $_POST['display_name'] ?? $_GET['display_name'] ?? "";
  9. $email = $_POST['email'] ?? $_GET['email'] ?? "";
  10. $password = $_POST['password'] ?? $_GET['password'] ?? "";
  11. //TODO: scrub inputs
  12. if(empty($username) || empty($displayName) || empty($password)) {
  13. return array("error" => "One or more required fields missing: username, display_name, password, email");
  14. }
  15. $passwordHash = hash("sha256", $password);
  16. $sql = "INSERT INTO users (username, password, display_name, email)
  17. VALUES
  18. (:username, :passwordhash, :display_name, :email);";
  19. $db = SqliteDatabase::getSingleton();
  20. $preparedQuery = $db->prepare($sql);
  21. $preparedQuery->bindValue(':username', $username);
  22. $preparedQuery->bindValue(':passwordhash', $passwordHash);
  23. $preparedQuery->bindValue(':display_name', $displayName);
  24. $preparedQuery->bindValue(':email', $email);
  25. try {
  26. $result = $preparedQuery->execute();
  27. $loggerData = array();
  28. $loggerData['user_added'] = $username;
  29. $loggerData['admin_display_name'] = $_SESSION['display_name'];
  30. $loggerData['admin_user_id'] = $_SESSION['user_id'];
  31. SecurityLogger::action("add-user", $loggerData, time());
  32. return array("status" => "success", "message" => "Added new user '" . $username . "'.");
  33. }
  34. catch(Exception $e) {
  35. return array("error" => "Error when adding user '" . $username. "': possibly duplicate?" , "exception" => $e->getMessage());
  36. }
  37. }
  38. }