Download auth.py from Ashish-K/stepwise: direct link, hf CLI and curl.
- Browser
- Download file 2.91 kB
-
https://huggingface.co/spaces/Ashish-K/stepwise/resolve/main/auth.py
- Command line
-
hf download hf://spaces/Ashish-K/stepwise/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Ashish-K/stepwise/resolve/main/auth.py
2.91 kB
| """Accounts for StepWise: admin, parent and child logins. | |
| Passwords are stored only as scrypt hashes. A login returns a signed token that the | |
| browser keeps and sends as "Authorization: Bearer <token>". The token carries the | |
| user id, an expiry and the user's token version; changing or resetting a password | |
| bumps the version, which signs that user out everywhere. | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import hashlib | |
| import hmac | |
| import json | |
| import os | |
| import secrets | |
| import time | |
| TOKEN_DAYS = 60 | |
| _N, _R, _P = 2 ** 14, 8, 1 | |
| def _secret() -> bytes: | |
| s = os.environ.get("SESSION_SECRET") | |
| if s: | |
| return s.encode() | |
| # Stable across restarts without a new Space secret: derived from secrets the Space already has. | |
| seed = (os.environ.get("ACCESS_KEY", "") + "|" + os.environ.get("HF_TOKEN", "") + "|stepwise-session").encode() | |
| return hashlib.sha256(seed).digest() | |
| SECRET = _secret() | |
| def hash_password(pw: str) -> str: | |
| salt = secrets.token_bytes(16) | |
| h = hashlib.scrypt(pw.encode(), salt=salt, n=_N, r=_R, p=_P, dklen=32) | |
| return f"scrypt${_N}${_R}${_P}${salt.hex()}${h.hex()}" | |
| def verify_password(pw: str, stored: str) -> bool: | |
| try: | |
| _, n, r, p, salt, h = stored.split("$") | |
| got = hashlib.scrypt(pw.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p), dklen=32) | |
| return hmac.compare_digest(got.hex(), h) | |
| except (ValueError, TypeError): | |
| return False | |
| def _b64(b: bytes) -> str: | |
| return base64.urlsafe_b64encode(b).rstrip(b"=").decode() | |
| def _unb64(s: str) -> bytes: | |
| return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) | |
| def make_token(uid: str, version: int) -> str: | |
| body = _b64(json.dumps({"u": uid, "v": version, "exp": int(time.time()) + TOKEN_DAYS * 86400}).encode()) | |
| sig = _b64(hmac.new(SECRET, body.encode(), hashlib.sha256).digest()) | |
| return f"{body}.{sig}" | |
| def read_token(token: str) -> dict | None: | |
| try: | |
| body, sig = token.split(".") | |
| want = _b64(hmac.new(SECRET, body.encode(), hashlib.sha256).digest()) | |
| if not hmac.compare_digest(sig, want): | |
| return None | |
| data = json.loads(_unb64(body)) | |
| return data if data.get("exp", 0) > time.time() else None | |
| except (ValueError, TypeError, json.JSONDecodeError): | |
| return None | |
| class LoginLimiter: | |
| """At most 8 wrong passwords per username in 15 minutes.""" | |
| def __init__(self, limit: int = 8, window: int = 900) -> None: | |
| self.limit, self.window, self.fails = limit, window, {} | |
| def blocked(self, name: str) -> bool: | |
| t = time.time() | |
| self.fails[name] = [x for x in self.fails.get(name, []) if t - x < self.window] | |
| return len(self.fails[name]) >= self.limit | |
| def fail(self, name: str) -> None: | |
| self.fails.setdefault(name, []).append(time.time()) | |
| def clear(self, name: str) -> None: | |
| self.fails.pop(name, None) | |