Actualiser js/auth.js
This commit is contained in:
+66
-26
@@ -1,29 +1,6 @@
|
|||||||
const API_BASE_URL = 'https://monpetitpari.fr/api';
|
const API_BASE_URL = 'https://monpetitpari.fr/api';
|
||||||
|
|
||||||
async function apiCall(endpoint, method = 'GET', data = null) {
|
// Gestion du token dans le stockage local
|
||||||
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() {
|
function getToken() {
|
||||||
return localStorage.getItem('authToken');
|
return localStorage.getItem('authToken');
|
||||||
}
|
}
|
||||||
@@ -37,20 +14,59 @@ function removeToken() {
|
|||||||
localStorage.removeItem('currentUser');
|
localStorage.removeItem('currentUser');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Moteur d'appel API sécurisé et centralisé
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inscription
|
||||||
async function register() {
|
async function register() {
|
||||||
const username = document.getElementById('regUsername').value;
|
const username = document.getElementById('regUsername').value;
|
||||||
const email = document.getElementById('regEmail').value;
|
const email = document.getElementById('regEmail').value;
|
||||||
const password = document.getElementById('regPassword').value;
|
const password = document.getElementById('regPassword').value;
|
||||||
|
|
||||||
if (!username || !email || !password) {
|
if (!username || !email || !password) {
|
||||||
alert('Veuillez remplir tous les champs');
|
alert('Veuillez remplir tous les champs');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
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);
|
setToken(result.token);
|
||||||
localStorage.setItem('currentUser', JSON.stringify(result.user));
|
localStorage.setItem('currentUser', JSON.stringify(result.user));
|
||||||
|
|
||||||
alert('Compte créé avec succès!');
|
alert('Compte créé avec succès!');
|
||||||
closeModal();
|
closeModal();
|
||||||
|
|
||||||
if (result.user.role === 'admin') {
|
if (result.user.role === 'admin') {
|
||||||
window.location.href = 'admin.html';
|
window.location.href = 'admin.html';
|
||||||
} else {
|
} else {
|
||||||
@@ -61,17 +77,25 @@ async function register() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Connexion
|
||||||
async function login() {
|
async function login() {
|
||||||
const username = document.getElementById('loginUsername').value;
|
const username = document.getElementById('loginUsername').value;
|
||||||
const password = document.getElementById('loginPassword').value;
|
const password = document.getElementById('loginPassword').value;
|
||||||
|
|
||||||
if (!username || !password) {
|
if (!username || !password) {
|
||||||
alert('Veuillez remplir tous les champs');
|
alert('Veuillez remplir tous les champs');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
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);
|
setToken(result.token);
|
||||||
localStorage.setItem('currentUser', JSON.stringify(result.user));
|
localStorage.setItem('currentUser', JSON.stringify(result.user));
|
||||||
|
|
||||||
if (result.user.role === 'admin') {
|
if (result.user.role === 'admin') {
|
||||||
window.location.href = 'admin.html';
|
window.location.href = 'admin.html';
|
||||||
} else {
|
} else {
|
||||||
@@ -82,11 +106,13 @@ async function login() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Déconnexion
|
||||||
function logout() {
|
function logout() {
|
||||||
removeToken();
|
removeToken();
|
||||||
window.location.href = 'index.html';
|
window.location.href = 'index.html';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Afficher / Masquer la fenêtre modale de connexion et d'inscription
|
||||||
function showModal(type) {
|
function showModal(type) {
|
||||||
document.getElementById('authModal').style.display = 'block';
|
document.getElementById('authModal').style.display = 'block';
|
||||||
if (type === 'register') {
|
if (type === 'register') {
|
||||||
@@ -110,19 +136,33 @@ function toggleAuth(type) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initialisation au chargement de la page
|
||||||
window.onload = function() {
|
window.onload = function() {
|
||||||
|
// Sécurité : Attacher l'événement au bouton Connexion s'il n'a pas l'attribut onclick dans le HTML
|
||||||
|
const loginBtn = document.getElementById('loginBtn');
|
||||||
|
if (loginBtn && !loginBtn.onclick) {
|
||||||
|
loginBtn.onclick = () => showModal('login');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vérifier si l'utilisateur est déjà connecté pour le rediriger directement
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
const user = localStorage.getItem('currentUser');
|
const user = localStorage.getItem('currentUser');
|
||||||
|
|
||||||
if (token && user) {
|
if (token && user) {
|
||||||
|
try {
|
||||||
const userData = JSON.parse(user);
|
const userData = JSON.parse(user);
|
||||||
if (userData.role === 'admin') {
|
if (userData.role === 'admin') {
|
||||||
window.location.href = 'admin.html';
|
window.location.href = 'admin.html';
|
||||||
} else {
|
} else {
|
||||||
window.location.href = 'dashboard.html';
|
window.location.href = 'dashboard.html';
|
||||||
}
|
}
|
||||||
|
} catch(e) {
|
||||||
|
removeToken();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Fermer la modale en cliquant à l'extérieur de la boîte de dialogue
|
||||||
window.onclick = function(event) {
|
window.onclick = function(event) {
|
||||||
const modal = document.getElementById('authModal');
|
const modal = document.getElementById('authModal');
|
||||||
if (event.target === modal) {
|
if (event.target === modal) {
|
||||||
|
|||||||
Reference in New Issue
Block a user