Merge pull request #13 from tips-of-mine/feat/toggle-user-role

Feat/toggle user role
This commit is contained in:
tips-of-mine
2025-06-15 20:37:34 +02:00
committed by GitHub
14 changed files with 200 additions and 3 deletions

View File

@ -215,6 +215,7 @@ $router->addRoute('GET', '/users', 'UserController@index', true);
$router->addRoute('GET', '/users/create', 'UserController@showCreateForm', true);
$router->addRoute('POST', '/users/create', 'UserController@create', true);
$router->addRoute('POST', '/users/delete', 'UserController@delete', true);
$router->addRoute('POST', '/users/toggle-admin', 'UserController@toggleAdminRole', true);
$router->addRoute('GET', '/logout', 'AuthController@logout', true);
// Exécuter le routage

View File

@ -7,6 +7,7 @@ use App\Services\AuthService;
use App\Services\LogService;
use App\Services\LanguageService;
use App\Utils\DarkMode;
use \PDOException;
/**
* Contrôleur pour la gestion des utilisateurs.
@ -210,4 +211,76 @@ class UserController
header('Location: /users');
exit();
}
/**
* Modifie le rôle d'un utilisateur (admin/user).
*/
public function toggleAdminRole()
{
$this->requireAdmin();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: /users');
exit();
}
$userIdToModify = $_POST['user_id'] ?? null;
$ipAddress = $_SERVER['REMOTE_ADDR'];
$adminUserId = $this->authService->getUserId();
if (empty($userIdToModify)) {
$_SESSION['error'] = $this->langService->__('user_role_error_id_missing'); // Nouvelle chaîne de langue
header('Location: /users');
exit();
}
// Récupérer les informations de l'utilisateur à modifier
$stmt = $this->db->prepare("SELECT username, role FROM users WHERE id = ?");
$stmt->execute([$userIdToModify]);
$userToModify = $stmt->fetch();
if (!$userToModify) {
$_SESSION['error'] = $this->langService->__('user_not_found'); // Nouvelle chaîne de langue (ou existante)
header('Location: /users');
exit();
}
// Empêcher la modification du rôle de l'utilisateur "admin" (ou un nom spécifique)
// ou de son propre rôle si c'est l'admin connecté
if ($userToModify['username'] === 'admin' || $userIdToModify == $adminUserId) {
$_SESSION['error'] = $this->langService->__('cannot_change_admin_role'); // Nouvelle chaîne de langue
$this->logService->log('warning', "Tentative de modification du rôle de l'administrateur principal ou de soi-même par l'admin ID: {$adminUserId}.", $adminUserId, $ipAddress);
header('Location: /users');
exit();
}
$newRole = ($userToModify['role'] === 'admin') ? 'user' : 'admin';
// Si on retire le rôle admin, vérifier qu'il en reste au moins un autre
if ($newRole === 'user' && $userToModify['role'] === 'admin') {
$stmt = $this->db->query("SELECT COUNT(*) FROM users WHERE role = 'admin'");
$adminCount = $stmt->fetchColumn();
if ($adminCount <= 1) {
$_SESSION['error'] = $this->langService->__('cannot_remove_last_admin_role'); // Nouvelle chaîne de langue
$this->logService->log('warning', "Tentative de suppression du dernier rôle admin par l'admin ID: {$adminUserId}.", $adminUserId, $ipAddress);
header('Location: /users');
exit();
}
}
try {
$stmt = $this->db->prepare("UPDATE users SET role = ? WHERE id = ?");
$stmt->execute([$newRole, $userIdToModify]);
$this->logService->log('info', "Rôle de l'utilisateur '{$userToModify['username']}' (ID: {$userIdToModify}) changé en '{$newRole}' par l'administrateur ID: {$adminUserId}.", $adminUserId, $ipAddress);
$_SESSION['success'] = $this->langService->__('user_role_updated_success', ['username' => htmlspecialchars($userToModify['username']), 'role' => htmlspecialchars($newRole)]); // Nouvelle chaîne de langue
} catch (\PDOException $e) {
error_log("Erreur lors du changement de rôle de l'utilisateur: " . $e->getMessage());
$_SESSION['error'] = $this->langService->__('user_role_update_error_db'); // Nouvelle chaîne de langue
$this->logService->log('error', "Échec changement de rôle pour utilisateur ID: {$userIdToModify}: " . $e->getMessage(), $adminUserId, $ipAddress);
}
header('Location: /users');
exit();
}
}

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Auto-translated 'User not found for deletion.' to Arabic",
"user_delete_error_db": "Auto-translated 'Error deleting user from the database.' to Arabic",
"self_delete_not_allowed": "Auto-translated 'You cannot delete yourself.' to Arabic",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Benutzer zum Löschen nicht gefunden.",
"user_delete_error_db": "Fehler beim Löschen des Benutzers aus der Datenbank.",
"self_delete_not_allowed": "Sie können sich nicht selbst löschen.",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "User not found for deletion.",
"user_delete_error_db": "Error deleting user from the database.",
"self_delete_not_allowed": "You cannot delete yourself.",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Usuario no encontrado para la eliminación.",
"user_delete_error_db": "Error al eliminar el usuario de la base de datos.",
"self_delete_not_allowed": "No puedes eliminarte a ti mismo.",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Utilisateur introuvable pour la suppression.",
"user_delete_error_db": "Erreur lors de la suppression de l'utilisateur dans la base de données.",
"self_delete_not_allowed": "Vous ne pouvez pas vous supprimer vous-même.",
"user_role_error_id_missing": "ID utilisateur manquant pour la modification du rôle.",
"user_not_found": "Utilisateur non trouvé.",
"cannot_change_admin_role": "Le rôle de l'administrateur principal ou son propre rôle ne peut être modifié.",
"cannot_remove_last_admin_role": "Impossible de retirer le statut d'administrateur au dernier administrateur.",
"user_role_updated_success": "Le rôle de l'utilisateur '{username}' a été changé en '{role}' avec succès.",
"user_role_update_error_db": "Erreur de base de données lors de la mise à jour du rôle de l'utilisateur.",
"confirm_toggle_admin_role": "Êtes-vous sûr de vouloir modifier le rôle de cet utilisateur ?",
"remove_admin_status": "Retirer Admin",
"pass_to_admin": "Passer Admin",
"cannot_change_main_admin_role": "Rôle non modifiable"
"cert_revoke_success_intermediate": "Le certificat intermédiaire '{name}' a été révoqué avec succès et la CRL du CA Racine a été mise à jour.",
"cert_revoke_warn_crl_update_failed_intermediate": "Le certificat intermédiaire '{name}' a été révoqué, mais la mise à jour de la CRL du CA Racine a rencontré un problème. Veuillez contacter un administrateur.",
"cert_revoke_error_intermediate": "Erreur lors de la révocation du certificat intermédiaire '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Auto-translated 'User not found for deletion.' to Hindi",
"user_delete_error_db": "Auto-translated 'Error deleting user from the database.' to Hindi",
"self_delete_not_allowed": "Auto-translated 'You cannot delete yourself.' to Hindi",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Utente non trovato per l'eliminazione.",
"user_delete_error_db": "Errore durante l'eliminazione dell'utente dal database.",
"self_delete_not_allowed": "Non puoi eliminare te stesso.",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Auto-translated 'User not found for deletion.' to Japanese",
"user_delete_error_db": "Auto-translated 'Error deleting user from the database.' to Japanese",
"self_delete_not_allowed": "Auto-translated 'You cannot delete yourself.' to Japanese",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Utilizador não encontrado para eliminação.",
"user_delete_error_db": "Erro ao eliminar utilizador da base de dados.",
"self_delete_not_allowed": "Não pode eliminar-se a si mesmo.",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Auto-translated 'User not found for deletion.' to Russian",
"user_delete_error_db": "Auto-translated 'Error deleting user from the database.' to Russian",
"self_delete_not_allowed": "Auto-translated 'You cannot delete yourself.' to Russian",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -81,6 +81,16 @@
"user_delete_error_not_found": "Auto-translated 'User not found for deletion.' to Chinese",
"user_delete_error_db": "Auto-translated 'Error deleting user from the database.' to Chinese",
"self_delete_not_allowed": "Auto-translated 'You cannot delete yourself.' to Chinese",
"user_role_error_id_missing": "User ID missing for role modification.",
"user_not_found": "User not found.",
"cannot_change_admin_role": "The main administrator's role or your own role cannot be modified.",
"cannot_remove_last_admin_role": "Cannot remove administrator status from the last administrator.",
"user_role_updated_success": "User '{username}' role has been successfully changed to '{role}'.",
"user_role_update_error_db": "Database error while updating user role.",
"confirm_toggle_admin_role": "Are you sure you want to modify this user's role?",
"remove_admin_status": "Remove Admin",
"pass_to_admin": "Make Admin",
"cannot_change_main_admin_role": "Role not modifiable"
"cert_revoke_success_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been successfully revoked and the Root CA CRL has been updated.",
"cert_revoke_warn_crl_update_failed_intermediate": "NEEDS TRANSLATION: Intermediate certificate '{name}' has been revoked, but updating the Root CA CRL encountered an issue. Please contact an administrator.",
"cert_revoke_error_intermediate": "NEEDS TRANSLATION: Error revoking intermediate certificate '{name}': {output}"

