Actualiser js/auth.js

This commit is contained in:
2026-07-21 16:09:47 +02:00
parent 92ee7ae39d
commit f7d7ebd63f
+29 -44
View File
@@ -1,6 +1,29 @@
const API_BASE_URL = 'https://monpetitpari.fr/api';
// Gestion du token
async function apiCall(endpoint, method = 'GET', data = null) {
const options = {
method: method,
headers: { 'Content-Type': 'application/json' }
};
const token = getToken();
if (token) options.headers['Authorization'] = `Bearer ${token}`;
if (data && (method === 'POST' || method === 'PUT')) {
options.body = JSON.stringify(data);
}
try {
const response = await fetch(`${API_BASE_URL}/${endpoint}`, options);
const text = await response.text();
const result = JSON.parse(text);
if (!response.ok) {
throw new Error(result.error || 'Erreur serveur');
}
return result;
} catch (error) {
console.error('API Error:', error);
throw error;
}
}
function getToken() {
return localStorage.getItem('authToken');
}
@@ -14,47 +37,20 @@ function removeToken() {
localStorage.removeItem('currentUser');
}
// Remplace le bloc try/catch de apiCall par celui-ci pour mieux voir l'erreur
try {
const response = await fetch(`${API_BASE_URL}/${endpoint}`, options);
const text = await response.text(); // On récupère le texte brut d'abord
console.log('Réponse brute du serveur :', text); // <--- AJOUTE ÇA
const result = JSON.parse(text); // On tente le parse après
if (!response.ok) {
throw new Error(result.error || 'Erreur serveur');
}
return result;
} catch (error) {
console.error('API Error:', error);
throw error;
}
// Inscription
async function register() {
const username = document.getElementById('regUsername').value;
const email = document.getElementById('regEmail').value;
const password = document.getElementById('regPassword').value;
if (!username || !email || !password) {
alert('Veuillez remplir tous les champs');
return;
}
try {
const result = await apiCall('auth.php?action=register', 'POST', {
username,
email,
password
});
const result = await apiCall('auth.php?action=register', 'POST', { username, email, password });
setToken(result.token);
localStorage.setItem('currentUser', JSON.stringify(result.user));
alert('Compte créé avec succès!');
closeModal();
if (result.user.role === 'admin') {
window.location.href = 'admin.html';
} else {
@@ -65,25 +61,17 @@ async function register() {
}
}
// Connexion
async function login() {
const username = document.getElementById('loginUsername').value;
const password = document.getElementById('loginPassword').value;
if (!username || !password) {
alert('Veuillez remplir tous les champs');
return;
}
try {
const result = await apiCall('auth.php?action=login', 'POST', {
username,
password
});
const result = await apiCall('auth.php?action=login', 'POST', { username, password });
setToken(result.token);
localStorage.setItem('currentUser', JSON.stringify(result.user));
if (result.user.role === 'admin') {
window.location.href = 'admin.html';
} else {
@@ -94,17 +82,17 @@ async function login() {
}
}
// Déconnexion
function logout() {
removeToken();
window.location.href = 'index.html';
}
// Afficher/Masquer le modal
function showModal(type) {
document.getElementById('authModal').style.display = 'block';
if (type === 'register') {
toggleAuth('register');
} else {
toggleAuth('login');
}
}
@@ -122,11 +110,9 @@ function toggleAuth(type) {
}
}
// Vérifier si l'utilisateur est connecté au chargement
window.onload = function() {
const token = getToken();
const user = localStorage.getItem('currentUser');
if (token && user) {
const userData = JSON.parse(user);
if (userData.role === 'admin') {
@@ -137,10 +123,9 @@ window.onload = function() {
}
};
// Fermer modal en cliquant dehors
window.onclick = function(event) {
const modal = document.getElementById('authModal');
if (event.target === modal) {
closeModal();
}
}
};