- SQLite: таблицы users (email, password_hash, role, verified) + invites - auth.py: register_user, verify_email, hash_password + legacy env user - email_service.py: SMTP Timeweb (smtp.timeweb.ru:465) — код подтверждения - API: POST /api/register, /api/verify-email, /api/admin/invite - UI: /register?invite=TOKEN — 3-шаговая регистрация - Admin: кнопка создать приглашение, список invites + users - Обратная совместимость: env user (smeta) = admin Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
161 lines
4.8 KiB
Python
161 lines
4.8 KiB
Python
"""JWT authentication — multi-user with invite-based registration.
|
|
|
|
Supports:
|
|
1. Legacy env-var user (SMETA_USER/SMETA_PASS) — admin
|
|
2. Registered users from SQLite (email + password)
|
|
"""
|
|
|
|
import hashlib
|
|
import hmac
|
|
import logging
|
|
import os
|
|
import secrets
|
|
import time
|
|
|
|
from jose import jwt
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
SECRET = os.environ.get("SESSION_SECRET", "")
|
|
if not SECRET:
|
|
logger.warning("SESSION_SECRET not set!")
|
|
|
|
ALGORITHM = "HS256"
|
|
TOKEN_EXPIRE = 86400 # 24 hours
|
|
|
|
# Legacy single user (admin)
|
|
LEGACY_USER = os.environ.get("SMETA_USER", "")
|
|
LEGACY_PASS = os.environ.get("SMETA_PASS", "")
|
|
|
|
# Rate limiting
|
|
_login_attempts: dict[str, list[float]] = {}
|
|
MAX_ATTEMPTS = 5
|
|
LOCKOUT_SECONDS = 300
|
|
|
|
|
|
def _is_locked(ip: str) -> bool:
|
|
now = time.time()
|
|
attempts = _login_attempts.get(ip, [])
|
|
attempts = [t for t in attempts if now - t < LOCKOUT_SECONDS]
|
|
_login_attempts[ip] = attempts
|
|
return len(attempts) >= MAX_ATTEMPTS
|
|
|
|
|
|
def _record_attempt(ip: str):
|
|
_login_attempts.setdefault(ip, []).append(time.time())
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
"""Hash password with salt using SHA-256."""
|
|
salt = secrets.token_hex(16)
|
|
h = hashlib.sha256((salt + password).encode()).hexdigest()
|
|
return f"{salt}:{h}"
|
|
|
|
|
|
def check_password(password: str, password_hash: str) -> bool:
|
|
"""Verify password against stored hash."""
|
|
if ":" not in password_hash:
|
|
return False
|
|
salt, h = password_hash.split(":", 1)
|
|
return hmac.compare_digest(
|
|
hashlib.sha256((salt + password).encode()).hexdigest(), h
|
|
)
|
|
|
|
|
|
def _make_token(username: str, role: str = "user") -> str:
|
|
"""Create JWT token."""
|
|
payload = {
|
|
"sub": username,
|
|
"role": role,
|
|
"exp": int(time.time()) + TOKEN_EXPIRE,
|
|
}
|
|
return jwt.encode(payload, SECRET, algorithm=ALGORITHM)
|
|
|
|
|
|
def authenticate(username: str, password: str, client_ip: str = "") -> str | None:
|
|
"""Authenticate user. Tries legacy env user first, then SQLite.
|
|
|
|
Returns JWT token or None.
|
|
"""
|
|
if not SECRET:
|
|
return None
|
|
if client_ip and _is_locked(client_ip):
|
|
return None
|
|
|
|
# 1. Legacy admin user from env vars
|
|
if LEGACY_USER and LEGACY_PASS:
|
|
if hmac.compare_digest(username, LEGACY_USER) and hmac.compare_digest(password, LEGACY_PASS):
|
|
return _make_token(username, role="admin")
|
|
|
|
# 2. Registered users from SQLite
|
|
from db import get_user_by_email
|
|
user = get_user_by_email(username) # username = email
|
|
if user and user["verified"] and check_password(password, user["password_hash"]):
|
|
return _make_token(user["email"], role=user["role"])
|
|
|
|
if client_ip:
|
|
_record_attempt(client_ip)
|
|
return None
|
|
|
|
|
|
def register_user(email: str, password: str, invite_token: str) -> dict:
|
|
"""Register new user with invite token.
|
|
|
|
Returns {"ok": True, "message": ...} or {"ok": False, "error": ...}.
|
|
"""
|
|
from db import get_user_by_email, create_user, use_invite, set_verify_code
|
|
|
|
email = email.lower().strip()
|
|
if not email or "@" not in email:
|
|
return {"ok": False, "error": "Некорректный email"}
|
|
if len(password) < 6:
|
|
return {"ok": False, "error": "Пароль минимум 6 символов"}
|
|
|
|
# Check invite
|
|
if not use_invite(invite_token, email):
|
|
return {"ok": False, "error": "Недействительная или использованная ссылка-приглашение"}
|
|
|
|
# Check existing user
|
|
if get_user_by_email(email):
|
|
return {"ok": False, "error": "Пользователь с таким email уже существует"}
|
|
|
|
# Create user
|
|
pw_hash = hash_password(password)
|
|
create_user(email, pw_hash)
|
|
|
|
# Generate verification code
|
|
code = f"{secrets.randbelow(1000000):06d}"
|
|
set_verify_code(email, code)
|
|
|
|
return {"ok": True, "message": "Код подтверждения отправлен на email", "code": code}
|
|
|
|
|
|
def verify_email(email: str, code: str) -> dict:
|
|
"""Verify email with code. Returns {"ok": True} or {"ok": False, "error": ...}."""
|
|
from db import verify_user
|
|
if verify_user(email, code):
|
|
return {"ok": True, "message": "Email подтверждён. Можете войти."}
|
|
return {"ok": False, "error": "Неверный или просроченный код"}
|
|
|
|
|
|
def verify_token(token: str) -> str | None:
|
|
"""Return username if token is valid, else None."""
|
|
if not SECRET:
|
|
return None
|
|
try:
|
|
payload = jwt.decode(token, SECRET, algorithms=[ALGORITHM])
|
|
return payload.get("sub")
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def get_token_role(token: str) -> str:
|
|
"""Return role from token (admin/user)."""
|
|
if not SECRET:
|
|
return "user"
|
|
try:
|
|
payload = jwt.decode(token, SECRET, algorithms=[ALGORITHM])
|
|
return payload.get("role", "user")
|
|
except Exception:
|
|
return "user"
|