Skip to content

Home Information - Your home, your data, organized.

Python

Added sign in email to tests UI pages. Test for viewing and sending.

Anthony Cassandra8db68bae54f7
diff --git a/src/hi/apps/config/settings_manager.py b/src/hi/apps/config/settings_manager.py
index 950ba7e2..d907fd31 100644
--- a/src/hi/apps/config/settings_manager.py
+++ b/src/hi/apps/config/settings_manager.py
@@ -1,6 +1,6 @@
from datetime import datetime
import logging
-from threading import local
+from threading import local, Lock
from typing import List
from django.apps import apps
@@ -27,6 +27,7 @@ class SettingsManager( Singleton ):
self._subsystem_list = list()
self._attribute_value_map = dict()
self._change_listeners = list()
+ self._attributes_lock = Lock()
app_settings_list = self._discover_app_settings()
self._subsystem_list = self._load_or_create_settings( app_settings_list = app_settings_list )
@@ -34,14 +35,19 @@ class SettingsManager( Singleton ):
return
def reload(self):
- self._attribute_value_map = dict()
- for subsystem in self._subsystem_list:
- for subsystem_attribute in subsystem.attributes.all():
- attr_type = subsystem_attribute.setting_key
- self._attribute_value_map[attr_type] = subsystem_attribute.value
+ self._attributes_lock.acquire()
+ try:
+ self._attribute_value_map = dict()
+ for subsystem in self._subsystem_list:
+ subsystem.refresh_from_db()
+ for subsystem_attribute in subsystem.attributes.all():
+ attr_type = subsystem_attribute.setting_key
+ self._attribute_value_map[attr_type] = subsystem_attribute.value
+ continue
continue
- continue
-
+ finally:
+ self._attributes_lock.release()
+
self._notify_change_listeners()
return
@@ -69,6 +75,7 @@ class SettingsManager( Singleton ):
return self._attribute_value_map.get( setting_enum.key )
def set_setting_value( self, setting_enum : SettingEnum, value : str ):
+ self._attributes_lock.acquire()
try:
db_attribute = SubsystemAttribute.objects.get(
setting_key = setting_enum.key,
@@ -79,6 +86,8 @@ class SettingsManager( Singleton ):
except SubsystemAttribute.DoesNotExist:
raise KeyError( f'No setting "{setting_enum.name}" found.' )
+ finally:
+ self._attributes_lock.release()
return
def _discover_app_settings(self) -> List[ AppSettings ]:
diff --git a/src/hi/apps/notify/notification_manager.py b/src/hi/apps/notify/notification_manager.py
index 19d14f11..f267c3fe 100644
--- a/src/hi/apps/notify/notification_manager.py
+++ b/src/hi/apps/notify/notification_manager.py
@@ -60,7 +60,7 @@ class NotificationManager(Singleton):
)
email_address_list = parse_emails_from_text( text = email_addresses_str )
if not email_address_list:
- logger.debug( f'No valid notification emails defined. Ignoring: {notification}.' )
+ logger.info( f'No valid notification emails defined. Ignoring: {notification}.' )
return False
logger.debug( f'Sending notification email to "{email_address_list}": {notification}.' )
diff --git a/src/hi/apps/notify/templates/notify/emails/base_email_message.html b/src/hi/apps/notify/templates/notify/emails/base_email_message.html
index fab88b4d..79ba7b89 100644
--- a/src/hi/apps/notify/templates/notify/emails/base_email_message.html
+++ b/src/hi/apps/notify/templates/notify/emails/base_email_message.html
@@ -3,12 +3,12 @@
<head>
<style>
body { margin: 0; padding: 0; font-family: Arial, sans-serif; }
- .email-container { border: 4px solid #040408; padding: 0; margin: 0; }
+ .email-container { border: 4px solid #f45f36; padding: 0; margin: 0; }
.email-inner { border: 4px solid white; padding: 0; margin: 0; }
.email-header { border: 4px solid #177072; padding: 0; }
- .email-header tr { background-color: #177072; }
- .email-logo { width: 128px; padding-left: 2px; padding-bottom: 4px; }
- .email-title { font-size: 18px; font-weight: 800; color: white; padding: 12px; }
+ .email-header tr { background-color: #fefeff; }
+ .email-logo { width: 149px; padding-left: 8px; padding-right: 8px; }
+ .email-title { font-size: 18px; font-weight: 800; color: #177072; padding-left: 8px; padding-right: 8px; }
.email-content { margin: 8px; }
.email-unsubscribe { margin: 8px; color: #888888; font-size: 0.8rem; text-decoration: none; }
img.logo { height: 48px; width: auto; }
@@ -25,7 +25,7 @@
{% block logo %}
{% if BASE_URL %}
<a href="{{ BASE_URL }}" alt="Home Information Home">
- <img class="logo" src="{{ BASE_URL }}{% static 'img/hi-icon-196x196.png' %}"
+ <img class="logo" src="{{ BASE_URL }}{% static 'img/hi-logo-149x64.png' %}"
alt="Home Information Logo"/>
</a>
{% endif %}
diff --git a/src/hi/apps/notify/templates/notify/emails/notification_message.html b/src/hi/apps/notify/templates/notify/emails/notification_message.html
index 03397482..ee758f39 100644
--- a/src/hi/apps/notify/templates/notify/emails/notification_message.html
+++ b/src/hi/apps/notify/templates/notify/emails/notification_message.html
@@ -1,5 +1,5 @@
{% extends "notify/emails/base_email_message.html" %}
-{% block title %}Home Information Notification{% endblock %}
+{% block title %}Notification{% endblock %}
{% block content %}
<p>
<ul>
diff --git a/src/hi/apps/notify/templates/notify/emails/notification_message.txt b/src/hi/apps/notify/templates/notify/emails/notification_message.txt
index c98f066c..68055a07 100644
--- a/src/hi/apps/notify/templates/notify/emails/notification_message.txt
+++ b/src/hi/apps/notify/templates/notify/emails/notification_message.txt
@@ -4,5 +4,4 @@
{{ notification.title }}
{% for item in notification.item_list %} - {{ item.title }}
-{% endfor %}
-{% endblock %}
+{% endfor %}{% endblock %}
diff --git a/src/hi/apps/notify/tests/ui/views.py b/src/hi/apps/notify/tests/ui/views.py
index 65add1bb..61b09be2 100644
--- a/src/hi/apps/notify/tests/ui/views.py
+++ b/src/hi/apps/notify/tests/ui/views.py
@@ -1,14 +1,17 @@
import asyncio
-import html
from typing import Dict
from django.core.exceptions import BadRequest
from django.shortcuts import render
-from django.template.loader import render_to_string
from django.views.generic import View
+from hi.apps.config.settings_manager import SettingsManager
+from hi.apps.notify.email_sender import EmailSender
from hi.apps.notify.notify_mixins import NotificationMixin
from hi.apps.notify.tests.synthetic_data import NotifySyntheticData
+from hi.apps.notify.settings import NotifySetting
+
+from hi.tests.ui.email_test_views import EmailTestViewView
class TestUiNotifyHomeView( View ):
@@ -19,56 +22,34 @@ class TestUiNotifyHomeView( View ):
return render(request, "notify/tests/ui/home.html", context )
-class TestUiViewEmailView( View ):
+class TestUiViewEmailView( EmailTestViewView ):
- def get( self, request, *args, **kwargs ):
- context = self.get_context_for_email_message( request, *args, **kwargs )
- return self.email_preview_response(
- request = request,
- app_name = 'notify',
- view_name = context.get('email_type', 'Not specifified'),
- context = context,
- )
+ @property
+ def app_name(self):
+ return 'notify'
- def get_context_for_email_message( self, request, *args, **kwargs ) -> Dict[ str, object ]:
- email_type = kwargs.get('email_type')
+ def get_extra_context( self, email_type : str ) -> Dict[ str, object ]:
if email_type == 'notification':
notification = NotifySyntheticData().create_random_notification()
return {
- 'email_type': email_type,
'notification': notification,
}
return dict()
- def email_preview_response( self, request, app_name : str, view_name : str, context : dict ):
-
- context.update({
- 'view_name': view_name,
- 'BASE_URL': ' ',
- 'UNSUBSCRIBE_URL': 'https://example.com/unsubscribe',
- 'USER_HOME_URL': 'https://example.com/home',
- })
-
- # Need to make sure inline CSS of HTML email does not clash with
- # site's main CSS. Using IFRAME for this, and the "srcdoc"
- # atttribute need us to pre-render.
- #
- body_html_template = f'{app_name}/emails/{view_name}_message.html'
- body_html = render_to_string( body_html_template, context )
- escaped_email_html = html.escape( body_html )
-
- context.update({
- 'subject_text_template': f'{app_name}/emails/{view_name}_subject.txt',
- 'body_text_template': f'{app_name}/emails/{view_name}_message.txt',
- 'body_html_template': body_html_template,
- 'body_html': escaped_email_html,
- })
- return render( request, 'notify/tests/ui/email_preview.html', context )
-
-
+
class TestUiSendEmailView( View, NotificationMixin ):
def get( self, request, *args, **kwargs ):
+
+ if not EmailSender.is_email_configured():
+ raise NotImplementedError('Email is not configured for this server.')
+
+ email_addresses_str = SettingsManager().get_setting_value(
+ NotifySetting.NOTIFICATIONS_EMAIL_ADDRESSES,
+ )
+ if not email_addresses_str:
+ raise NotImplementedError('No notification addresses have been defined in the settings.')
+
email_type = kwargs.get('email_type')
if email_type == 'notification':
notification = NotifySyntheticData().create_random_notification()
diff --git a/src/hi/apps/user/templates/user/emails/emailer_message.html b/src/hi/apps/user/templates/user/emails/emailer_message.html
deleted file mode 100644
index 1863b995..00000000
--- a/src/hi/apps/user/templates/user/emails/emailer_message.html
+++ /dev/null
@@ -1,45 +0,0 @@
-{% load static %}
-<html>
- <head>
- </head>
- <body>
- <div style="border: 4px solid #F45F36; padding: 0; margin: 0">
- <div style="border: 4px solid white; padding: 0; margin: 0;">
- <div style="border: 4px solid #177072; padding: 0;">
- {% block body %}
- <table style="width: 100%;" cellpadding="0" cellspacing="0">
- <tr style="background-color: white">
- <td style="width: 128px; padding-left: 2px; padding-bottom: 4px;">
- {% block logo %}
- {% if BASE_URL %}
- <a href="{{ BASE_URL }}" alt="Home Information"><img src="{{ BASE_URL }}{% static 'img/hi-logo-149x64.png' %}" alt="Plates Logo"/></a>
- {% endif %}
- {% endblock %}
- </td>
- <td>
- <p style="font-size: 18px; font-weight: 800; color: #177072; padding: 12px;" >
- {% block title %}
- {% endblock %}
- </p>
- </td>
- </tr>
- </table>
-
- {% endblock %}
-
- <div style="margin: 8px;">
- {% block content %}
- {% endblock %}
- </div>
-
- {% if UNSUBSCRIBE_URL %}
- <hr />
- <p style="margin: 8px;">
- <a style="color: #888888; font-size: 0.8rem;" href="{{ UNSUBSCRIBE_URL }}">Unsubscribe.</a>
- </p>
- {% endif %}
- </div>
- </div>
- </div>
- </body>
-</html>
diff --git a/src/hi/apps/user/templates/user/emails/emailer_message.txt b/src/hi/apps/user/templates/user/emails/emailer_message.txt
deleted file mode 100644
index fef1fbb9..00000000
--- a/src/hi/apps/user/templates/user/emails/emailer_message.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-{% block content %}
-{% endblock %}
-
-
-{% if UNSUBSCRIBE_URL %}Unsubscribe: {{ UNSUBSCRIBE_URL }}{% endif %}
diff --git a/src/hi/apps/user/templates/user/emails/signin_magic_link_message.html b/src/hi/apps/user/templates/user/emails/signin_magic_link_message.html
index 7a2eb03f..73404754 100644
--- a/src/hi/apps/user/templates/user/emails/signin_magic_link_message.html
+++ b/src/hi/apps/user/templates/user/emails/signin_magic_link_message.html
@@ -1,6 +1,6 @@
-{% extends "user/emails/emailer_message.html" %}
+{% extends "notify/emails/base_email_message.html" %}
{% load common_template_helpers %}
-{% block title %}Greetings!{% endblock %}
+{% block title %}Sign In Access Code{% endblock %}
{% block content %}
<p>
Your access code is:
diff --git a/src/hi/apps/user/templates/user/emails/signin_magic_link_message.txt b/src/hi/apps/user/templates/user/emails/signin_magic_link_message.txt
index 9b390bec..3593f047 100644
--- a/src/hi/apps/user/templates/user/emails/signin_magic_link_message.txt
+++ b/src/hi/apps/user/templates/user/emails/signin_magic_link_message.txt
@@ -1,10 +1,9 @@
-{% extends "user/emails/emailer_message.txt" %}
+{% extends "notify/emails/base_email_message.txt" %}
{% load common_template_helpers %}
-{% block content %}Greetings!
+{% block content %}Home Information Sign In
Your access code is:
{{ magic_code }}
-Note that this code will expire after {{ magic_code_lifetime_minutes }} minutes. The code is not case sensitive.
-{% endblock %}
+Note that this code will expire after {{ magic_code_lifetime_minutes }} minutes. The code is not case sensitive.{% endblock %}
diff --git a/src/hi/apps/user/templates/user/emails/signin_magic_link_subject.txt b/src/hi/apps/user/templates/user/emails/signin_magic_link_subject.txt
index b2fdfe23..3167dd4a 100644
--- a/src/hi/apps/user/templates/user/emails/signin_magic_link_subject.txt
+++ b/src/hi/apps/user/templates/user/emails/signin_magic_link_subject.txt
@@ -1 +1 @@
-Home Information: Access Code
+Home Information: Sign In Access Code
diff --git a/src/hi/apps/user/templates/user/tests/ui/home.html b/src/hi/apps/user/templates/user/tests/ui/home.html
new file mode 100644
index 00000000..ca30903b
--- /dev/null
+++ b/src/hi/apps/user/templates/user/tests/ui/home.html
@@ -0,0 +1,33 @@
+{% extends "pages/base.html" %}
+{% block head_title %}HI: User Visual Testing!{% endblock %}
+
+{% block content %}
+<div class="container-fluid m-4">
+
+ <h2 class="text-info">User: UI Tests</h2>
+
+ <div class="row">
+ <div class="col-xl-4 col-lg-4 col-md-6 col-12">
+ <div class="panel panel-default">
+ <div class="panel-heading">
+ <h3 class="panel-title text-primary">Emails</h3>
+ </div>
+ <div class="panel-body">
+ <ul>
+ <li>
+ <a href="{% url 'user_tests_ui_view_signin_email' email_type='signin_magic_link' %}" data-async="modal">View Signin Email
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'user_tests_ui_send_signin_email' email_type='signin_magic_link' %}" data-async="modal">Send Signin Email
+ </a>
+ </li>
+ </ul>
+ </div>
+ </div>
+
+ </div>
+
+ </div>
+</div>
+{% endblock %}
diff --git a/src/hi/apps/user/templates/user/tests/ui/send_email_success.html b/src/hi/apps/user/templates/user/tests/ui/send_email_success.html
new file mode 100644
index 00000000..5f2f5b74
--- /dev/null
+++ b/src/hi/apps/user/templates/user/tests/ui/send_email_success.html
@@ -0,0 +1,11 @@
+{% extends "modals/action_ok.html" %}
+
+{% block title_text %}
+Email Sent
+{% endblock %}
+
+{% block body %}
+<div class="container">
+ No errors or issues sending email.
+</div>
+{% endblock %}
diff --git a/src/hi/apps/user/tests/__init__.py b/src/hi/apps/user/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/user/tests/ui/__init__.py b/src/hi/apps/user/tests/ui/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/user/tests/ui/urls.py b/src/hi/apps/user/tests/ui/urls.py
new file mode 100644
index 00000000..7ed884e0
--- /dev/null
+++ b/src/hi/apps/user/tests/ui/urls.py
@@ -0,0 +1,19 @@
+from django.urls import re_path
+
+from . import views
+
+
+urlpatterns = [
+
+ re_path( r'^$',
+ views.TestUiUserHomeView.as_view(),
+ name='user_tests_ui'),
+
+ re_path( r'^email/signin/view/(?P<email_type>\w+)$',
+ views.TestUiViewSigninEmailView.as_view(),
+ name='user_tests_ui_view_signin_email'),
+
+ re_path( r'^email/signin/send/(?P<email_type>\w+)$',
+ views.TestUiSendSigninEmailView.as_view(),
+ name='user_tests_ui_send_signin_email'),
+]
diff --git a/src/hi/apps/user/tests/ui/views.py b/src/hi/apps/user/tests/ui/views.py
new file mode 100644
index 00000000..37022b26
--- /dev/null
+++ b/src/hi/apps/user/tests/ui/views.py
@@ -0,0 +1,64 @@
+from typing import Dict
+
+from django.conf import settings
+from django.core.exceptions import BadRequest
+from django.shortcuts import render
+from django.views.generic import View
+
+from hi.apps.notify.email_sender import EmailSender
+from hi.apps.user.signin_manager import SigninManager
+from hi.apps.user.transient_models import UserAuthenticationData
+
+from hi.tests.ui.email_test_views import EmailTestViewView
+
+
+class TestUiUserHomeView( View ):
+
+ def get(self, request, *args, **kwargs):
+ context = {
+ }
+ return render(request, "user/tests/ui/home.html", context )
+
+
+class TestUiViewSigninEmailView( EmailTestViewView ):
+
+ @property
+ def app_name(self):
+ return 'user'
+
+ def get_extra_context( self, email_type : str ) -> Dict[ str, object ]:
+ if email_type == 'signin_magic_link':
+ return {
+ 'magic_code': 'abc123',
+ 'magic_code_lifetime_minutes': 123,
+ }
+ return dict()
+
+
+class TestUiSendSigninEmailView( View ):
+ """ Actually sending emails to ensure looks right on delivery. """
+
+ def get( self, request, *args, **kwargs ):
+ if not EmailSender.is_email_configured():
+ raise NotImplementedError('Email is not configured for this server.')
+
+ if request.user.is_anonymous or not request.user.email:
+ email_address = settings.EMAIL_HOST_USER
+ else:
+ email_address = request.user.email
+
+ email_type = kwargs.get('email_type')
+ if email_type == 'signin_magic_link':
+ user_auth_data = UserAuthenticationData(
+ request = request,
+ override_email = email_address,
+ )
+ SigninManager().send_signin_magic_link_email(
+ request = request,
+ user_auth_data = user_auth_data,
+ )
+ else:
+ raise BadRequest( f'Sending email type "{email_type}" not implemented.' )
+
+ return render( request, 'user/tests/ui/send_email_success.html' )
+
diff --git a/src/hi/apps/user/transient_models.py b/src/hi/apps/user/transient_models.py
index 830a9196..eab14c3f 100644
--- a/src/hi/apps/user/transient_models.py
+++ b/src/hi/apps/user/transient_models.py
@@ -12,13 +12,19 @@ logger = logging.getLogger(__name__)
class UserAuthenticationData:
- def __init__( self, request : HttpRequest, override_user : UserType = None ):
+ def __init__( self,
+ request : HttpRequest,
+ override_user : UserType = None,
+ override_email : str = None ):
if override_user:
self._user = override_user
else:
self._user = request.user
- self._email_address = self._user.email
+ if override_email:
+ self._email_address = override_email
+ else:
+ self._email_address = self._user.email
# We re-purpose the clever way tokens are used for password resets in Django
token_generator = PasswordResetTokenGenerator()
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index e13bf64a..4354a538 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -4,6 +4,8 @@ from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
+INSTALLED_APPS += [ 'hi.tests' ]
+
ALLOWED_HOSTS = [
'127.0.0.1',
'192.168.100.6',
diff --git a/src/hi/tests/templates/tests/ui/email_preview.html b/src/hi/tests/templates/tests/ui/email_preview.html
new file mode 100644
index 00000000..30841491
--- /dev/null
+++ b/src/hi/tests/templates/tests/ui/email_preview.html
@@ -0,0 +1,30 @@
+{% extends "modals/action_ok.html" %}
+
+{% block title_text %}
+Email: {{ view_name }}
+{% endblock %}
+
+{% block body %}
+<div class="container">
+
+ <h4>Subject (text)</h4>
+ <div class="border mb-2 p-2"><pre>{% include subject_text_template %}</pre></div>
+
+ <h4>Body (text)</h4>
+ <div class="border mb-2 p-2"><pre>{% include body_text_template %}</pre></div>
+
+ <h4>Body (HTML)</h4>
+
+ <div class="border p-2">
+
+ {% autoescape off %}
+ <iframe srcdoc="{{ body_html|safe }}"
+ style="width: 100%; height: 50vh; border: 1px solid #ccc;"
+ sandbox="allow-same-origin allow-scripts">
+ </iframe>
+ {% endautoescape %}
+
+ </div>
+
+</div>
+{% endblock %}
diff --git a/src/hi/tests/ui/email_test_views.py b/src/hi/tests/ui/email_test_views.py
new file mode 100644
index 00000000..f5fcdeec
--- /dev/null
+++ b/src/hi/tests/ui/email_test_views.py
@@ -0,0 +1,59 @@
+import html
+from typing import Dict
+
+from django.shortcuts import render
+from django.template.loader import render_to_string
+from django.views.generic import View
+
+
+class EmailTestViewView( View ):
+ """ For visually seeing email without sending for formatting """
+
+ @property
+ def app_name(self):
+ raise NotImplementedError('Subclasses must override this' )
+
+ def get_extra_context( self, email_type : str ) -> Dict[ str, object ]:
+ raise NotImplementedError('Subclasses must override this' )
+
+ def get( self, request, *args, **kwargs ):
+ context = self.get_context_for_email_message( request, *args, **kwargs )
+ return self.email_preview_response(
+ request = request,
+ app_name = self.app_name,
+ view_name = context.get('email_type', 'NOT_SPECIFIED'),
+ context = context,
+ )
+
+ def get_context_for_email_message( self, request, *args, **kwargs ) -> Dict[ str, object ]:
+ email_type = kwargs.get('email_type')
+ context = {
+ 'email_type': email_type,
+ }
+ context.update( self.get_extra_context( email_type = email_type ))
+ return context
+
+ def email_preview_response( self, request, app_name : str, view_name : str, context : dict ):
+
+ context.update({
+ 'view_name': view_name,
+ 'BASE_URL': ' ',
+ 'UNSUBSCRIBE_URL': 'https://example.com/unsubscribe',
+ 'USER_HOME_URL': 'https://example.com/home',
+ })
+
+ # Need to make sure inline CSS of HTML email does not clash with
+ # site's main CSS. Using IFRAME for this, and the "srcdoc"
+ # atttribute need us to pre-render.
+ #
+ body_html_template = f'{app_name}/emails/{view_name}_message.html'
+ body_html = render_to_string( body_html_template, context )
+ escaped_email_html = html.escape( body_html )
+
+ context.update({
+ 'subject_text_template': f'{app_name}/emails/{view_name}_subject.txt',
+ 'body_text_template': f'{app_name}/emails/{view_name}_message.txt',
+ 'body_html_template': body_html_template,
+ 'body_html': escaped_email_html,
+ })
+ return render( request, 'tests/ui/email_preview.html', context )