Skip to content

Home Information - Your home, your data, organized.

Python

Added handling of case where emails are not configured.

Anthony Cassandra2198e8af523c
diff --git a/src/hi/apps/common/email_sender.py b/src/hi/apps/common/email_sender.py
deleted file mode 100644
index fcdf06c5..00000000
--- a/src/hi/apps/common/email_sender.py
+++ /dev/null
@@ -1,63 +0,0 @@
-from dataclasses import dataclass, field
-import logging
-from typing import Dict, List
-
-from django.conf import settings
-from django.http.request import HttpRequest
-
-from hi.apps.common.email_utils import send_html_email
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass
-class EmailSenderData:
- request : HttpRequest
- subject_template_name : str
- message_text_template_name : str
- message_html_template_name : str
- to_email_address : str
- from_email_address : str = None # Defaults to system-wide FROM
- template_context : Dict[str, str] = field( default_factory = dict )
- files : List = None # For attachments
- non_blocking : bool = True
-
- # For testing
- override_to_email_address : str = None
-
-
-class EmailSender:
- """ For sending a single email message. """
-
- def __init__( self, data : EmailSenderData ):
- self._data = data
- return
-
- def send( self):
-
- context = self._data.template_context
- self._add_base_url( context = context )
-
- effective_to_email_address = self._data.to_email_address
- if self._data.override_to_email_address:
- effective_to_email_address = self._data.override_to_email_address
-
- send_html_email(
- request = self._data.request,
- subject_template_name = self._data.subject_template_name,
- message_text_template_name = self._data.message_text_template_name,
- message_html_template_name = self._data.message_html_template_name,
- to_email_addresses = [ effective_to_email_address ],
- from_email_address = self._data.from_email_address,
- context = context,
- files = self._data.files,
- non_blocking = self._data.non_blocking,
- )
- return
-
- def _add_base_url( self, context : Dict ):
- if self._data.request:
- context['BASE_URL'] = self._data.request.build_absolute_uri('/')[:-1]
- else:
- context['BASE_URL'] = settings.BASE_URL_FOR_EMAIL_LINKS
- return
diff --git a/src/hi/apps/notify/admin.py b/src/hi/apps/notify/admin.py
new file mode 100644
index 00000000..286af863
--- /dev/null
+++ b/src/hi/apps/notify/admin.py
@@ -0,0 +1,16 @@
+from django.contrib import admin
+
+from . import models
+
+
[email protected](models.UnsubscribedEmail)
+class UnsubscribedEmailAdmin(admin.ModelAdmin):
+
+ show_full_result_count = False
+
+ list_display = (
+ 'email',
+ 'created_datetime',
+ )
+
+ search_fields = ['email']
diff --git a/src/hi/apps/notify/email_sender.py b/src/hi/apps/notify/email_sender.py
index e631860d..7621fcef 100644
--- a/src/hi/apps/notify/email_sender.py
+++ b/src/hi/apps/notify/email_sender.py
@@ -1,15 +1,17 @@
from asgiref.sync import sync_to_async
+from dataclasses import dataclass, field
import logging
-from typing import Dict
+from typing import Dict, List, Union
from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.http import HttpRequest
from django.urls import reverse
from hi.apps.common.email_utils import send_html_email
from hi.apps.common.utils import hash_with_seed
from .models import UnsubscribedEmail
-from .transient_models import EmailData
logger = logging.getLogger(__name__)
@@ -18,6 +20,44 @@ class UnsubscribedEmailError(Exception):
pass
+@dataclass
+class EmailData:
+ """
+ Input data format for sending emails with EmailSender. Caller defines
+ the three required templates for formatting the email. The email sender
+ will create a template context that includes the following variables
+ that should be used in the email:
+
+ BASE_URL - Use this to forms any needed site links.
+ HOME_URL - Url to the site's main landing page page.
+ UNSUBSCRIBE_URL - Include as best practice if you send email more broadly.
+
+ The templates are best defined by extending some pre-defined base
+ templates to make all emails have a consistent formatting. e.g.,
+ Unsubscribe URL appearing in footer.
+ """
+
+ # Set the request to None for background tasks, but also make sure
+ # settings.BASE_URL_FOR_EMAIL_LINKS is set.
+ #
+ request : HttpRequest
+
+ subject_template_name : str
+ message_text_template_name : str
+ message_html_template_name : str
+ to_email_address : Union[ str, List[ str ]]
+
+ # Defaults to system-wide settings.DEFAULT_FROM_EMAIL
+ from_email_address : str = None
+
+ template_context : Dict[str, str] = field( default_factory = dict )
+ files : List = None # For attachments
+ non_blocking : bool = True
+
+ # For testing (can use the unsubscribe link to test for the original intended "to" email)
+ override_to_email_address : str = None
+
+
class EmailSender:
""" For sending a single email message. """
@@ -39,6 +79,7 @@ class EmailSender:
return
def _send_helper(self):
+ self._ensure_email_configured()
context = self._data.template_context
self._add_base_url( context = context )
@@ -101,3 +142,15 @@ class EmailSender:
raise UnsubscribedEmailError( f'Email address is unsubscribed for {email_address}' )
return
+ def _ensure_email_configured( self ):
+ for setting_name in [ 'EMAIL_BACKEND',
+ 'EMAIL_HOST',
+ 'EMAIL_PORT',
+ 'EMAIL_HOST_USER',
+ 'DEFAULT_FROM_EMAIL',
+ 'SERVER_EMAIL' ]:
+ email_setting = getattr( settings, setting_name )
+ if not email_setting:
+ raise ImproperlyConfigured( f'Email is not configured. Missing "{setting_name}".' )
+ continue
+ return
diff --git a/src/hi/apps/notify/notification_manager.py b/src/hi/apps/notify/notification_manager.py
index d56c5227..19d14f11 100644
--- a/src/hi/apps/notify/notification_manager.py
+++ b/src/hi/apps/notify/notification_manager.py
@@ -6,8 +6,8 @@ from hi.apps.common.utils import str_to_bool
from hi.apps.config.settings_manager import SettingsManager
from hi.apps.notify.notification_queue import NotificationQueue
-from .email_sender import EmailSender
-from .transient_models import EmailData, Notification, NotificationItem
+from .email_sender import EmailData, EmailSender
+from .transient_models import Notification, NotificationItem
from .settings import NotifySetting
logger = logging.getLogger(__name__)
diff --git a/src/hi/apps/notify/transient_models.py b/src/hi/apps/notify/transient_models.py
index 5cfefc66..8affe159 100644
--- a/src/hi/apps/notify/transient_models.py
+++ b/src/hi/apps/notify/transient_models.py
@@ -15,41 +15,3 @@ class NotificationItem:
class Notification:
title : str
item_list : List[ NotificationItem ]
-
-
-@dataclass
-class EmailData:
- """
- Input data format for sending emails with EmailSender. Caller defines
- the three required templates for formatting the email. The email sender
- will create a template context that includes the following variables
- that should be used in the email:
-
- BASE_URL - Use this to forms any needed site links.
- HOME_URL - Url to the site's main landing page page.
- UNSUBSCRIBE_URL - Include as best practice if you send email more broadly.
-
- The templates are best defined by extending some pre-defined base
- templates to make all emails have a consistent formatting. e.g.,
- Unsubscribe URL appearing in footer.
- """
-
- # Set the request to None for background tasks, but also make sure
- # settings.BASE_URL_FOR_EMAIL_LINKS is set.
- #
- request : HttpRequest
-
- subject_template_name : str
- message_text_template_name : str
- message_html_template_name : str
- to_email_address : Union[ str, List[ str ]]
-
- # Defaults to system-wide settings.DEFAULT_FROM_EMAIL
- from_email_address : str = None
-
- template_context : Dict[str, str] = field( default_factory = dict )
- files : List = None # For attachments
- non_blocking : bool = True
-
- # For testing (can use the unsubscribe link to test for the original intended "to" email)
- override_to_email_address : str = None
diff --git a/src/hi/apps/user/signin_manager.py b/src/hi/apps/user/signin_manager.py
index dc8d0150..784a6ed8 100644
--- a/src/hi/apps/user/signin_manager.py
+++ b/src/hi/apps/user/signin_manager.py
@@ -5,7 +5,7 @@ from django.http import HttpRequest
from django.urls import reverse
from hi.apps.common.singleton import Singleton
-from hi.apps.common.email_sender import EmailSender, EmailSenderData
+from hi.apps.notify.email_sender import EmailData, EmailSender
from .transient_models import UserAuthenticationData
@@ -14,6 +14,10 @@ logger = logging.getLogger(__name__)
class SigninManager( Singleton ):
+ SIGNIN_SUBJECT_TEMPLATE_NAME = 'user/emails/signin_magic_link_subject.txt'
+ SIGNIN_MESSAGE_TEXT_TEMPLATE_NAME = 'user/emails/signin_magic_link_message.txt'
+ SIGNIN_MESSAGE_HTML_TEMPLATE_NAME = 'user/emails/signin_magic_link_message.html'
+
def __init_singleton__(self):
return
@@ -21,22 +25,6 @@ class SigninManager( Singleton ):
request : HttpRequest,
user_auth_data : UserAuthenticationData ):
- _ = self.send_verify_email_helper(
- request = request,
- user_auth_data = user_auth_data,
- subject_template_name = 'user/emails/signin_magic_link_subject.txt',
- message_text_template_name = 'user/emails/signin_magic_link_message.txt',
- message_html_template_name ='user/emails/signin_magic_link_message.html',
- )
- return
-
- def send_verify_email_helper( self,
- request : HttpRequest,
- user_auth_data : UserAuthenticationData,
- subject_template_name : str,
- message_text_template_name : str,
- message_html_template_name : str,
- ):
to_email_address = user_auth_data.email_address
page_url = request.build_absolute_uri(
reverse( 'user_signin_magic_link',
@@ -48,11 +36,11 @@ class SigninManager( Singleton ):
'page_url': page_url,
'magic_code': user_auth_data.magic_code,
}
- email_sender_data = EmailSenderData(
+ email_sender_data = EmailData(
request = request,
- subject_template_name = subject_template_name,
- message_text_template_name = message_text_template_name,
- message_html_template_name = message_html_template_name,
+ subject_template_name = self.SIGNIN_SUBJECT_TEMPLATE_NAME,
+ message_text_template_name = self.SIGNIN_MESSAGE_TEXT_TEMPLATE_NAME,
+ message_html_template_name = self.SIGNIN_MESSAGE_HTML_TEMPLATE_NAME,
to_email_address = to_email_address,
template_context = email_template_context,
non_blocking = True,
diff --git a/src/hi/middleware.py b/src/hi/middleware.py
index 92b335f8..d6c93586 100644
--- a/src/hi/middleware.py
+++ b/src/hi/middleware.py
@@ -3,6 +3,7 @@ import logging
from django.conf import settings
from django.core.exceptions import (
BadRequest,
+ ImproperlyConfigured,
PermissionDenied,
SuspiciousOperation,
)
@@ -58,6 +59,8 @@ class ExceptionMiddleware(object):
if isinstance( exception, BadRequest ):
return views.bad_request_response(request, message=str(exception))
+ if isinstance( exception, ImproperlyConfigured ):
+ return views.improperly_configured_response(request, message=str(exception))
if isinstance( exception, SuspiciousOperation ):
return views.bad_request_response(request, message=str(exception))
if isinstance( exception, PermissionDenied ):
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 95c3d8e0..30c52f18 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -375,7 +375,7 @@ else:
#
BASE_URL_FOR_EMAIL_LINKS = 'https://{SITE_DOMAIN}'
-# When tests functionalityt requires knowing if in unit test context.
+# When tests functionality requires knowing if in unit test context.
UNIT_TESTING = False
# In development and debugging, the debug noise and interference from the
diff --git a/src/hi/templates/modals/improperly_configured.html b/src/hi/templates/modals/improperly_configured.html
new file mode 100644
index 00000000..f6d32afe
--- /dev/null
+++ b/src/hi/templates/modals/improperly_configured.html
@@ -0,0 +1,5 @@
+{% extends "modals/error_base.html" %}
+
+{% block title_text %}
+Improperly Configured
+{% endblock %}
diff --git a/src/hi/templates/pages/bad_request.html b/src/hi/templates/pages/bad_request.html
index d5c7f033..f525326f 100644
--- a/src/hi/templates/pages/bad_request.html
+++ b/src/hi/templates/pages/bad_request.html
@@ -1,5 +1,5 @@
{% extends "pages/error_base.html" %}
{% block title %}
-<span id="hi-edit-required-page" >Bad Request</span>
+<span id="hi-bad-request-page" >Bad Request</span>
{% endblock %}
diff --git a/src/hi/templates/pages/improperly_configured.html b/src/hi/templates/pages/improperly_configured.html
new file mode 100644
index 00000000..91bb9226
--- /dev/null
+++ b/src/hi/templates/pages/improperly_configured.html
@@ -0,0 +1,5 @@
+{% extends "pages/error_base.html" %}
+
+{% block title %}
+<span id="hi-improperly-configured-page" >Improperly Configured</span>
+{% endblock %}
diff --git a/src/hi/templates/pages/internal_error.html b/src/hi/templates/pages/internal_error.html
index 08f03a62..94939c14 100644
--- a/src/hi/templates/pages/internal_error.html
+++ b/src/hi/templates/pages/internal_error.html
@@ -1,5 +1,5 @@
{% extends "pages/error_base.html" %}
{% block title %}
-<span id="hi-edit-required-page" >Internal Error</span>
+<span id="hi-internal-error-page" >Internal Error</span>
{% endblock %}
diff --git a/src/hi/templates/pages/method_not_allowed.html b/src/hi/templates/pages/method_not_allowed.html
index 4c161efc..d959a93c 100644
--- a/src/hi/templates/pages/method_not_allowed.html
+++ b/src/hi/templates/pages/method_not_allowed.html
@@ -1,5 +1,5 @@
{% extends "pages/error_base.html" %}
{% block title %}
-<span id="hi-edit-required-page" >Method Not Allowed</span>
+<span id="hi-method-not-allowed-page" >Method Not Allowed</span>
{% endblock %}
diff --git a/src/hi/templates/pages/not_authorized.html b/src/hi/templates/pages/not_authorized.html
index 3c695f37..75911c15 100644
--- a/src/hi/templates/pages/not_authorized.html
+++ b/src/hi/templates/pages/not_authorized.html
@@ -1,5 +1,5 @@
{% extends "pages/error_base.html" %}
{% block title %}
-<span id="hi-edit-required-page" >Not Authorized</span>
+<span id="hi-not-authorized-page-page" >Not Authorized</span>
{% endblock %}
diff --git a/src/hi/templates/pages/page_not_found.html b/src/hi/templates/pages/page_not_found.html
index e92e7e1a..dc42daa1 100644
--- a/src/hi/templates/pages/page_not_found.html
+++ b/src/hi/templates/pages/page_not_found.html
@@ -1,5 +1,5 @@
{% extends "pages/error_base.html" %}
{% block title %}
-<span id="hi-edit-required-page" >Page Not Found</span>
+<span id="hi-page-not-found-page" >Page Not Found</span>
{% endblock %}
diff --git a/src/hi/templates/pages/transient_error.html b/src/hi/templates/pages/transient_error.html
index 8840e99b..477fbb1a 100644
--- a/src/hi/templates/pages/transient_error.html
+++ b/src/hi/templates/pages/transient_error.html
@@ -1,5 +1,5 @@
{% extends "pages/error_base.html" %}
{% block title %}
-<span id="hi-edit-required-page" >Transient Error</span>
+<span id="hi-transient-error-page" >Transient Error</span>
{% endblock %}
diff --git a/src/hi/views.py b/src/hi/views.py
index 9eea4859..20219510 100644
--- a/src/hi/views.py
+++ b/src/hi/views.py
@@ -58,6 +58,18 @@ def bad_request_response( request, message : str = None, force_json : bool = Fal
context = context )
+def improperly_configured_response( request, message : str = None, force_json : bool = False ):
+ if not message:
+ message = 'Improperly configured.'
+ context = { 'message': message }
+ return error_response( request = request,
+ sync_template_name = "pages/improperly_configured.html",
+ async_template_name = "modals/improperly_configured.html",
+ status_code = 501,
+ force_json = force_json,
+ context = context )
+
+
def not_authorized_response( request, message : str = None, force_json : bool = False ):
if not message:
message = 'Not authorized.'