From 60417d459423fe9ea2ff5837cbca88b86f7c9f45 Mon Sep 17 00:00:00 2001 From: ramforth Date: Mon, 17 Nov 2025 00:10:47 +0100 Subject: [PATCH] Preparing storage of generated keys --- .env.example | 4 ++++ security.py | 21 ++++++++++++++------- 2 files changed, 18 insertions(+), 7 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..633d90b --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +# This is an example file. Copy it to .env and fill in your actual secrets. +# The .env file is ignored by Git and should NEVER be committed. + +ENCRYPTION_KEY="your_32_byte_url_safe_base64_encoded_key_goes_here" diff --git a/security.py b/security.py index 203d84c..edd41fa 100644 --- a/security.py +++ b/security.py @@ -6,20 +6,26 @@ from dotenv import load_dotenv # Load environment variables from a .env file for local development load_dotenv() -# It is CRITICAL that this key is set in your environment and kept secret. -# It should be a 32-url-safe-base64-encoded key. -ENCRYPTION_KEY = os.getenv("ENCRYPTION_KEY") +def _get_fernet_instance() -> Fernet: + """ + Helper function to get the Fernet instance. + This ensures the key is checked only when encryption/decryption is needed. + """ + # It is CRITICAL that this key is set in your environment and kept secret. + # It should be a 32-url-safe-base64-encoded key. + encryption_key = os.getenv("ENCRYPTION_KEY") -if not ENCRYPTION_KEY: - raise ValueError("ENCRYPTION_KEY is not set in the environment. Please generate a key and add it to your .env file.") + if not encryption_key: + raise ValueError("ENCRYPTION_KEY is not set in the environment. Please generate a key and add it to your .env file.") -# Ensure the key is in bytes for the Fernet instance -fernet = Fernet(ENCRYPTION_KEY.encode()) + # Ensure the key is in bytes for the Fernet instance + return Fernet(encryption_key.encode()) def encrypt_tokens(access_token: str, refresh_token: str) -> str: """ Combines access and refresh tokens into a JSON object, then encrypts it. """ + fernet = _get_fernet_instance() tokens = {"access_token": access_token, "refresh_token": refresh_token} tokens_json_string = json.dumps(tokens) encrypted_data = fernet.encrypt(tokens_json_string.encode()) @@ -29,6 +35,7 @@ def decrypt_tokens(encrypted_data_str: str) -> dict: """ Decrypts the token string back into a dictionary of tokens. """ + fernet = _get_fernet_instance() decrypted_data_bytes = fernet.decrypt(encrypted_data_str.encode()) tokens_json_string = decrypted_data_bytes.decode() return json.loads(tokens_json_string)