APmanageur Wi-Fi V1.0

This commit is contained in:
yoannmultigaming committed 2026-11-18 03:17:05 +01:00
1 parent 8770fe4f7a
commit eb6659dad2
2 files changed
+88 -54

No files matched your search

+58 -48
View File
@@ -750,6 +750,10 @@ def list_sessions(current_token='', lang='fr'):
def extract_token(h): def extract_token(h):
token = h.headers.get('X-Session-Token', '') if hasattr(h, 'headers') else '' 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: if not token and hasattr(h, 'headers') and 'Cookie' in h.headers:
for part in h.headers.get('Cookie', '').split(';'): for part in h.headers.get('Cookie', '').split(';'):
part = part.strip() part = part.strip()
@@ -8468,6 +8472,60 @@ class Handler(BaseHTTPRequestHandler):
log('modification_identifiants', f"Renommage machine -> {new_name}", request_ip(self), 'AUTH') 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}) self.send_json({'ok': True, 'message': 'Machine renommée avec succès', 'name': new_name})
return 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 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/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': if self.path == '/api/devices/limits':
@@ -8696,10 +8754,6 @@ class Handler(BaseHTTPRequestHandler):
c.commit(); c.close() c.commit(); c.close()
log('configuration_proxy_inverse_modifiee', username(self) or 'Administrateur', request_ip(self), 'SETTINGS') 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 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 self.path == '/api/vpn/profiles/delete':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
pid = int(data.get('id', 0)) pid = int(data.get('id', 0))
@@ -8741,16 +8795,6 @@ class Handler(BaseHTTPRequestHandler):
ks = 1 if data.get('kill_switch') else 0 ks = 1 if data.get('kill_switch') else 0
assign_client_vpn(mac, pid, ks) assign_client_vpn(mac, pid, ks)
self.send_json({'ok': True, 'message': 'Assignation VPN du client mise à jour avec succès'}); return 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 self.path == '/api/notifications/stats-report/trigger':
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
ok, msg = trigger_manual_stats_report() ok, msg = trigger_manual_stats_report()
@@ -8800,40 +8844,6 @@ class Handler(BaseHTTPRequestHandler):
with traffic_lock: station_traffic.clear() with traffic_lock: station_traffic.clear()
log('reinitialisation_donnees', 'Système', request_ip(self), 'SYSTEM') 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 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': if self.path == '/api/auth/2fa/status':
self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return
if self.path == '/api/auth/2fa/enable': if self.path == '/api/auth/2fa/enable':
+30 -6
View File
@@ -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) { async function testSetupNotification(channel) {
const detailsBox = $('setupNotifTestDetails'); const detailsBox = $('setupNotifTestDetails');
if (detailsBox) { if (detailsBox) {
@@ -3059,7 +3082,7 @@
}; };
const res = await fetch(API_URL + '/api/notifications/test', { const res = await fetch(API_URL + '/api/notifications/test', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: getSetupAuthHeaders(),
body: JSON.stringify(payload) body: JSON.stringify(payload)
}); });
const data = await res.json(); const data = await res.json();
@@ -3099,7 +3122,9 @@
async function loadNotificationSettingsInSetup() { async function loadNotificationSettingsInSetup() {
try { 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; if (!res.ok) return;
const cfg = await res.json(); const cfg = await res.json();
@@ -3576,7 +3601,7 @@
const b64 = e.target.result.split(',')[1]; const b64 = e.target.result.split(',')[1];
const res = await fetch(API_URL + '/api/backup/inspect', { const res = await fetch(API_URL + '/api/backup/inspect', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: getSetupAuthHeaders(),
body: JSON.stringify({ filename: file.name, data_base64: b64 }) body: JSON.stringify({ filename: file.name, data_base64: b64 })
}); });
const d = await res.json(); const d = await res.json();
@@ -3658,7 +3683,7 @@
try { try {
const res = await fetch(API_URL + '/api/backup/import', { const res = await fetch(API_URL + '/api/backup/import', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: getSetupAuthHeaders(),
body: JSON.stringify({ backup: pendingBackupData, options: options }) body: JSON.stringify({ backup: pendingBackupData, options: options })
}); });
const d = await res.json(); const d = await res.json();
@@ -3792,8 +3817,7 @@
} }
} catch (_) { } } catch (_) { }
const headers = { 'Content-Type': 'application/json' }; const headers = getSetupAuthHeaders(token, true);
if (token) headers['Authorization'] = 'Bearer ' + token;
// C. Configuration du réseau Wi-Fi // 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…'; msg.textContent = isEn ? '2/5 Configuring Wi-Fi Access Point…' : '2/5 Configuration du point d\'accès Wi-Fi…';