Spaces:
Running
Running
Download backend/app/security.py from HeshamXOR/MalwareGuard: direct link, hf CLI and curl.
- Browser
- Download file 1.53 kB
-
https://huggingface.co/spaces/HeshamXOR/MalwareGuard/resolve/main/backend/app/security.py
- Command line
-
hf download hf://spaces/HeshamXOR/MalwareGuard/backend/app/security.py
-
curl -L -o security.py https://huggingface.co/spaces/HeshamXOR/MalwareGuard/resolve/main/backend/app/security.py
1.53 kB
| """Password hashing and JWT helpers.""" | |
| from datetime import datetime, timedelta, timezone | |
| import base64 | |
| import hashlib | |
| import hmac | |
| import os | |
| from typing import Any | |
| from jose import JWTError, jwt | |
| from .config import settings | |
| ALGORITHM = "HS256" | |
| def hash_password(password: str) -> str: | |
| salt = os.urandom(16) | |
| digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 120_000) | |
| return f"pbkdf2_sha256${base64.b64encode(salt).decode()}${base64.b64encode(digest).decode()}" | |
| def verify_password(password: str, stored_hash: str) -> bool: | |
| try: | |
| scheme, salt_b64, digest_b64 = stored_hash.split("$", 2) | |
| if scheme != "pbkdf2_sha256": | |
| return False | |
| salt = base64.b64decode(salt_b64) | |
| expected = base64.b64decode(digest_b64) | |
| actual = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 120_000) | |
| return hmac.compare_digest(actual, expected) | |
| except Exception: | |
| return False | |
| def create_access_token(subject: str, extra: dict[str, Any] | None = None) -> str: | |
| expires = datetime.now(timezone.utc) + timedelta(minutes=settings.jwt_expire_minutes) | |
| payload: dict[str, Any] = {"sub": subject, "exp": expires} | |
| if extra: | |
| payload.update(extra) | |
| return jwt.encode(payload, settings.jwt_secret_key, algorithm=ALGORITHM) | |
| def decode_access_token(token: str) -> dict[str, Any] | None: | |
| try: | |
| return jwt.decode(token, settings.jwt_secret_key, algorithms=[ALGORITHM]) | |
| except JWTError: | |
| return None | |