37 lines
1.1 KiB
Python
37 lines
1.1 KiB
Python
import hmac
|
|||
|
|
|
||
|
|
from cryptography.fernet import Fernet
|
||
|
|
from fastapi import Depends, HTTPException
|
||
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||
|
|
|
||
|
|
from app.config import get_settings
|
||
|
|
|
||
|
|
_bearer = HTTPBearer(auto_error=False)
|
||
|
|
|
||
|
|
|
||
|
|
def _fernet() -> Fernet:
|
||
|
|
key = get_settings().secret_key
|
||
|
|
if not key:
|
||
|
|
raise RuntimeError("SECRET_KEY не задан (ключ Fernet)")
|
||
|
|
return Fernet(key.encode())
|
||
|
|
|
||
|
|
|
||
|
|
def encrypt(value: str) -> str:
|
||
|
|
return _fernet().encrypt(value.encode()).decode()
|
||
|
|
|
||
|
|
|
||
|
|
def decrypt(token: str) -> str:
|
||
|
|
return _fernet().decrypt(token.encode()).decode()
|
||
|
|
|
||
|
|
|
||
|
|
def check_admin(user: str, password: str) -> bool:
|
||
|
|
s = get_settings()
|
||
|
|
ok_user = hmac.compare_digest(user.encode(), s.admin_user.encode())
|
||
|
|
ok_pass = hmac.compare_digest(password.encode(), s.admin_password.encode())
|
||
|
|
return ok_user and ok_pass
|
||
|
|
|
||
|
|
|
||
|
|
def require_api_token(cred: HTTPAuthorizationCredentials | None = Depends(_bearer)) -> None:
|
||
|
|
expected = get_settings().api_token
|
||
|
|
if cred is None or not hmac.compare_digest(cred.credentials.encode(), expected.encode()):
|
||
|
|
raise HTTPException(status_code=401, detail="Invalid or missing API token")
|