From eb6659dad2fe95d48af6f543837d51934b60a101 Mon Sep 17 00:00:00 2001 From: yoannmultigaming Date: Wed, 18 Nov 2026 03:17:05 +0100 Subject: [PATCH] APmanageur Wi-Fi V1.0 --- ap.py | 106 +++++++++++++++++++++++++++++------------------------ setup.html | 36 +++++++++++++++--- 2 files changed, 88 insertions(+), 54 deletions(-) diff --git a/ap.py b/ap.py index 6e6ccdd..4fe0f50 100644 --- a/ap.py +++ b/ap.py @@ -750,6 +750,10 @@ def list_sessions(current_token='', lang='fr'): def extract_token(h): token = h.headers.get('X-Session-Token', '') if hasattr(h, 'headers') else '' + if not token and hasattr(h, 'headers'): + auth_hdr = h.headers.get('Authorization', '') + if auth_hdr.lower().startswith('bearer '): + token = auth_hdr[7:].strip() if not token and hasattr(h, 'headers') and 'Cookie' in h.headers: for part in h.headers.get('Cookie', '').split(';'): part = part.strip() @@ -8468,6 +8472,60 @@ class Handler(BaseHTTPRequestHandler): log('modification_identifiants', f"Renommage machine -> {new_name}", request_ip(self), 'AUTH') self.send_json({'ok': True, 'message': 'Machine renommée avec succès', 'name': new_name}) return + if self.path == '/api/backup/inspect': + if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return + fname = str(data.get('filename', 'sauvegarde')).strip() + b64_content = str(data.get('data_base64', '')).strip() + raw_json = data.get('backup') + if raw_json and isinstance(raw_json, dict): + self.send_json({'ok': True, 'filename': fname, 'backup': raw_json}); return + if not b64_content: + self.send_json({'error': 'Contenu du fichier manquant'}, 400); return + try: + raw_bytes = base64.b64decode(b64_content) + backup = inspect_backup_bytes(raw_bytes, fname) + self.send_json({'ok': True, 'filename': fname, 'backup': backup}) + except Exception as e: + self.send_json({'error': f'Impossible d’analyser le fichier : {e}'}, 400) + return + if self.path == '/api/backup/import': + if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return + try: + was_active = False + try: was_active = bool(status(force_refresh=True).get('active')) + except Exception: pass + if 'data_base64' in data and data['data_base64']: + raw_bytes = base64.b64decode(data['data_base64']) + backup = inspect_backup_bytes(raw_bytes, data.get('filename', '')) + stats = import_backup_data(backup, data.get('options', {})) + else: + stats = import_backup_data(data) + invalidate_status_cache() + if not was_active and stats.get('preferences', 0) > 0 and get_pref('ap_ssid', '') and get_pref('ap_password', ''): + threading.Thread(target=restore_ap_from_db, daemon=True).start() + log('import_configuration_complete', username(self) or 'Administrateur', request_ip(self), 'SYSTEM') + self.send_json({ + 'ok': True, + 'message': f"Sauvegarde restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages restaurés).", + 'stats': stats + }) + except Exception as e: + self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400) + return + if self.path == '/api/vpn/profiles': + if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return + pid = create_or_update_vpn_profile(data) + self.send_json({'ok': True, 'message': 'Profil VPN enregistré avec succès', 'id': pid}); return + if self.path == '/api/notifications/settings': + if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return + save_notifications_settings(data) + self.send_json({'ok':True, 'message':'Réglages des notifications enregistrés avec succès'}); return + if self.path == '/api/notifications/test': + if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return + channel = str(data.get('channel', 'all')).strip().lower() + test_cfg = data.get('config') + results = test_notifications(channel, test_config=test_cfg) + self.send_json({'ok':True, 'results':results}); return if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if self.path == '/api/clients/block': set_blocked(str(data.get('mac','')),bool(data.get('blocked',True))); self.send_json({'ok':True}); return if self.path == '/api/devices/limits': @@ -8696,10 +8754,6 @@ class Handler(BaseHTTPRequestHandler): c.commit(); c.close() log('configuration_proxy_inverse_modifiee', username(self) or 'Administrateur', request_ip(self), 'SETTINGS') self.send_json({'ok': True, 'message': 'Réglages du proxy inversé enregistrés avec succès !'}); return - if self.path == '/api/vpn/profiles': - if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return - pid = create_or_update_vpn_profile(data) - self.send_json({'ok': True, 'message': 'Profil VPN enregistré avec succès', 'id': pid}); return if self.path == '/api/vpn/profiles/delete': if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return pid = int(data.get('id', 0)) @@ -8741,16 +8795,6 @@ class Handler(BaseHTTPRequestHandler): ks = 1 if data.get('kill_switch') else 0 assign_client_vpn(mac, pid, ks) self.send_json({'ok': True, 'message': 'Assignation VPN du client mise à jour avec succès'}); return - if self.path == '/api/notifications/settings': - if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return - save_notifications_settings(data) - self.send_json({'ok':True, 'message':'Réglages des notifications enregistrés avec succès'}); return - if self.path == '/api/notifications/test': - if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return - channel = str(data.get('channel', 'all')).strip().lower() - test_cfg = data.get('config') - results = test_notifications(channel, test_config=test_cfg) - self.send_json({'ok':True, 'results':results}); return if self.path == '/api/notifications/stats-report/trigger': if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return ok, msg = trigger_manual_stats_report() @@ -8800,40 +8844,6 @@ class Handler(BaseHTTPRequestHandler): with traffic_lock: station_traffic.clear() log('reinitialisation_donnees', 'Système', request_ip(self), 'SYSTEM') self.send_json({'ok':True,'message':'Toutes les données et le point d’accès ont été réinitialisés et supprimés'}); return - if self.path == '/api/backup/inspect': - if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return - fname = str(data.get('filename', 'sauvegarde')).strip() - b64_content = str(data.get('data_base64', '')).strip() - raw_json = data.get('backup') - if raw_json and isinstance(raw_json, dict): - self.send_json({'ok': True, 'filename': fname, 'backup': raw_json}); return - if not b64_content: - self.send_json({'error': 'Contenu du fichier manquant'}, 400); return - try: - raw_bytes = base64.b64decode(b64_content) - backup = inspect_backup_bytes(raw_bytes, fname) - self.send_json({'ok': True, 'filename': fname, 'backup': backup}) - except Exception as e: - self.send_json({'error': f'Impossible d’analyser le fichier : {e}'}, 400) - return - if self.path == '/api/backup/import': - if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return - try: - if 'data_base64' in data and data['data_base64']: - raw_bytes = base64.b64decode(data['data_base64']) - backup = inspect_backup_bytes(raw_bytes, data.get('filename', '')) - stats = import_backup_data(backup, data.get('options', {})) - else: - stats = import_backup_data(data) - log('import_configuration_complete', username(self) or 'Administrateur', request_ip(self), 'SYSTEM') - self.send_json({ - 'ok': True, - 'message': f"Sauvegarde restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages restaurés).", - 'stats': stats - }) - except Exception as e: - self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400) - return if self.path == '/api/auth/2fa/status': self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return if self.path == '/api/auth/2fa/enable': diff --git a/setup.html b/setup.html index 71f8bb7..cc9b03a 100644 --- a/setup.html +++ b/setup.html @@ -3047,6 +3047,29 @@ }; } + function getSetupAuthToken(extraToken) { + if (extraToken) return extraToken; + try { + const m = document.cookie.match(/(?:^|;\s*)apAuthToken=([^;]+)/); + if (m && m[1]) return decodeURIComponent(m[1]); + } catch (_) { } + try { + return localStorage.getItem('apAuthToken') || sessionStorage.getItem('apAuthToken') || ''; + } catch (_) { + return ''; + } + } + + function getSetupAuthHeaders(extraToken, jsonContent = true) { + const h = jsonContent ? { 'Content-Type': 'application/json' } : {}; + const tok = getSetupAuthToken(extraToken); + if (tok) { + h['X-Session-Token'] = tok; + h['Authorization'] = 'Bearer ' + tok; + } + return h; + } + async function testSetupNotification(channel) { const detailsBox = $('setupNotifTestDetails'); if (detailsBox) { @@ -3059,7 +3082,7 @@ }; const res = await fetch(API_URL + '/api/notifications/test', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: getSetupAuthHeaders(), body: JSON.stringify(payload) }); const data = await res.json(); @@ -3099,7 +3122,9 @@ async function loadNotificationSettingsInSetup() { try { - const res = await fetch(API_URL + '/api/notifications/settings'); + const res = await fetch(API_URL + '/api/notifications/settings', { + headers: getSetupAuthHeaders('', false) + }); if (!res.ok) return; const cfg = await res.json(); @@ -3576,7 +3601,7 @@ const b64 = e.target.result.split(',')[1]; const res = await fetch(API_URL + '/api/backup/inspect', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: getSetupAuthHeaders(), body: JSON.stringify({ filename: file.name, data_base64: b64 }) }); const d = await res.json(); @@ -3658,7 +3683,7 @@ try { const res = await fetch(API_URL + '/api/backup/import', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: getSetupAuthHeaders(), body: JSON.stringify({ backup: pendingBackupData, options: options }) }); const d = await res.json(); @@ -3792,8 +3817,7 @@ } } catch (_) { } - const headers = { 'Content-Type': 'application/json' }; - if (token) headers['Authorization'] = 'Bearer ' + token; + const headers = getSetupAuthHeaders(token, true); // C. Configuration du réseau Wi-Fi msg.textContent = isEn ? '2/5 Configuring Wi-Fi Access Point…' : '2/5 Configuration du point d\'accès Wi-Fi…';