AP manageur V1.1 (Bêta)
This commit is contained in:
1 parent
5598321998
commit
d806c0ddac
4 files changed
+426
-19
No files matched your search
@@ -1219,6 +1219,36 @@ def verify_user(username, password):
|
||||
c = db(); row = c.execute('SELECT username,password_hash,totp_secret FROM auth_users WHERE username=?', (username.strip(),)).fetchone(); c.close()
|
||||
return row if row and password_ok(password, row[1]) else None
|
||||
|
||||
_login_failures = {}
|
||||
_login_failures_lock = threading.Lock()
|
||||
|
||||
def check_login_rate_limit(ip):
|
||||
now = time.time()
|
||||
with _login_failures_lock:
|
||||
info = _login_failures.get(ip)
|
||||
if info:
|
||||
if info.get('locked_until', 0) > now:
|
||||
remaining = max(1, int(info['locked_until'] - now))
|
||||
return False, remaining
|
||||
if now - info.get('last_time', 0) > 300:
|
||||
_login_failures.pop(ip, None)
|
||||
return True, 0
|
||||
|
||||
def record_login_failure(ip):
|
||||
now = time.time()
|
||||
with _login_failures_lock:
|
||||
info = _login_failures.setdefault(ip, {'count': 0, 'last_time': now, 'locked_until': 0})
|
||||
info['count'] += 1
|
||||
info['last_time'] = now
|
||||
if info['count'] >= 5:
|
||||
info['locked_until'] = now + 300
|
||||
return True, 300
|
||||
return False, 0
|
||||
|
||||
def record_login_success(ip):
|
||||
with _login_failures_lock:
|
||||
_login_failures.pop(ip, None)
|
||||
|
||||
def parse_os(user_agent):
|
||||
if not user_agent: return 'Inconnu'
|
||||
ua = user_agent.lower()
|
||||
@@ -3363,8 +3393,8 @@ def send_telegram_notification(cfg, title, message, details=None):
|
||||
|
||||
def send_custom_webhook_notification(cfg, title, message, details=None, level="info"):
|
||||
url = (cfg.get('url') or '').strip()
|
||||
if not url or not url.startswith('http'):
|
||||
raise ValueError("URL du Webhook personnalisé invalide")
|
||||
if not url or not (url.startswith('http://') or url.startswith('https://')):
|
||||
raise ValueError("URL du Webhook personnalisé invalide (seuls http:// et https:// sont autorisés)")
|
||||
|
||||
method = (cfg.get('method') or 'POST').strip().upper()
|
||||
if method not in ('POST', 'PUT', 'GET'):
|
||||
@@ -11637,7 +11667,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
data['error'] = translate_api_text(data['error'], req_lang)
|
||||
if 'message' in data and isinstance(data['message'], str):
|
||||
data['message'] = translate_api_text(data['message'], req_lang)
|
||||
body=json.dumps(data,ensure_ascii=False).encode(); self.send_response(status); self.send_header('Content-Type','application/json; charset=utf-8'); self.send_header('Connection','close'); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token, X-Language, Accept-Language'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
|
||||
body=json.dumps(data,ensure_ascii=False).encode(); self.send_response(status); self.send_header('Content-Type','application/json; charset=utf-8'); self.send_header('Connection','close'); self.send_header('X-Content-Type-Options','nosniff'); self.send_header('X-Frame-Options','SAMEORIGIN'); self.send_header('Referrer-Policy','strict-origin-when-cross-origin'); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token, X-Language, Accept-Language'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
|
||||
def do_OPTIONS(self): self.send_response(204); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.end_headers()
|
||||
def do_GET(self):
|
||||
if self.path == '/api/version':
|
||||
@@ -12216,28 +12246,44 @@ class Handler(BaseHTTPRequestHandler):
|
||||
log('creation_compte_admin', u, request_ip(self), 'AUTH')
|
||||
self.send_json({'ok':True,'message':'Compte créé','two_factor_enabled':False}); return
|
||||
if self.path == '/api/login':
|
||||
ip = request_ip(self)
|
||||
allowed, remaining = check_login_rate_limit(ip)
|
||||
if not allowed:
|
||||
self.send_json({'error': f'Trop de tentatives échouées. Compte temporairement verrouillé pour {remaining} seconde(s).'}, 429)
|
||||
return
|
||||
u=str(data.get('username',''))
|
||||
row=verify_user(u,str(data.get('password','')))
|
||||
if not row:
|
||||
log('echec_connexion', u or 'Inconnu', request_ip(self), 'AUTH')
|
||||
dispatch_notification('admin_login_failed', "⚠️ Échec de connexion administrateur", f"Une tentative de connexion au compte administrateur a échoué (mot de passe invalide).", details={"Identifiant tenté": u or "Inconnu", "Adresse IP": request_ip(self), "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=8, level="danger")
|
||||
time.sleep(1.0)
|
||||
is_locked, lock_sec = record_login_failure(ip)
|
||||
log('echec_connexion', u or 'Inconnu', ip, 'AUTH')
|
||||
dispatch_notification('admin_login_failed', "⚠️ Échec de connexion administrateur", f"Une tentative de connexion au compte administrateur a échoué (mot de passe invalide).", details={"Identifiant tenté": u or "Inconnu", "Adresse IP": ip, "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=8, level="danger")
|
||||
if is_locked:
|
||||
self.send_json({'error': f'Trop de tentatives échouées. Accès temporairement verrouillé pendant {lock_sec} secondes.'}, 429)
|
||||
return
|
||||
raise ValueError('Utilisateur ou mot de passe incorrect')
|
||||
used_recovery = False
|
||||
if row[2]:
|
||||
otp=data.get('otp')
|
||||
if not totp_ok(row[2],otp):
|
||||
if not recovery_use(otp):
|
||||
log('echec_connexion', row[0], request_ip(self), 'AUTH')
|
||||
time.sleep(1.0)
|
||||
is_locked, lock_sec = record_login_failure(ip)
|
||||
log('echec_connexion', row[0], ip, 'AUTH')
|
||||
if is_locked:
|
||||
self.send_json({'error': f'Trop de tentatives échouées. Accès temporairement verrouillé pendant {lock_sec} secondes.'}, 429)
|
||||
return
|
||||
raise ValueError('Code de double identification incorrect')
|
||||
used_recovery = True
|
||||
log('connexion_code_recuperation', row[0], request_ip(self), 'AUTH')
|
||||
log('connexion_code_recuperation', row[0], ip, 'AUTH')
|
||||
else:
|
||||
log('connexion_admin', row[0], request_ip(self), 'AUTH')
|
||||
log('connexion_admin', row[0], ip, 'AUTH')
|
||||
else:
|
||||
log('connexion_admin', row[0], request_ip(self), 'AUTH')
|
||||
log('connexion_admin', row[0], ip, 'AUTH')
|
||||
record_login_success(ip)
|
||||
c_name = str(data.get('device_name', '')).strip() or urllib.parse.unquote(self.headers.get('X-Device-Name', ''))
|
||||
dispatch_notification('admin_login', "🔒 Connexion au compte administrateur", f"Connexion réussie au compte administrateur « {row[0]} ».", details={"Compte": row[0], "Machine": c_name or "Machine non spécifiée", "Adresse IP": request_ip(self), "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="info")
|
||||
self.send_json({'ok':True,'token':new_session(row[0], request_ip(self), self.headers.get('User-Agent',''), c_name),'used_recovery':used_recovery}); return
|
||||
dispatch_notification('admin_login', "🔒 Connexion au compte administrateur", f"Connexion réussie au compte administrateur « {row[0]} ».", details={"Compte": row[0], "Machine": c_name or "Machine non spécifiée", "Adresse IP": ip, "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="info")
|
||||
self.send_json({'ok':True,'token':new_session(row[0], ip, self.headers.get('User-Agent',''), c_name),'used_recovery':used_recovery}); return
|
||||
if self.path == '/api/auth/passkey/login/options':
|
||||
c = db()
|
||||
pks = c.execute('SELECT id FROM auth_passkeys').fetchall()
|
||||
|
||||
Reference in new issue
Block a user