Actualiser api.php

This commit is contained in:
2026-06-18 12:30:57 +02:00
parent c6b80495ea
commit 728312cbc2
+95 -134
View File
@@ -1,156 +1,117 @@
/** <?php
* Mon Cinéma - Module d'Administration (admin.js) header("Content-Type: application/json; charset=UTF-8");
* Version synchronisée avec api.php header("Access-Control-Allow-Origin: *");
*/ header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
const API_URL = '../api.php'; if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
let allItems = []; http_response_code(200);
let currentAdminTab = 'critique'; exit;
// ── INITIALISATION ──
document.addEventListener('DOMContentLoaded', loadDashboardData);
async function loadDashboardData() {
try {
const res = await fetch(`${API_URL}?action=get_films`);
allItems = await res.json();
const secRes = await fetch(`${API_URL}?action=check_security_status`);
const secData = await secRes.json();
const banner = document.getElementById('security-banner');
if (banner) banner.style.display = secData.is_blank ? 'flex' : 'none';
renderAdminTable();
} catch (err) { console.error('Erreur chargement :', err); }
} }
function renderAdminTable() { define('ENCRYPTION_KEY', 'MaCleSecreteSuperRobuste123!');
const tbody = document.getElementById('admin-table-body');
if (!tbody) return;
tbody.innerHTML = '';
const filtered = allItems.filter(item => item.type === currentAdminTab);
document.getElementById('admin-count-label').textContent = `${filtered.length} élément(s)`;
filtered.forEach(f => { $host = 'localhost';
const tr = document.createElement('tr'); $db = 'mon_cinema';
tr.innerHTML = ` $user = 'root';
<td><input type="checkbox" class="film-checkbox" value="${f.id}"></td> $pass = '';
<td>${f.poster ? `<img src="${f.poster}" class="thumb" width="40">` : '-'}</td> $charset = 'utf8mb4';
<td><strong>${f.title}</strong></td> $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
<td>${f.year || ''}</td>
<td>${f.director || ''}</td> try {
<td>${currentAdminTab === 'critique' ? (f.rating ? '★'.repeat(f.rating) : '☆') : (f.format || '-')}</td> $pdo = new PDO($dsn, $user, $pass, [
<td> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
<button onclick="openEditModal('${f.id}')">Éditer</button> PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
<button onclick="deleteSingleFilm('${f.id}')">Supprimer</button> PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
</td>`; ]);
tbody.appendChild(tr); } catch (\PDOException $e) {
}); echo json_encode(["error" => "Erreur BDD : " . $e->getMessage()]);
exit;
} }
// ── ACTIONS CRUD ── function encryptData($data) {
async function saveFilmForm(e) { $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
e.preventDefault(); $encrypted = openssl_encrypt($data, 'aes-256-cbc', ENCRYPTION_KEY, 0, $iv);
const payload = { return base64_encode($encrypted . '::' . $iv);
type: currentAdminTab,
id: document.getElementById('f-id').value,
title: document.getElementById('f-title').value,
year: document.getElementById('f-year').value,
director: document.getElementById('f-director').value,
poster: document.getElementById('f-poster').value,
// Champs conditionnels
rating: document.getElementById('f-rating').value,
review: document.getElementById('f-review').value,
streaming: document.getElementById('f-streaming').value,
format: document.getElementById('f-format').value,
length: document.getElementById('f-length').value,
publisher: document.getElementById('f-publisher').value,
ean_isbn13: document.getElementById('f-ean').value,
number_of_discs: document.getElementById('f-discs').value,
aspect_ratio: document.getElementById('f-aspect').value,
description: document.getElementById('f-description').value
};
await fetch(`${API_URL}?action=save_film`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
closeAdminModal();
loadDashboardData();
} }
async function deleteSingleFilm(id) { function decryptData($data) {
if (!confirm('Supprimer cette œuvre ?')) return; if (!$data) return '';
await fetch(`${API_URL}?action=delete_film&id=${id}&type=${currentAdminTab}`, { $decoded = base64_decode($data);
method: 'DELETE', if (strpos($decoded, '::') === false) return '';
headers: { 'Authorization': localStorage.getItem('token') } list($encrypted_data, $iv) = explode('::', $decoded, 2);
}); return openssl_decrypt($encrypted_data, 'aes-256-cbc', ENCRYPTION_KEY, 0, $iv);
loadDashboardData();
} }
// ── MODALES & UI ── function makeStableId($title, $year) {
function switchAdminTab(tabName) { $key = strtolower(trim($title)) . '|' . trim($year);
currentAdminTab = tabName; return (abs(crc32($key)) % 2000000000) + 100000000;
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.getElementById(`btn-tab-${tabName}`).classList.add('active');
// Basculer l'affichage des formulaires
document.getElementById('form-critique-fields').style.display = tabName === 'critique' ? 'block' : 'none';
document.getElementById('form-videotheque-fields').style.display = tabName === 'videotheque' ? 'block' : 'none';
renderAdminTable();
} }
function openAddModal() { function makeNewIdSafe() {
document.getElementById('film-form').reset(); return (abs(crc32(uniqid('', true))) % 2000000000) + 100000000;
document.getElementById('f-id').value = '';
document.getElementById('admin-modal').classList.add('open');
} }
function openEditModal(id) { function convertRating($rawRating) {
const item = allItems.find(x => String(x.id) === String(id)); return max(1, min(5, (int)round(floatval($rawRating))));
if (!item) return;
// Remplissage formulaire...
document.getElementById('f-id').value = item.id;
document.getElementById('f-title').value = item.title;
document.getElementById('admin-modal').classList.add('open');
} }
function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); } function checkAuth($pdo) {
function openConfigModal() { document.getElementById('config-modal').classList.add('open'); } $stmtCheck = $pdo->query("SELECT COUNT(*) as total FROM users");
function closeConfigModal() { document.getElementById('config-modal').classList.remove('open'); } if ($stmtCheck->fetch()['total'] == 0) return true;
function openPasswordModal() { document.getElementById('password-modal').classList.add('open'); }
function closePasswordModal() { document.getElementById('password-modal').classList.remove('open'); }
function logout() { $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
localStorage.removeItem('token'); if (empty($token) && function_exists('apache_request_headers')) {
window.location.href = 'login.html'; $headers = apache_request_headers();
$token = $headers['Authorization'] ?? '';
}
if ($token !== md5(ENCRYPTION_KEY . 'session')) {
http_response_code(403);
echo json_encode(["error" => "Accès interdit."]);
exit;
}
} }
// ── MOT DE PASSE ── $method = $_SERVER['REQUEST_METHOD'];
async function saveNewPassword() { $action = $_GET['action'] ?? '';
const newPwd = document.getElementById('new-password-input').value;
const confirmPwd = document.getElementById('new-password-confirm').value;
if (newPwd !== confirmPwd) return alert("Les mots de passe ne correspondent pas.");
const res = await fetch(`${API_URL}?action=update_password`, { switch ($method) {
method: 'POST', case 'GET':
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, if ($action === 'get_films') {
body: JSON.stringify({ new_password: newPwd }) $critiques = $pdo->query("SELECT *, 'critique' AS type FROM critiques ORDER BY created_at DESC")->fetchAll();
}); $videotheque = $pdo->query("SELECT *, 'videotheque' AS type FROM videotheque ORDER BY created_at DESC")->fetchAll();
if (res.ok) { alert("Mot de passe mis à jour."); closePasswordModal(); } echo json_encode(array_merge($critiques, $videotheque), JSON_UNESCAPED_UNICODE);
} } elseif ($action === 'check_security_status') {
$stmt = $pdo->query("SELECT COUNT(*) as total FROM users");
echo json_encode(["is_blank" => ($stmt->fetch()['total'] == 0)]);
}
break;
// ── IMPORT CSV ── case 'POST':
async function handleCsvUpload(input) { $data = json_decode(file_get_contents('php://input'), true) ?? [];
if (!input.files[0]) return;
const formData = new FormData(); if ($action === 'login') {
formData.append('csv_file', input.files[0]); $stmt = $pdo->query("SELECT COUNT(*) as total FROM users");
await fetch(`${API_URL}?action=import_csv`, { if ($stmt->fetch()['total'] == 0) {
method: 'POST', echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => true]);
headers: { 'Authorization': localStorage.getItem('token') }, } else {
body: formData $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE username = 'admin'");
}); $stmt->execute();
loadDashboardData(); $user = $stmt->fetch();
if ($user && password_verify($data['password'] ?? '', $user['password_hash'])) {
echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => false]);
} else {
http_response_code(401);
echo json_encode(["error" => "Mot de passe incorrect."]);
}
}
} elseif ($action === 'setup_admin' || $action === 'update_password') {
checkAuth($pdo);
$pwd = $data['password'] ?? $data['new_password'] ?? '';
$stmt = $pdo->prepare("REPLACE INTO users (id, username, password_hash) VALUES (1, 'admin', :pass)");
$stmt->execute([':pass' => password_hash($pwd, PASSWORD_BCRYPT)]);
echo json_encode(["success" => true]);
}
break;
} }