You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by ma...@apache.org on 2018/10/31 17:48:22 UTC
[airavata-django-portal] 08/09: AIRAVATA-2888 DB model for email
templates
This is an automated email from the ASF dual-hosted git repository.
machristie pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/airavata-django-portal.git
commit ab00e5389917f9f83307a93acc2fcbbe8b6f9965
Author: Marcus Christie <ma...@iu.edu>
AuthorDate: Tue Oct 30 15:08:57 2018 -0400
AIRAVATA-2888 DB model for email templates
---
django_airavata/apps/auth/admin.py | 6 +-
django_airavata/apps/auth/middleware.py | 5 +-
.../apps/auth/migrations/0002_emailtemplate.py | 25 +++++++++
.../migrations/0003_default_email_templates.py | 57 +++++++++++++++++++
django_airavata/apps/auth/models.py | 22 ++++++++
django_airavata/apps/auth/views.py | 65 ++++++++++++++++------
django_airavata/settings.py | 1 +
django_airavata/settings_local.py.sample | 22 +++++++-
.../includes/gateway_title.html | 2 +-
django_airavata/urls.py | 2 +
.../base/templatetags/navigation_tags.py | 4 +-
11 files changed, 188 insertions(+), 23 deletions(-)
diff --git a/django_airavata/apps/auth/admin.py b/django_airavata/apps/auth/admin.py
index b97a94f..a587a1e 100644
--- a/django_airavata/apps/auth/admin.py
+++ b/django_airavata/apps/auth/admin.py
@@ -1,2 +1,6 @@
+from django.contrib import admin
-# Register your models here.
+from .models import EmailTemplate
+
+
+admin.site.register(EmailTemplate)
diff --git a/django_airavata/apps/auth/middleware.py b/django_airavata/apps/auth/middleware.py
index 954f137..ceea0dc 100644
--- a/django_airavata/apps/auth/middleware.py
+++ b/django_airavata/apps/auth/middleware.py
@@ -57,8 +57,11 @@ def gateway_groups_middleware(get_response):
read_only_admins_group_id in group_ids
# Gateway Admins are made 'superuser' in Django so they can edit
# pages in the CMS
- if request.is_gateway_admin and not request.user.is_superuser:
+ if request.is_gateway_admin and (
+ not request.user.is_superuser or
+ not request.user.is_staff):
request.user.is_superuser = True
+ request.user.is_staff = True
request.user.save()
except Exception as e:
log.error("Failed to set is_gateway_admin, "
diff --git a/django_airavata/apps/auth/migrations/0002_emailtemplate.py b/django_airavata/apps/auth/migrations/0002_emailtemplate.py
new file mode 100644
index 0000000..b9006b3
--- /dev/null
+++ b/django_airavata/apps/auth/migrations/0002_emailtemplate.py
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.16 on 2018-10-29 18:23
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('django_airavata_auth', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='EmailTemplate',
+ fields=[
+ ('template_type', models.IntegerField(choices=[(1, 'Verify Email Template'), (2, 'New User Email Template')], primary_key=True, serialize=False)),
+ ('subject', models.CharField(max_length=255)),
+ ('body', models.TextField()),
+ ('created_date', models.DateTimeField(auto_now_add=True)),
+ ('updated_date', models.DateTimeField(auto_now=True)),
+ ],
+ ),
+ ]
diff --git a/django_airavata/apps/auth/migrations/0003_default_email_templates.py b/django_airavata/apps/auth/migrations/0003_default_email_templates.py
new file mode 100644
index 0000000..c21cacc
--- /dev/null
+++ b/django_airavata/apps/auth/migrations/0003_default_email_templates.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.16 on 2018-10-29 18:33
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+from django_airavata.apps.auth.models import (
+ NEW_USER_EMAIL_TEMPLATE,
+ VERIFY_EMAIL_TEMPLATE
+)
+
+
+def default_templates(apps, schema_editor):
+
+ EmailTemplate = apps.get_model("django_airavata_auth", "EmailTemplate")
+ verify_email_template = EmailTemplate(
+ template_type=VERIFY_EMAIL_TEMPLATE,
+ subject="{{first_name}} {{last_name}} ({{username}}), "
+ "Please Verify Your Email Account in {{portal_title}}",
+ body="""
+ <p>
+ Dear {{first_name}} {{last_name}},
+ </p>
+
+ <p>
+ Someone has created an account with this email address. If this was
+ you, click the link below to verify your email address:
+ </p>
+
+ <p><a href="{{url}}">{{url}}</a></p>
+
+ <p>If you didn't create this account, just ignore this message.</p>
+ """.strip())
+ verify_email_template.save()
+ new_user_email_template = EmailTemplate(
+ template_type=NEW_USER_EMAIL_TEMPLATE,
+ subject="New User Account Was Created Successfully",
+ body="""
+ <p>Gateway Portal: {{http_host}}</p>
+ <p>Tenant: {{gateway_id}}</p>
+ <p>Username: {{username}}</p>
+ <p>Name: {{first_name}} {{last_name}}</p>
+ <p>Email: {{email}}</p>
+ """.strip()
+ )
+ new_user_email_template.save()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('django_airavata_auth', '0002_emailtemplate'),
+ ]
+
+ operations = [
+ migrations.RunPython(default_templates)
+ ]
diff --git a/django_airavata/apps/auth/models.py b/django_airavata/apps/auth/models.py
index e3d8952..e169759 100644
--- a/django_airavata/apps/auth/models.py
+++ b/django_airavata/apps/auth/models.py
@@ -2,6 +2,9 @@ import uuid
from django.db import models
+VERIFY_EMAIL_TEMPLATE = 1
+NEW_USER_EMAIL_TEMPLATE = 2
+
class EmailVerification(models.Model):
username = models.CharField(max_length=64)
@@ -9,3 +12,22 @@ class EmailVerification(models.Model):
max_length=36, unique=True, default=uuid.uuid4)
created_date = models.DateTimeField(auto_now_add=True)
verified = models.BooleanField(default=False)
+
+
+class EmailTemplate(models.Model):
+ TEMPLATE_TYPE_CHOICES = (
+ (VERIFY_EMAIL_TEMPLATE, 'Verify Email Template'),
+ (NEW_USER_EMAIL_TEMPLATE, 'New User Email Template'),
+ )
+ template_type = models.IntegerField(
+ primary_key=True, choices=TEMPLATE_TYPE_CHOICES)
+ subject = models.CharField(max_length=255)
+ body = models.TextField()
+ created_date = models.DateTimeField(auto_now_add=True)
+ updated_date = models.DateTimeField(auto_now=True)
+
+ def __str__(self):
+ for choice in self.TEMPLATE_TYPE_CHOICES:
+ if self.template_type == choice[0]:
+ return choice[1]
+ return "Unknown"
diff --git a/django_airavata/apps/auth/views.py b/django_airavata/apps/auth/views.py
index 1ec89c2..7f01581 100644
--- a/django_airavata/apps/auth/views.py
+++ b/django_airavata/apps/auth/views.py
@@ -2,12 +2,14 @@ import logging
from urllib.parse import quote
from django.conf import settings
-from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
+from django.contrib.auth import authenticate, login, logout
from django.core.exceptions import ObjectDoesNotExist
-from django.core.mail import mail_admins, send_mail
+from django.core.mail import EmailMessage
from django.forms import ValidationError
+from django.http.request import split_domain_port
from django.shortcuts import redirect, render, resolve_url
+from django.template import Context, Template
from django.urls import reverse
from requests_oauthlib import OAuth2Session
@@ -157,11 +159,33 @@ def verify_email(request, code):
logger.debug("Enabling user {}".format(username))
# enable user and inform admins
iam_admin_client.enable_user(username)
- # TODO: use proper template for new user email
- mail_admins(
- 'New User Created',
- 'New user: {}'.format(username)
- )
+ user_profile = iam_admin_client.get_user(username)
+ new_user_email_template = models.EmailTemplate.objects.get(
+ pk=models.NEW_USER_EMAIL_TEMPLATE)
+ email_address = user_profile.emails[0]
+ first_name = user_profile.firstName
+ last_name = user_profile.lastName
+ domain, port = split_domain_port(request.get_host())
+ context = Context({
+ "username": username,
+ "email": email_address,
+ "first_name": first_name,
+ "last_name": last_name,
+ "portal_title": settings.PORTAL_TITLE,
+ "gateway_id": settings.GATEWAY_ID,
+ "http_host": domain,
+ })
+ subject = Template(new_user_email_template.subject).render(context)
+ body = Template(new_user_email_template.body).render(context)
+ msg = EmailMessage(subject=subject,
+ body=body,
+ from_email="{} <{}>".format(
+ settings.PORTAL_TITLE,
+ settings.SERVER_EMAIL),
+ to=["{} {} <{}>".format(
+ first_name, last_name, email_address)])
+ msg.content_subtype = 'html'
+ msg.send()
messages.success(
request,
"Your account has been successfully created. "
@@ -240,12 +264,21 @@ def _create_and_send_email_verification_link(
logger.debug(
"verification_uri={}".format(verification_uri))
- # TODO: need a better template, customization
- # TODO: add email settings documentation to
- # settings_local.py
- send_mail(
- 'Please verify your email address',
- "Verification link: {}".format(verification_uri),
- "Django Portal <pg...@gmail.com>",
- ["{} {} <{}>".format(first_name, last_name, email)]
- )
+ verify_email_template = models.EmailTemplate.objects.get(
+ pk=models.VERIFY_EMAIL_TEMPLATE)
+ context = Context({
+ "username": username,
+ "email": email,
+ "first_name": first_name,
+ "last_name": last_name,
+ "portal_title": settings.PORTAL_TITLE,
+ "url": verification_uri,
+ })
+ subject = Template(verify_email_template.subject).render(context)
+ body = Template(verify_email_template.body).render(context)
+ msg = EmailMessage(subject=subject, body=body,
+ from_email="{} <{}>".format(
+ settings.PORTAL_TITLE, settings.SERVER_EMAIL),
+ to=["{} {} <{}>".format(first_name, last_name, email)])
+ msg.content_subtype = 'html'
+ msg.send()
diff --git a/django_airavata/settings.py b/django_airavata/settings.py
index b399246..1ce34e6 100644
--- a/django_airavata/settings.py
+++ b/django_airavata/settings.py
@@ -33,6 +33,7 @@ ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django_airavata.apps.admin.apps.AdminConfig',
+ 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
diff --git a/django_airavata/settings_local.py.sample b/django_airavata/settings_local.py.sample
index 6cf09ce..796459b 100644
--- a/django_airavata/settings_local.py.sample
+++ b/django_airavata/settings_local.py.sample
@@ -11,10 +11,23 @@ import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+# Django - general settings
# Uncomment and specify for production deployments
-#DEBUG = False
-#STATIC_ROOT = "/var/www/path/to/sitename/static/"
-#ALLOWED_HOSTS = ['production.hostname']
+# DEBUG = False
+# STATIC_ROOT = "/var/www/path/to/sitename/static/"
+# ALLOWED_HOSTS = ['production.hostname']
+
+# Django - Email settings
+# Uncomment and specify the following for sending emails (default email backend
+# just prints to the console)
+# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
+# EMAIL_HOST = '...'
+# EMAIL_PORT = '...'
+# EMAIL_HOST_USER = '...'
+# EMAIL_HOST_PASSWORD = '...'
+# EMAIL_USE_TLS = True
+# ADMINS = [('Admin Name', 'admin@example.com')]
+# SERVER_EMAIL = 'portal@example.com'
# Keycloak Configuration
KEYCLOAK_CLIENT_ID = '...'
@@ -60,6 +73,9 @@ SHARING_API_HOST = 'localhost'
SHARING_API_PORT = 7878
SHARING_API_SECURE = False
+# Portal settings
+PORTAL_TITLE = 'Django Airavata Gateway'
+
# Logging configuration
# LOGGING = {
# 'version': 1,
diff --git a/django_airavata/templates/django_airavata_wagtail_base/includes/gateway_title.html b/django_airavata/templates/django_airavata_wagtail_base/includes/gateway_title.html
index 3905188..5668183 100644
--- a/django_airavata/templates/django_airavata_wagtail_base/includes/gateway_title.html
+++ b/django_airavata/templates/django_airavata_wagtail_base/includes/gateway_title.html
@@ -1,5 +1,5 @@
{% if not gateway_title %}
- Django Airavata Gateway
+ {{ default_title }}
{% else %}
{{ gateway_title.title_text }}
{% endif %}
diff --git a/django_airavata/urls.py b/django_airavata/urls.py
index fe9b2a9..6cdcb2a 100644
--- a/django_airavata/urls.py
+++ b/django_airavata/urls.py
@@ -16,6 +16,7 @@ Including another URLconf
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
+from django.contrib import admin
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
@@ -23,6 +24,7 @@ from wagtail.documents import urls as wagtaildocs_urls
from . import views
urlpatterns = [
+ url(r'^djadmin/', admin.site.urls),
url(r'^admin/', include('django_airavata.apps.admin.urls')),
url(r'^auth/', include('django_airavata.apps.auth.urls')),
url(r'^workspace/', include('django_airavata.apps.workspace.urls')),
diff --git a/django_airavata/wagtailapps/base/templatetags/navigation_tags.py b/django_airavata/wagtailapps/base/templatetags/navigation_tags.py
index 8b0fc3d..b46e3a9 100644
--- a/django_airavata/wagtailapps/base/templatetags/navigation_tags.py
+++ b/django_airavata/wagtailapps/base/templatetags/navigation_tags.py
@@ -1,4 +1,5 @@
from django import template
+from django.conf import settings
from wagtail.core.models import Page
from django_airavata.wagtailapps.base.models import (
@@ -180,5 +181,6 @@ def gateway_title(context):
gateway_title = GatewayTitle.objects.first()
return {
- 'gateway_title': gateway_title
+ 'gateway_title': gateway_title,
+ 'default_title': settings.PORTAL_TITLE,
}