| import jwt | |
| from datetime import datetime, timedelta | |
| from cryptography.fernet import Fernet | |
| from backend.core.config import settings | |
| # Initialize Fernet for AES encryption | |
| cipher_suite = Fernet(settings.ENCRYPTION_KEY.encode()) | |
| def create_access_token(data: dict): | |
| """Generates a JWT token for user sessions.""" | |
| to_encode = data.copy() | |
| expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire}) | |
| encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM) | |
| return encoded_jwt | |
| def encrypt_hf_token(token: str) -> str: | |
| """Encrypts the Hugging Face token before saving to DB.""" | |
| return cipher_suite.encrypt(token.encode()).decode() | |
| def decrypt_hf_token(encrypted_token: str) -> str: | |
| """Decrypts the Hugging Face token for API usage.""" | |
| return cipher_suite.decrypt(encrypted_token.encode()).decode() | |