From 223112c08518ced7615f7c9804f18ca5f8c274a1 Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 30 Mar 2026 04:47:46 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=5Fmake=5Frefresh=5Ftoken=20=D0=B2=20auth.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refresh-токен (7 дней) для JWT авторизации. Был локально, но не закоммичен — ломал логин на проде. Co-Authored-By: Claude Opus 4.6 (1M context) --- auth.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/auth.py b/auth.py index 60e4b52..8202b57 100644 --- a/auth.py +++ b/auth.py @@ -22,6 +22,7 @@ if not SECRET: ALGORITHM = "HS256" TOKEN_EXPIRE = 86400 # 24 hours +REFRESH_EXPIRE = 604800 # 7 days # Legacy single user (admin) LEGACY_USER = os.environ.get("SMETA_USER", "") @@ -63,7 +64,7 @@ def check_password(password: str, password_hash: str) -> bool: def _make_token(username: str, role: str = "user") -> str: - """Create JWT token.""" + """Create JWT access token (24h).""" payload = { "sub": username, "role": role, @@ -72,6 +73,30 @@ def _make_token(username: str, role: str = "user") -> str: return jwt.encode(payload, SECRET, algorithm=ALGORITHM) +def _make_refresh_token(username: str, role: str = "user") -> str: + """Create JWT refresh token (7 days).""" + payload = { + "sub": username, + "role": role, + "type": "refresh", + "exp": int(time.time()) + REFRESH_EXPIRE, + } + return jwt.encode(payload, SECRET, algorithm=ALGORITHM) + + +def refresh_access_token(refresh_token: str) -> str | None: + """Exchange valid refresh token for new access token.""" + if not SECRET: + return None + try: + payload = jwt.decode(refresh_token, SECRET, algorithms=[ALGORITHM]) + if payload.get("type") != "refresh": + return None + return _make_token(payload["sub"], payload.get("role", "user")) + except Exception: + return None + + def authenticate(username: str, password: str, client_ip: str = "") -> str | None: """Authenticate user. Tries legacy env user first, then SQLite.