Spaces:
Sleeping
Sleeping
Download Backend/routes/auth_utils.py from smit9604/ExamCraftAI: direct link, hf CLI and curl.
- Browser
- Download file 1.31 kB
-
https://huggingface.co/spaces/smit9604/ExamCraftAI/resolve/main/Backend/routes/auth_utils.py
- Command line
-
hf download hf://spaces/smit9604/ExamCraftAI/Backend/routes/auth_utils.py
-
curl -L -o auth_utils.py https://huggingface.co/spaces/smit9604/ExamCraftAI/resolve/main/Backend/routes/auth_utils.py
1.31 kB
| import os | |
| import functools | |
| from flask import request, jsonify | |
| from supabase import create_client, Client | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv(dotenv_path='.env.local') | |
| # Initialize Supabase | |
| supabase_url: str = os.environ.get("SUPABASE_URL", "") | |
| supabase_key: str = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "") | |
| supabase: Client = create_client(supabase_url, supabase_key) if supabase_url and supabase_key else None | |
| def get_user_id(req): | |
| """Verifies token and returns the user's ID.""" | |
| auth_header = req.headers.get("Authorization") | |
| if auth_header and auth_header.startswith("Bearer "): | |
| token = auth_header.split(" ")[1] | |
| if supabase: | |
| try: | |
| user_res = supabase.auth.get_user(token) | |
| if user_res and user_res.user: | |
| return user_res.user.id | |
| except Exception as e: | |
| print(f"Auth verification error: {e}") | |
| return None | |
| def token_required(f): | |
| """Decorator to protect routes requiring authentication.""" | |
| def decorated(*args, **kwargs): | |
| user_id = get_user_id(request) | |
| if not user_id: | |
| return jsonify({"error": "Unauthorized"}), 401 | |
| return f(user_id, *args, **kwargs) | |
| return decorated | |