Spaces:
Sleeping
Sleeping
Download src/utils/auth.py from abdullah9873/backend-rag-chatbot: direct link, hf CLI and curl.
- Browser
- Download file 1.01 kB
-
https://huggingface.co/spaces/abdullah9873/backend-rag-chatbot/resolve/main/src/utils/auth.py
- Command line
-
hf download hf://spaces/abdullah9873/backend-rag-chatbot/src/utils/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/abdullah9873/backend-rag-chatbot/resolve/main/src/utils/auth.py
1.01 kB
| from jose import jwt, JWTError | |
| from datetime import datetime, timedelta | |
| from typing import Optional | |
| import os | |
| SECRET_KEY = os.getenv("SECRET_KEY", "super-secret-key") # Replace with a strong, random key in production | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 30 | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): | |
| to_encode = data.copy() | |
| if expires_delta: | |
| expire = datetime.utcnow() + expires_delta | |
| else: | |
| expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire}) | |
| encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| return encoded_jwt | |
| def verify_access_token(token: str, credentials_exception): | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| user_id: str = payload.get("sub") | |
| if user_id is None: | |
| raise credentials_exception | |
| return user_id | |
| except JWTError: | |
| raise credentials_exception | |