| const { WebSocketServer } = require('ws');
|
| const fs = require('fs');
|
| const path = require('path');
|
|
|
|
|
|
|
| const PORT = process.env.PORT || 7860;
|
|
|
|
|
| const wss = new WebSocketServer({ port: PORT, host: '0.0.0.0' });
|
|
|
|
|
| const DOSSIER_USER = path.join(__dirname, 'user');
|
|
|
|
|
| if (!fs.existsSync(DOSSIER_USER)) {
|
| fs.mkdirSync(DOSSIER_USER);
|
| }
|
|
|
| console.log("=== SERVEUR DE CHAT PRODUCTION EN LIGNE ===");
|
| console.log(`Serveur WebSocket actif sur le port ${PORT}...\n`);
|
|
|
| wss.on('connection', (ws) => {
|
| console.log("[CONNEXION] Un client distant s'est connecté.");
|
|
|
| ws.on('message', (message) => {
|
| const texteRecu = message.toString();
|
|
|
| try {
|
| const donnees = JSON.parse(texteRecu);
|
|
|
|
|
| if (donnees.type === "enregistrement" && donnees.email && donnees.pseudo) {
|
| const contenuFichier = `pseudo: ${donnees.pseudo}\nemail: ${donnees.email}`;
|
|
|
|
|
| const nomFichier = `${donnees.email.replace(/[^a-zA-Z0-9@.]/g, "_")}.txt`;
|
| const cheminFichier = path.join(DOSSIER_USER, nomFichier);
|
|
|
|
|
| fs.writeFileSync(cheminFichier, contenuFichier, 'utf8');
|
| console.log(`[PROD-USER] Nouvel enregistrement : user/${nomFichier}`);
|
|
|
| ws.send(JSON.stringify({ type: "reponse_enregistrement", statut: "succes" }));
|
| return;
|
| }
|
|
|
|
|
| if (donnees.type === "comparer" && donnees.email && donnees.pseudo) {
|
| const nomFichier = `${donnees.email.replace(/[^a-zA-Z0-9@.]/g, "_")}.txt`;
|
| const cheminFichier = path.join(DOSSIER_USER, nomFichier);
|
|
|
| if (fs.existsSync(cheminFichier)) {
|
| const contenu = fs.readFileSync(cheminFichier, 'utf8');
|
| const contenuAttendu = `pseudo: ${donnees.pseudo}\nemail: ${donnees.email}`;
|
|
|
| if (contentsMatch(contenu, contenuAttendu)) {
|
| console.log(`[PROD-AUTH] Succès pour : ${donnees.email}`);
|
| ws.send(JSON.stringify({ type: "reponse_comparer", valide: true, message: "Infos correctes" }));
|
| } else {
|
| console.log(`[PROD-AUTH] Échec (Pseudo invalide) pour : ${donnees.email}`);
|
| ws.send(JSON.stringify({ type: "reponse_comparer", valide: false, message: "Pseudo incorrect" }));
|
| }
|
| } else {
|
| console.log(`[PROD-AUTH] Échec (Inconnu) pour : ${donnees.email}`);
|
| ws.send(JSON.stringify({ type: "reponse_comparer", valide: false, message: "Utilisateur inconnu" }));
|
| }
|
| return;
|
| }
|
|
|
| } catch (e) {
|
|
|
| }
|
|
|
|
|
| wss.clients.forEach((client) => {
|
| if (client.readyState === 1) {
|
| client.send(texteRecu);
|
| }
|
| });
|
| });
|
|
|
| ws.on('close', () => {
|
| console.log("[DÉCONNEXION] Un client s'est déconnecté.");
|
| });
|
| });
|
|
|
|
|
| function contentsMatch(str1, str2) {
|
| return str1.replace(/\r/g, '').trim() === str2.replace(/\r/g, '').trim();
|
| } |