feat(вход): TOTP и recovery
This commit is contained in:
@@ -17,6 +17,10 @@ from jose import jwt
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TOTPRequired(Exception):
|
||||
"""Пароль верный, но нужен второй фактор — не ошибка пароля."""
|
||||
|
||||
SECRET = os.environ.get("SESSION_SECRET", "")
|
||||
if not SECRET:
|
||||
logger.warning("SESSION_SECRET not set!")
|
||||
@@ -144,6 +148,12 @@ def refresh_access_token(refresh_token: str) -> str | None:
|
||||
except Exception:
|
||||
return None
|
||||
if LEGACY_USER and sub == LEGACY_USER:
|
||||
try:
|
||||
import db as _db
|
||||
if _db.has_totp_admin():
|
||||
return None
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return _issue_access(sub, role)
|
||||
from db import get_user_by_email, get_auth_session
|
||||
u = get_user_by_email(sub)
|
||||
@@ -162,7 +172,8 @@ def refresh_access_token(refresh_token: str) -> str | None:
|
||||
return _make_token(u["email"], u["role"])
|
||||
|
||||
|
||||
def authenticate(username: str, password: str, client_ip: str = "") -> str | None:
|
||||
def authenticate(username: str, password: str, client_ip: str = "",
|
||||
code: str = "", recovery: str = "") -> str | None:
|
||||
"""Authenticate user. Tries legacy env user first, then SQLite.
|
||||
|
||||
Returns JWT token or None.
|
||||
@@ -176,8 +187,15 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
|
||||
if email_key and _is_locked(email_key, MAX_ATTEMPTS_EMAIL, LOCKOUT_SECONDS_EMAIL):
|
||||
return None
|
||||
|
||||
# 1. Legacy admin user from env vars
|
||||
# 1. Legacy admin user from env vars; при включённом 2FA дверь закрыта.
|
||||
if LEGACY_USER and LEGACY_PASS:
|
||||
try:
|
||||
import db as _db
|
||||
if _db.has_totp_admin():
|
||||
logger.warning("env-admin отключён: у админов включён 2FA")
|
||||
return None
|
||||
except Exception: # noqa: BLE001 — сбой проверки не должен открывать дверь
|
||||
return None
|
||||
# Сравниваем БАЙТЫ: строковое сравнение падает на кириллице
|
||||
# («comparing strings with non-ASCII characters is not supported»), и вход с русским
|
||||
# паролем или адресом отдавал человеку маску сбоя вместо ответа (живой прогон
|
||||
@@ -199,6 +217,28 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
|
||||
update_password_hash(user["email"], hash_password(password))
|
||||
except Exception: # noqa: BLE001 — апгрейд не должен ломать вход
|
||||
logger.exception("password rehash failed")
|
||||
if user.get("totp_enabled"):
|
||||
if not code and not recovery:
|
||||
raise TOTPRequired()
|
||||
key = f"totp:{user['email']}"
|
||||
if _is_locked(key, 5, 300):
|
||||
return None
|
||||
import json as _json
|
||||
import totp as _totp
|
||||
ok = False
|
||||
if recovery:
|
||||
hashes = _json.loads(user.get("totp_recovery") or "[]")
|
||||
idx = _totp.verify_recovery(recovery, hashes)
|
||||
if idx is not None:
|
||||
hashes.pop(int(idx))
|
||||
from db import consume_recovery
|
||||
consume_recovery(user["email"], _json.dumps(hashes))
|
||||
ok = True
|
||||
else:
|
||||
ok = _totp.verify(user.get("totp_secret") or "", code)
|
||||
if not ok:
|
||||
_record_attempt(key)
|
||||
return None
|
||||
return _issue_access(user["email"], user["role"], client_ip)
|
||||
|
||||
if ip_key:
|
||||
|
||||
Reference in New Issue
Block a user