Download server/security.py from ag235772/Workhub: direct link, hf CLI and curl.
- Browser
- Download file 2.44 kB
-
https://huggingface.co/spaces/ag235772/Workhub/resolve/main/server/security.py
- Command line
-
hf download hf://spaces/ag235772/Workhub/server/security.py
-
curl -L -o security.py https://huggingface.co/spaces/ag235772/Workhub/resolve/main/server/security.py
2.44 kB
| """Secrets, TOTP and QR helpers.""" | |
| import base64, hashlib, hmac, io, os, re, secrets, time | |
| import pyotp | |
| import qrcode | |
| import qrcode.image.svg | |
| from cryptography.fernet import Fernet | |
| DATA_DIR = os.environ.get("HUB_SERVER_DATA", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "server_data")) | |
| ALLOWED_DOMAIN = os.environ.get("ALLOWED_DOMAIN", "indusface.com").lower().lstrip("@") | |
| ISSUER = "Indusface Work Hub" | |
| def app_secret(): | |
| s = os.environ.get("APP_SECRET") | |
| if s: | |
| return s | |
| os.makedirs(DATA_DIR, exist_ok=True) | |
| p = os.path.join(DATA_DIR, ".secret") | |
| if not os.path.exists(p): # dev convenience only; production must set APP_SECRET | |
| with open(p, "w") as f: | |
| f.write(secrets.token_urlsafe(48)) | |
| os.chmod(p, 0o600) | |
| return open(p).read().strip() | |
| def _fernet(): | |
| return Fernet(base64.urlsafe_b64encode(hashlib.sha256(("totp|" + app_secret()).encode()).digest())) | |
| def encrypt(s): | |
| return _fernet().encrypt(s.encode()).decode() | |
| def decrypt(s): | |
| return _fernet().decrypt(s.encode()).decode() | |
| def hash_token(t): | |
| return hashlib.sha256(t.encode()).hexdigest() | |
| def new_device_token(): | |
| return secrets.token_urlsafe(32) | |
| def allowed_email(email): | |
| """Only real @<ALLOWED_DOMAIN> addresses; rejects guest (#EXT#) and look-alike domains.""" | |
| e = (email or "").strip().lower() | |
| return bool(re.fullmatch(r"[a-z0-9][a-z0-9._%+\-']*@" + re.escape(ALLOWED_DOMAIN), e)) and "#ext#" not in e | |
| def mask_email(e): | |
| u, _, d = e.partition("@") | |
| return (u[:1] + "***@" + d) if u else "" | |
| def new_totp_secret(): | |
| return pyotp.random_base32() | |
| def totp_uri(secret, email): | |
| return pyotp.TOTP(secret).provisioning_uri(name=email, issuer_name=ISSUER) | |
| def qr_data_uri(text): | |
| img = qrcode.make(text, image_factory=qrcode.image.svg.SvgPathImage, box_size=10) | |
| buf = io.BytesIO() | |
| img.save(buf) | |
| return "data:image/svg+xml;base64," + base64.b64encode(buf.getvalue()).decode() | |
| def verify_totp(secret, code, last_step=0): | |
| """Return the accepted time-step (for replay protection) or None.""" | |
| code = re.sub(r"\s+", "", code or "") | |
| if not re.fullmatch(r"\d{6}", code): | |
| return None | |
| t = pyotp.TOTP(secret) | |
| cur = int(time.time() // 30) | |
| for step in (cur, cur - 1, cur + 1): | |
| if step > last_step and hmac.compare_digest(t.generate_otp(step), code): | |
| return step | |
| return None | |