Portfolio_pero/admin/security.php
2026-09-03 13:27:06 +02:00

339 lines
16 KiB
PHP

<?php
/**
* BackOffice - securite et gestion des admins.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/database.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
$db = getDatabase();
$feedback = '';
$feedbackType = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$action = (string) ($_POST['action'] ?? '');
if ($action === 'change_password') {
$current = (string) ($_POST['current_password'] ?? '');
$new = (string) ($_POST['new_password'] ?? '');
$confirm = (string) ($_POST['confirm_password'] ?? '');
if ($current === '' || $new === '' || $confirm === '') {
$feedback = 'Tous les champs sont requis.';
$feedbackType = 'error';
} elseif ($new !== $confirm) {
$feedback = 'Les nouveaux mots de passe ne correspondent pas.';
$feedbackType = 'error';
} elseif (strlen($new) < 12 || !preg_match('/[A-Z]/', $new) || !preg_match('/[a-z]/', $new) || !preg_match('/\d/', $new)) {
$feedback = 'Le mot de passe doit contenir au moins 12 caracteres, une majuscule, une minuscule et un chiffre.';
$feedbackType = 'error';
} else {
$stmt = $db->prepare('SELECT password_hash FROM admins WHERE id = :id');
$stmt->execute(['id' => $_SESSION['admin_id']]);
$hash = (string) $stmt->fetchColumn();
if ($hash === '' || !password_verify($current, $hash)) {
$feedback = 'Mot de passe actuel incorrect.';
$feedbackType = 'error';
} else {
$newHash = password_hash($new, PASSWORD_DEFAULT);
$db->prepare('UPDATE admins SET password_hash = :hash WHERE id = :id')
->execute([
'hash' => $newHash,
'id' => $_SESSION['admin_id'],
]);
$db->prepare(
'INSERT INTO admin_logs (admin_id, username, action, ip, success)
VALUES (:admin_id, :username, :action, :ip, 1)'
)->execute([
'admin_id' => $_SESSION['admin_id'],
'username' => $_SESSION['admin_username'],
'action' => 'change_password',
'ip' => Security::clientIp(),
]);
$feedback = 'Mot de passe modifie avec succes.';
$feedbackType = 'success';
}
}
} elseif ($action === 'create_admin') {
$username = trim((string) ($_POST['new_username'] ?? ''));
$password = (string) ($_POST['new_admin_password'] ?? '');
if (!preg_match('/^[a-zA-Z0-9._-]{3,50}$/', $username)) {
$feedback = 'Identifiant invalide. Utilisez 3 a 50 caracteres alphanumeriques.';
$feedbackType = 'error';
} elseif (strlen($password) < 12 || !preg_match('/[A-Z]/', $password) || !preg_match('/[a-z]/', $password) || !preg_match('/\d/', $password)) {
$feedback = 'Le mot de passe doit contenir au moins 12 caracteres, une majuscule, une minuscule et un chiffre.';
$feedbackType = 'error';
} else {
try {
$db->prepare('INSERT INTO admins (username, password_hash) VALUES (:username, :hash)')
->execute([
'username' => $username,
'hash' => password_hash($password, PASSWORD_DEFAULT),
]);
$db->prepare(
'INSERT INTO admin_logs (admin_id, username, action, detail, ip, success)
VALUES (:admin_id, :username, :action, :detail, :ip, 1)'
)->execute([
'admin_id' => $_SESSION['admin_id'],
'username' => $_SESSION['admin_username'],
'action' => 'create_admin',
'detail' => 'Cree : ' . $username,
'ip' => Security::clientIp(),
]);
$feedback = 'Compte admin cree avec succes.';
$feedbackType = 'success';
} catch (PDOException) {
$feedback = 'Cet identifiant existe deja.';
$feedbackType = 'error';
}
}
} elseif ($action === 'delete_admin') {
$adminId = (int) ($_POST['admin_id'] ?? 0);
if ($adminId === (int) $_SESSION['admin_id']) {
$feedback = 'Vous ne pouvez pas supprimer votre propre compte.';
$feedbackType = 'error';
} elseif ($adminId > 0) {
$db->prepare('DELETE FROM admins WHERE id = :id')->execute(['id' => $adminId]);
$feedback = 'Compte admin supprime.';
$feedbackType = 'success';
}
} elseif ($action === 'purge_logs') {
$db->exec('DELETE FROM admin_logs WHERE created_at < NOW() - INTERVAL 90 DAY');
$db->exec('DELETE FROM login_attempts WHERE created_at < NOW() - INTERVAL 7 DAY');
$feedback = 'Logs anciens purges.';
$feedbackType = 'success';
} elseif ($action === 'unblock_ip') {
$ip = trim((string) ($_POST['ip'] ?? ''));
if ($ip !== '') {
$db->prepare('DELETE FROM login_attempts WHERE ip = :ip')->execute(['ip' => $ip]);
$feedback = 'IP debloquee.';
$feedbackType = 'success';
}
}
}
$admins = $db->query('SELECT id, username, created_at FROM admins ORDER BY created_at ASC')->fetchAll();
$logs = $db->query(
'SELECT * FROM admin_logs ORDER BY created_at DESC LIMIT 50'
)->fetchAll();
$blockedIps = $db->query(
"SELECT ip, COUNT(*) AS attempts, MAX(created_at) AS last_attempt
FROM login_attempts
WHERE created_at > NOW() - INTERVAL 15 MINUTE
GROUP BY ip
HAVING attempts >= 5
ORDER BY attempts DESC"
)->fetchAll();
$totalAttempts = (int) $db->query(
'SELECT COUNT(*) FROM login_attempts WHERE created_at > NOW() - INTERVAL 24 HOUR'
)->fetchColumn();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Securite - BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Securite et admins</h1>
</div>
<?php if ($feedback !== ''): ?>
<div class="admin-alert admin-alert--<?= $feedbackType ?>"><?= Security::e($feedback) ?></div>
<?php endif; ?>
<div class="security-grid">
<div class="admin-form">
<h2 class="form-section-title">Changer mon mot de passe</h2>
<form method="post">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="change_password">
<div class="admin-form__group">
<label class="admin-form__label" for="current_password">Mot de passe actuel</label>
<input type="password" id="current_password" name="current_password" class="admin-form__input" required autocomplete="current-password">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="new_password">Nouveau mot de passe</label>
<input type="password" id="new_password" name="new_password" class="admin-form__input" required minlength="12" autocomplete="new-password">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="confirm_password">Confirmer le nouveau mot de passe</label>
<input type="password" id="confirm_password" name="confirm_password" class="admin-form__input" required minlength="12" autocomplete="new-password">
</div>
<div class="admin-form__actions">
<button type="submit" class="admin-btn admin-btn--primary">Modifier le mot de passe</button>
</div>
</form>
</div>
<div class="admin-form">
<h2 class="form-section-title">Creer un compte admin</h2>
<form method="post">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="create_admin">
<div class="admin-form__group">
<label class="admin-form__label" for="new_username">Identifiant</label>
<input type="text" id="new_username" name="new_username" class="admin-form__input" required maxlength="50" autocomplete="off">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="new_admin_password">Mot de passe</label>
<input type="password" id="new_admin_password" name="new_admin_password" class="admin-form__input" required minlength="12" autocomplete="new-password">
</div>
<div class="admin-form__actions">
<button type="submit" class="admin-btn admin-btn--primary">Creer le compte</button>
</div>
</form>
</div>
<div class="admin-form" style="grid-column:1/-1;">
<h2 class="form-section-title">Comptes administrateurs</h2>
<table class="admin-table" style="margin-top:1rem;">
<thead>
<tr><th>ID</th><th>Identifiant</th><th>Cree le</th><th>Action</th></tr>
</thead>
<tbody>
<?php foreach ($admins as $admin): ?>
<tr>
<td><?= (int) $admin['id'] ?></td>
<td>
<strong><?= Security::e($admin['username']) ?></strong>
<?php if ((int) $admin['id'] === (int) $_SESSION['admin_id']): ?>
<span class="admin-badge admin-badge--published" style="margin-left:0.5rem;">Vous</span>
<?php endif; ?>
</td>
<td><?= date('d/m/Y', strtotime($admin['created_at'])) ?></td>
<td>
<?php if ((int) $admin['id'] !== (int) $_SESSION['admin_id']): ?>
<form method="post" style="display:inline;" data-confirm-message="Supprimer cet admin ?">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="delete_admin">
<input type="hidden" name="admin_id" value="<?= (int) $admin['id'] ?>">
<button type="submit" class="admin-btn admin-btn--danger admin-btn--sm">Supprimer</button>
</form>
<?php else: ?>
<span style="color:var(--admin-text-secondary);font-size:0.8125rem;">-</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="admin-form" style="grid-column:1/-1;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;flex-wrap:wrap;gap:0.75rem;">
<h2 class="form-section-title" style="margin:0;">IPs bloquees</h2>
<span style="font-size:0.8125rem;color:var(--admin-text-secondary);">
<?= $totalAttempts ?> tentative(s) sur 24h
</span>
</div>
<?php if (empty($blockedIps)): ?>
<p style="color:var(--admin-text-secondary);font-size:0.875rem;">Aucune IP bloquee en ce moment.</p>
<?php else: ?>
<table class="admin-table">
<thead>
<tr><th>IP</th><th>Tentatives</th><th>Derniere tentative</th><th>Action</th></tr>
</thead>
<tbody>
<?php foreach ($blockedIps as $blockedIp): ?>
<tr>
<td><code><?= Security::e($blockedIp['ip']) ?></code></td>
<td><strong><?= (int) $blockedIp['attempts'] ?></strong></td>
<td><?= date('d/m/Y H:i:s', strtotime($blockedIp['last_attempt'])) ?></td>
<td>
<form method="post" style="display:inline;">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="unblock_ip">
<input type="hidden" name="ip" value="<?= Security::e($blockedIp['ip']) ?>">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Debloquer</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<div class="admin-form" style="grid-column:1/-1;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;flex-wrap:wrap;gap:0.75rem;">
<h2 class="form-section-title" style="margin:0;">Logs d'activite</h2>
<form method="post" data-confirm-message="Purger les logs de plus de 90 jours ?">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="purge_logs">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Purger les anciens logs</button>
</form>
</div>
<?php if (empty($logs)): ?>
<p style="color:var(--admin-text-secondary);font-size:0.875rem;">Aucun log disponible.</p>
<?php else: ?>
<table class="admin-table">
<thead>
<tr><th>Date</th><th>Admin</th><th>Action</th><th>Detail</th><th>IP</th><th>Statut</th></tr>
</thead>
<tbody>
<?php foreach ($logs as $log): ?>
<tr>
<td style="white-space:nowrap;"><?= date('d/m/Y H:i', strtotime($log['created_at'])) ?></td>
<td><?= Security::e((string) ($log['username'] ?? '-')) ?></td>
<td><code style="font-size:0.8rem;"><?= Security::e((string) $log['action']) ?></code></td>
<td style="color:var(--admin-text-secondary);font-size:0.8125rem;"><?= Security::e((string) ($log['detail'] ?? '-')) ?></td>
<td style="font-size:0.8rem;"><code><?= Security::e((string) ($log['ip'] ?? '-')) ?></code></td>
<td>
<?php if (!empty($log['success'])): ?>
<span class="admin-badge admin-badge--published">OK</span>
<?php else: ?>
<span class="admin-badge" style="background:rgba(239,68,68,0.1);color:var(--admin-red);">Echec</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
</main>
</div>
<script nonce="<?= Security::cspNonce() ?>">
document.querySelectorAll('form[data-confirm-message]').forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!window.confirm(form.dataset.confirmMessage || 'Confirmer cette action ?')) {
event.preventDefault();
}
});
});
</script>
</body>
</html>