Spaces:
Running
Running
Nrighton233j
Add JWT + internal-secret auth (before_request guard) matching download server pattern
0be5e7a Download auth.py from Nrighton233j/Api-cache: direct link, hf CLI and curl.
- Browser
- Download file 800 Bytes
-
https://huggingface.co/spaces/Nrighton233j/Api-cache/resolve/main/auth.py
- Command line
-
hf download hf://spaces/Nrighton233j/Api-cache/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Nrighton233j/Api-cache/resolve/main/auth.py
800 Bytes
| import os | |
| import jwt | |
| from flask import request, jsonify | |
| INTERNAL_SECRET = os.environ.get("INTERNAL_SECRET", "changeme") | |
| JWT_SECRET = os.environ.get("JWT_SECRET", "changeme-jwt") | |
| def get_authenticated_user_id(): | |
| """Extracts + verifies the user_id from a Bearer JWT issued by | |
| B24_Database's /users/login. Returns None if missing/invalid.""" | |
| auth_header = request.headers.get("Authorization", "") | |
| if not auth_header.startswith("Bearer "): | |
| return None | |
| token = auth_header[len("Bearer "):] | |
| try: | |
| payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"]) | |
| return payload.get("user_id") | |
| except jwt.PyJWTError: | |
| return None | |
| def check_internal_secret(): | |
| secret = request.headers.get("X-Internal-Auth") | |
| return secret == INTERNAL_SECRET | |