100 lines
3.3 KiB
Python
100 lines
3.3 KiB
Python
import hashlib
|
|
import os
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Optional
|
|
|
|
from fastapi import Depends, Header, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
|
|
from bd import Settings
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
SECRET_KEY: str = os.getenv("SECRET_KEY", "")
|
|
if not SECRET_KEY:
|
|
import secrets
|
|
SECRET_KEY = secrets.token_hex(32)
|
|
print("WARNING: SECRET_KEY not set in environment. Using a random key — tokens will be invalidated on restart!")
|
|
|
|
ALGORITHM = "HS256"
|
|
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60"))
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
|
|
|
|
|
def _prehash(password: str) -> str:
|
|
"""SHA-256 пред-хеш чтобы обойти 72-байтовый лимит bcrypt."""
|
|
return hashlib.sha256(password.encode()).hexdigest()
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return pwd_context.hash(_prehash(password))
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
return pwd_context.verify(_prehash(plain), hashed)
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
|
to_encode = data.copy()
|
|
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
|
to_encode["exp"] = expire
|
|
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
|
|
|
|
|
def _get_session():
|
|
settings = Settings()
|
|
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
|
return sessionmaker(bind=engine, future=True)
|
|
|
|
|
|
def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
"""FastAPI dependency: валидирует Bearer-токен и возвращает объект User."""
|
|
credentials_exc = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
try:
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
user_id: str = payload.get("sub")
|
|
if user_id is None:
|
|
raise credentials_exc
|
|
except JWTError:
|
|
raise credentials_exc
|
|
|
|
from bd.tables.users import User
|
|
|
|
try:
|
|
uid = uuid.UUID(user_id)
|
|
except Exception:
|
|
raise credentials_exc
|
|
|
|
Session = _get_session()
|
|
with Session() as session:
|
|
user = session.get(User, uid)
|
|
if user is None:
|
|
raise credentials_exc
|
|
# detach from session so object can be used outside
|
|
session.expunge(user)
|
|
return user
|
|
|
|
|
|
def require_admin_key(x_admin_key: Optional[str] = Header(default=None)):
|
|
"""FastAPI dependency: проверяет секретный ключ администратора (заголовок X-Admin-Key)."""
|
|
admin_key = os.getenv("ADMIN_KEY", "")
|
|
if not admin_key:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="Admin access is disabled: ADMIN_KEY not configured",
|
|
)
|
|
if x_admin_key != admin_key:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Invalid admin key",
|
|
)
|