Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion django_email_learning/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.conf import settings
from django.db import models
from django.core.validators import MaxValueValidator
from django.core.exceptions import ImproperlyConfigured
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
Expand Down Expand Up @@ -79,7 +80,13 @@ def _fernet(self) -> Fernet:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(), length=32, salt=FIXED_SALT, iterations=100000
)
key = base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode()))
try:
secret = settings.DJANGO_EMAIL_LEARNING["ENCRYPTION_SECRET_KEY"]
except (AttributeError, KeyError):
raise ImproperlyConfigured(
"DJANGO_EMAIL_LEARNING['ENCRYPTION_SECRET_KEY'] must be set in settings.py"
)
key = base64.urlsafe_b64encode(kdf.derive(secret.encode()))
return Fernet(key)

def _encrypt_password(self, password: str) -> str:
Expand Down
4 changes: 4 additions & 0 deletions django_service/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@
}
}

DJANGO_EMAIL_LEARNING = {
"ENCRYPTION_SECRET_KEY": "your-very-secure-and-random-key",
}

LOGGING = {
"version": 1,
"disable_existing_loggers": False,
Expand Down
27 changes: 27 additions & 0 deletions tests/test_models/test_imap_connection.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django_email_learning.models import ImapConnection
from django.core.exceptions import ImproperlyConfigured
import pytest


Expand Down Expand Up @@ -39,3 +40,29 @@ def test_imap_invalid_server_validation(invalid_server, imap_connection):
def test_imap_valid_server_validation(valid_server, imap_connection):
imap_connection.server = valid_server
imap_connection.full_clean() # Should not raise


def test_raise_improperly_configured_if_django_email_learning_config_missing(
settings, db
):
delattr(settings, "DJANGO_EMAIL_LEARNING")
with pytest.raises(ImproperlyConfigured):
ImapConnection.objects.create(
server="imap.example.com",
port=993,
email="[email protected]",
password="my_secret_password",
organization_id=1,
)


def test_raise_improperly_configured_if_encryption_key_missing(settings, db):
settings.DJANGO_EMAIL_LEARNING = {}
with pytest.raises(ImproperlyConfigured):
ImapConnection.objects.create(
server="imap.example.com",
port=993,
email="[email protected]",
password="my_secret_password",
organization_id=1,
)