View File

@ -36,13 +36,26 @@ require_once APP_ROOT_DIR . '/src/Views/shared/header.php';
<td><?= htmlspecialchars($user['username']) ?></td>
<td><?= htmlspecialchars($translations[$user['role']] ?? $user['role']) ?></td>
<td><?= htmlspecialchars((new DateTime($user['created_at']))->format('Y-m-d H:i:s')) ?></td>
<td>
<?php if ($user['id'] !== $authService->getUserId()): // Impossible de supprimer son propre compte ?>
<td class="actions-cell"> <!-- Ajout d'une classe pour styliser si besoin -->
<?php if ($user['username'] !== 'admin' && $user['id'] !== $authService->getUserId()): ?>
<form action="/users/toggle-admin" method="post" class="inline-form" onsubmit="return confirm('<?= htmlspecialchars($translations['confirm_toggle_admin_role'] ?? 'Êtes-vous sûr de vouloir modifier le rôle de cet utilisateur ?') ?>');">
<input type="hidden" name="user_id" value="<?= htmlspecialchars($user['id']) ?>">
<?php if ($user['role'] === 'admin'): ?>
<button type="submit" class="button warning-button"><?= htmlspecialchars($translations['remove_admin_status'] ?? 'Retirer Admin') ?></button>
<?php else: ?>
<button type="submit" class="button primary-button"><?= htmlspecialchars($translations['pass_to_admin'] ?? 'Passer Admin') ?></button>
<?php endif; ?>
</form>
<?php elseif ($user['username'] === 'admin'): ?>
<em><?= htmlspecialchars($translations['cannot_change_main_admin_role'] ?? 'Rôle non modifiable') ?></em>
<?php endif; ?>
<?php if ($user['id'] !== $authService->getUserId() && $user['username'] !== 'admin'): // Condition existante pour la suppression, légèrement ajustée pour être sûr que 'admin' n'est pas supprimable non plus via cette interface ?>
<form action="/users/delete" method="post" class="inline-form" onsubmit="return confirm('<?= htmlspecialchars($translations['confirm_delete_user']) ?>');">
<input type="hidden" name="user_id" value="<?= htmlspecialchars($user['id']) ?>">
<button type="submit" class="button danger-button"><?= htmlspecialchars($translations['delete_user']) ?></button>
</form>
<?php else: ?>
<?php elseif ($user['id'] === $authService->getUserId() && $user['username'] !== 'admin'): // Permet à l'admin de voir "non modifiable" pour lui meme, mais pas "auto suppression interdite" si c'est admin ?>
<em><?= htmlspecialchars($translations['self_delete_not_allowed']) ?></em>
<?php endif; ?>
</td>