Primakov Alexandr Alexandrovich 09cdd06307 init
2025-10-12 23:15:09 +03:00

41 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Utility functions"""
from cryptography.fernet import Fernet, InvalidToken
from app.config import settings
import base64
def get_cipher():
"""Get Fernet cipher for encryption"""
# Use first 32 bytes of encryption key, base64 encoded
key = settings.encryption_key.encode()[:32]
# Pad to 32 bytes if needed
key = key.ljust(32, b'0')
# Base64 encode for Fernet
key_b64 = base64.urlsafe_b64encode(key)
return Fernet(key_b64)
def encrypt_token(token: str) -> str:
"""Encrypt API token"""
cipher = get_cipher()
return cipher.encrypt(token.encode()).decode()
def decrypt_token(encrypted_token: str) -> str:
"""Decrypt API token
Raises:
ValueError: If token cannot be decrypted (wrong encryption key)
"""
cipher = get_cipher()
try:
return cipher.decrypt(encrypted_token.encode()).decode()
except InvalidToken:
raise ValueError(
"Не удалось расшифровать API токен. "
"Возможно, ключ шифрования (ENCRYPTION_KEY) был изменен. "
"Пожалуйста, обновите API токен для этого репозитория."
)