This commit is contained in:
Primakov Alexandr Alexandrovich
2025-10-12 23:15:09 +03:00
commit 09cdd06307
88 changed files with 15007 additions and 0 deletions
+40
View File
@@ -0,0 +1,40 @@
"""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 токен для этого репозитория."
)