Skip to content

Home Information - Your home, your data, organized.

Python

Added custom user model, signing feature and reset migrations.

Anthony Cassandra4443912d4f80
diff --git a/src/custom/__init__.py b/src/custom/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/custom/admin.py b/src/custom/admin.py
new file mode 100644
index 00000000..8ff82f28
--- /dev/null
+++ b/src/custom/admin.py
@@ -0,0 +1,60 @@
+from django.contrib import admin
+
+from django.contrib.auth.admin import UserAdmin
+from django.utils.translation import gettext_lazy as _
+
+
+from .forms import (
+ CustomUserChangeForm,
+ CustomUserCreationForm,
+)
+from .models import CustomUser
+
+
[email protected]( CustomUser )
+class CustomUserAdmin( UserAdmin ):
+ model = CustomUser
+ add_form = CustomUserCreationForm
+
+ # Fields for the user creation form
+ add_fieldsets = (
+ (
+ None,
+ {
+ "classes": ("wide",),
+ "fields": (
+ "email",
+ "first_name",
+ "last_name",
+ "is_staff",
+ ),
+ },
+ ),
+ )
+
+ # Fields for the user edit form
+ fieldsets = (
+ (None, {"fields": ("email", "password")}),
+ (_("Personal info"), {"fields": ("first_name", "last_name")}),
+ (
+ _("Permissions"),
+ {
+ "fields": (
+ "is_active",
+ "email_verified",
+ "is_staff",
+ "is_superuser",
+ "groups",
+ "user_permissions",
+ ),
+ },
+ ),
+ (_("Important dates"), {"fields": ("last_login", "date_joined")}),
+ )
+
+ form = CustomUserChangeForm
+ add_form = CustomUserCreationForm
+ list_display = ("email", "uuid", "first_name", "last_name", "email_verified", "is_staff")
+ list_filter = ("is_staff", "is_superuser", "is_active", "groups")
+ search_fields = ( "email", "uuid" )
+ ordering = ("id",)
diff --git a/src/custom/apps.py b/src/custom/apps.py
new file mode 100644
index 00000000..aab1ef97
--- /dev/null
+++ b/src/custom/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class CustomConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "custom"
diff --git a/src/custom/forms.py b/src/custom/forms.py
new file mode 100644
index 00000000..a1719b2f
--- /dev/null
+++ b/src/custom/forms.py
@@ -0,0 +1,56 @@
+from django import forms
+from django.contrib.auth.forms import (
+ ReadOnlyPasswordHashField,
+)
+from django.utils.translation import gettext_lazy as _
+
+from .models import CustomUser
+
+
+class CustomUserCreationForm( forms.ModelForm ):
+
+ class Meta:
+ model = CustomUser
+ fields = (
+ 'email',
+ 'first_name',
+ 'last_name',
+ 'is_staff',
+ )
+
+ def save(self, commit=True):
+ # Save without setting a password
+ user = super().save( commit = False )
+ if commit:
+ user.save()
+ return user
+
+
+class CustomUserChangeForm(forms.ModelForm):
+
+ password = ReadOnlyPasswordHashField(
+ label = _("Password"),
+ help_text = _(
+ "Raw passwords are not stored, so there is no way to see this "
+ "user’s password, but you can change the password using "
+ '<a href="{}">this form</a>.'
+ ),
+ )
+
+ class Meta:
+ model = CustomUser
+ fields = "__all__"
+ field_classes = { "email": forms.CharField }
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ password = self.fields.get("password")
+ if password:
+ password.help_text = password.help_text.format(
+ f"../../{self.instance.pk}/password/"
+ )
+ user_permissions = self.fields.get("user_permissions")
+ if user_permissions:
+ user_permissions.queryset = user_permissions.queryset.select_related(
+ "content_type"
+ )
diff --git a/src/custom/management/__init__.py b/src/custom/management/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/custom/management/commands/__init__.py b/src/custom/management/commands/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/custom/management/commands/creategroups.py b/src/custom/management/commands/creategroups.py
new file mode 100644
index 00000000..73e96607
--- /dev/null
+++ b/src/custom/management/commands/creategroups.py
@@ -0,0 +1,15 @@
+from django.core.management.base import BaseCommand
+
+from django.contrib.auth.models import Group
+
+
+class Command(BaseCommand):
+ """
+ Command provided so that we can automate creating groups we need
+ for the game, mostly around tools and content management administrative
+ functions.
+ """
+ def handle(self, *args, **options):
+ # TODO: Placeholder for eventual groups creation.
+ return
+
diff --git a/src/custom/management/commands/createsuperuser.py b/src/custom/management/commands/createsuperuser.py
new file mode 100644
index 00000000..412e0001
--- /dev/null
+++ b/src/custom/management/commands/createsuperuser.py
@@ -0,0 +1,23 @@
+from django.conf import settings
+from django.core.management.base import BaseCommand
+
+from custom.models import CustomUser
+
+
+class Command(BaseCommand):
+ """
+ Command provided so that we can automate creating the super user in
+ deployments. Normal django "createsuperuser" does not allow pasing
+ password.
+ """
+ def handle(self, *args, **options):
+ admin_email = settings.DJANGO_SUPERUSER_EMAIL
+ admin_password = settings.DJANGO_SUPERUSER_PASSWORD
+ if not admin_email or not admin_password:
+ raise ValueError( 'Need to set "DJANGO_SUPERUSER_EMAIL" and "DJANGO_SUPERUSER_PASSWORD"' )
+ if not CustomUser.objects.filter( email = admin_email ).exists():
+ CustomUser.objects.create_superuser(
+ email = admin_email,
+ password = admin_password,
+ )
+ return
diff --git a/src/custom/managers.py b/src/custom/managers.py
new file mode 100644
index 00000000..54c6b35b
--- /dev/null
+++ b/src/custom/managers.py
@@ -0,0 +1,64 @@
+from django.contrib import auth
+from django.contrib.auth.hashers import make_password
+from django.contrib.auth.base_user import BaseUserManager
+
+
+class CustomUserManager(BaseUserManager):
+ use_in_migrations = True
+
+ def _create_user( self, email, password, **extra_fields ):
+ """
+ Create and save a user with the given email and password.
+ """
+ email = self.normalize_email(email)
+ if email:
+ email = email.strip()
+ email = email or None
+
+ user = self.model( email=email, **extra_fields )
+ user.password = make_password(password)
+ user.save(using=self._db)
+ return user
+
+ def create_user(self, email=None, password=None, **extra_fields):
+ extra_fields.setdefault("is_staff", False)
+ extra_fields.setdefault("is_superuser", False)
+ return self._create_user(email, password, **extra_fields)
+
+ def create_superuser(self, email=None, password=None, **extra_fields):
+ extra_fields.setdefault("is_staff", True)
+ extra_fields.setdefault("is_superuser", True)
+
+ if extra_fields.get("is_staff") is not True:
+ raise ValueError("Superuser must have is_staff=True.")
+ if extra_fields.get("is_superuser") is not True:
+ raise ValueError("Superuser must have is_superuser=True.")
+
+ return self._create_user(email, password, **extra_fields)
+
+ def with_perm(
+ self, perm, is_active=True, include_superusers=True, backend=None, obj=None
+ ):
+ if backend is None:
+ backends = auth._get_backends(return_tuples=True)
+ if len(backends) == 1:
+ backend, _ = backends[0]
+ else:
+ raise ValueError(
+ "You have multiple authentication backends configured and "
+ "therefore must provide the `backend` argument."
+ )
+ elif not isinstance(backend, str):
+ raise TypeError(
+ "backend must be a dotted import path string (got %r)." % backend
+ )
+ else:
+ backend = auth.load_backend(backend)
+ if hasattr(backend, "with_perm"):
+ return backend.with_perm(
+ perm,
+ is_active=is_active,
+ include_superusers=include_superusers,
+ obj=obj,
+ )
+ return self.none()
diff --git a/src/custom/migrations/0001_initial.py b/src/custom/migrations/0001_initial.py
new file mode 100644
index 00000000..f3e44858
--- /dev/null
+++ b/src/custom/migrations/0001_initial.py
@@ -0,0 +1,134 @@
+# Generated by Django 4.2.15 on 2025-01-27 18:15
+
+import custom.managers
+from django.db import migrations, models
+import django.utils.timezone
+import uuid
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ("auth", "0012_alter_user_first_name_max_length"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CustomUser",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("password", models.CharField(max_length=128, verbose_name="password")),
+ (
+ "last_login",
+ models.DateTimeField(
+ blank=True, null=True, verbose_name="last login"
+ ),
+ ),
+ (
+ "is_superuser",
+ models.BooleanField(
+ default=False,
+ help_text="Designates that this user has all permissions without explicitly assigning them.",
+ verbose_name="superuser status",
+ ),
+ ),
+ (
+ "uuid",
+ models.UUIDField(
+ default=uuid.uuid4, unique=True, verbose_name="UUID"
+ ),
+ ),
+ (
+ "email",
+ models.EmailField(
+ blank=True,
+ max_length=254,
+ null=True,
+ unique=True,
+ verbose_name="email address",
+ ),
+ ),
+ (
+ "email_verified",
+ models.BooleanField(
+ default=False,
+ help_text="Has this email been verified.",
+ verbose_name="email verified",
+ ),
+ ),
+ (
+ "first_name",
+ models.CharField(
+ blank=True, max_length=150, verbose_name="first name"
+ ),
+ ),
+ (
+ "last_name",
+ models.CharField(
+ blank=True, max_length=150, verbose_name="last name"
+ ),
+ ),
+ (
+ "is_staff",
+ models.BooleanField(
+ default=False,
+ help_text="Designates whether the user can log into this admin site.",
+ verbose_name="staff status",
+ ),
+ ),
+ (
+ "is_active",
+ models.BooleanField(
+ default=True,
+ help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
+ verbose_name="active",
+ ),
+ ),
+ (
+ "date_joined",
+ models.DateTimeField(
+ default=django.utils.timezone.now, verbose_name="date joined"
+ ),
+ ),
+ (
+ "groups",
+ models.ManyToManyField(
+ blank=True,
+ help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
+ related_name="user_set",
+ related_query_name="user",
+ to="auth.group",
+ verbose_name="groups",
+ ),
+ ),
+ (
+ "user_permissions",
+ models.ManyToManyField(
+ blank=True,
+ help_text="Specific permissions for this user.",
+ related_name="user_set",
+ related_query_name="user",
+ to="auth.permission",
+ verbose_name="user permissions",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "user",
+ "verbose_name_plural": "users",
+ },
+ managers=[
+ ("objects", custom.managers.CustomUserManager()),
+ ],
+ ),
+ ]
diff --git a/src/custom/migrations/__init__.py b/src/custom/migrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/custom/models.py b/src/custom/models.py
new file mode 100644
index 00000000..7e5c77fa
--- /dev/null
+++ b/src/custom/models.py
@@ -0,0 +1,120 @@
+import logging
+import uuid
+
+from django.db import models
+from django.contrib.auth.base_user import AbstractBaseUser
+from django.contrib.auth.models import PermissionsMixin
+from django.utils import timezone
+from django.utils.translation import gettext_lazy as _
+
+from . import managers
+
+logger = logging.getLogger(__name__)
+
+
+class CustomUser( AbstractBaseUser, PermissionsMixin ):
+ """Mostly a copy of Django's AbstractUser code, but with uuid and email as
+ unique fields and without the username field.
+
+ Adds additional states of user authentication beyond Django's Anonymous
+ and Autheticated. New states:
+
+ Anonymous - Same as normal Django AnonymousUser with no database entry.
+ User, No Email - Authenticated but no email to enables app functionality before an email.
+ User, Has Email - Authenticated and has set an email, but we have not verified they own that email.
+ User, Has Verified Email - Authenticated, has set an email and we have verified they own that email.
+
+ The UUID field allows us to have a unique, unchanging field for external references to users.
+ """
+ # For external referencing
+ uuid = models.UUIDField(
+ 'UUID',
+ default = uuid.uuid4,
+ unique = True,
+ null = False,
+ )
+ # All users without emails
+ email = models.EmailField(
+ _('email address'),
+ unique = True,
+ null = True,
+ blank = True,
+ )
+ email_verified = models.BooleanField(
+ _('email verified'),
+ default = False,
+ help_text = _('Has this email been verified.')
+ )
+ first_name = models.CharField(
+ _('first name'),
+ max_length = 150,
+ blank = True
+ )
+ last_name = models.CharField(
+ _('last name'),
+ max_length = 150,
+ blank = True
+ )
+ is_staff = models.BooleanField(
+ _('staff status'),
+ default = False,
+ help_text = _('Designates whether the user can log into this admin site.')
+ )
+ is_active = models.BooleanField(
+ _('active'),
+ default = True,
+ help_text = _('Designates whether this user should be treated as '
+ 'active. Unselect this instead of deleting accounts.')
+ )
+ date_joined = models.DateTimeField(
+ _('date joined'),
+ default = timezone.now
+ )
+
+ objects = managers.CustomUserManager()
+
+ USERNAME_FIELD = "email"
+ EMAIL_FIELD = "email"
+ REQUIRED_FIELDS = [ ]
+
+ class Meta:
+ verbose_name = _('user')
+ verbose_name_plural = _('users')
+
+ def __str__(self):
+ if self.email:
+ return self.email
+ return self.uuid_str
+
+ def clean(self):
+ super().clean()
+ if self.email:
+ self.email = self.__class__.objects.normalize_email(self.email)
+ return
+
+ @property
+ def uuid_str(self):
+ return str(self.uuid)
+
+ def get_full_name(self):
+ """
+ Returns the first_name plus the last_name, with a space in between.
+ """
+ full_name = '%s %s' % (self.first_name, self.last_name)
+ return full_name.strip()
+
+ def get_short_name(self):
+ "Returns the short name for the user."
+ return self.first_name
+
+ def email_user(self, subject, message, from_email=None, **kwargs):
+ raise NotImplementedError( f'Use different mechansism to email the user: {self}' )
+
+ @property
+ def admin_name(self):
+ if self.email:
+ return self.email
+ if self.first_name:
+ return self.first_name
+ return self.uuid_str
+
diff --git a/src/custom/tests/__init__.py b/src/custom/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/custom/tests/test_models.py b/src/custom/tests/test_models.py
new file mode 100644
index 00000000..f775996b
--- /dev/null
+++ b/src/custom/tests/test_models.py
@@ -0,0 +1,45 @@
+from django.contrib.auth import get_user_model
+from django.test import TestCase
+
+from custom.models import CustomUser
+
+
+class UsersManagersTests(TestCase):
+
+ def test_create_user(self):
+ User = get_user_model()
+ user = User.objects.create_user()
+ self.assertIsInstance( user, CustomUser )
+ user = User.objects.create_user(email=None, password="foo")
+ self.assertIsInstance( user, CustomUser )
+ user = User.objects.create_user(email="")
+ self.assertIsInstance( user, CustomUser )
+ user = User.objects.create_user(email=" ")
+ self.assertIsInstance( user, CustomUser )
+ user = User.objects.create_user(email=" ") # Should force to None so no duplicate
+ self.assertIsInstance( user, CustomUser )
+ user = User.objects.create_user(email="[email protected]", password="foo")
+ self.assertIsInstance( user, CustomUser )
+ self.assertEqual(user.email, "[email protected]")
+ self.assertTrue( len(user.email) > 10 )
+ self.assertTrue(user.is_active)
+ self.assertFalse(user.is_staff)
+ self.assertFalse(user.is_superuser)
+ return
+
+ def test_create_superuser(self):
+ User = get_user_model()
+ admin_user = User.objects.create_user(email=None, password="foo")
+ self.assertIsInstance( admin_user, CustomUser )
+ admin_user = User.objects.create_superuser(email="[email protected]", password="foo")
+ self.assertIsInstance( admin_user, CustomUser )
+ self.assertEqual(admin_user.email, "[email protected]")
+ self.assertTrue( len(admin_user.email) > 10 )
+ self.assertTrue(admin_user.is_active)
+ self.assertTrue(admin_user.is_staff)
+ self.assertTrue(admin_user.is_superuser)
+ with self.assertRaises(ValueError):
+ User.objects.create_superuser(
+ email="[email protected]", password="foo", is_superuser=False)
+ return
+
diff --git a/src/hi/apps/collection/migrations/0001_initial.py b/src/hi/apps/collection/migrations/0001_initial.py
index ccf92c0a..1351a0a3 100644
--- a/src/hi/apps/collection/migrations/0001_initial.py
+++ b/src/hi/apps/collection/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
diff --git a/src/hi/apps/common/email_sender.py b/src/hi/apps/common/email_sender.py
new file mode 100644
index 00000000..fcdf06c5
--- /dev/null
+++ b/src/hi/apps/common/email_sender.py
@@ -0,0 +1,63 @@
+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/common/migrations/0001_initial.py b/src/hi/apps/common/migrations/0001_initial.py
index 064563be..c97a0390 100644
--- a/src/hi/apps/common/migrations/0001_initial.py
+++ b/src/hi/apps/common/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
diff --git a/src/hi/apps/common/tests/test_url_utils.py b/src/hi/apps/common/tests/test_url_utils.py
index 1f5a2652..1f8cc46e 100644
--- a/src/hi/apps/common/tests/test_url_utils.py
+++ b/src/hi/apps/common/tests/test_url_utils.py
@@ -16,24 +16,6 @@ class UrlUtilsTestCase(TestCase):
( '/help', '/help' ),
( '/privacy', '/privacy' ),
( '/tos', '/tos' ),
- ( '/accounts/login/', '/accounts/login/' ),
- ( '/accounts/google/login/', '/accounts/google/login/' ),
- ( '/accounts/facebook/login/', '/accounts/facebook/login/' ),
- ( '/accounts/google/login/callback/', '/accounts/google/login/callback/' ),
- ( '/accounts/facebook/login/callback/', '/accounts/facebook/login/callback/' ),
- ( '/accounts/social/signup/', '/accounts/social/signup/' ),
- ( '/accounts/logout/', '/accounts/logout/' ),
- ( '/accounts/password/reset/', '/accounts/password/reset/' ),
- ( '/accounts/password/reset/done/', '/accounts/password/reset/done/' ),
- ( '/accounts/signup/', '/accounts/signup/' ),
- ( '/api/user/info/sadfasdfasdfasdfasdf', '/api/user/info' ),
- ( '/img/avatar/sm/fun_car/ffddee.png', '/img/avatar' ),
- ( '/img/map/usa/visited-HI-DE/active-DE/400.png', '/img/map/usa' ),
- ( '/img/map/region/ny.png', '/img/map/region' ),
- ( '/img/award/icon/lg/bronze.png', '/img/award' ),
- ( '/img/award/trophy/lg/silver.png', '/img/award' ),
- ( '/img/badge/sm/daily_top_score/4/345.png', '/img/badge' ),
- ( '/img/location/lg/dam.png', '/img/location' ),
]
diff --git a/src/hi/apps/config/migrations/0001_initial.py b/src/hi/apps/config/migrations/0001_initial.py
index b15be5f8..fa2b6804 100644
--- a/src/hi/apps/config/migrations/0001_initial.py
+++ b/src/hi/apps/config/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
diff --git a/src/hi/apps/control/migrations/0001_initial.py b/src/hi/apps/control/migrations/0001_initial.py
index bdc0b18e..7a0db800 100644
--- a/src/hi/apps/control/migrations/0001_initial.py
+++ b/src/hi/apps/control/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
diff --git a/src/hi/apps/entity/migrations/0001_initial.py b/src/hi/apps/entity/migrations/0001_initial.py
index 5d5fb98b..d87aa4ef 100644
--- a/src/hi/apps/entity/migrations/0001_initial.py
+++ b/src/hi/apps/entity/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_form.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_form.html
index 8708d710..7bf3e064 100644
--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_form.html
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_form.html
@@ -26,5 +26,5 @@
</div>
{{ entity_form.entity_type_str }}
</div>
- {{ entity_form.entity_type_str.errors }}
+ <small class="form-error text-danger">{{ entity_form.entity_type_str.errors }}</small>
</div>
diff --git a/src/hi/apps/event/migrations/0001_initial.py b/src/hi/apps/event/migrations/0001_initial.py
index 48afcade..affcfb00 100644
--- a/src/hi/apps/event/migrations/0001_initial.py
+++ b/src/hi/apps/event/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
@@ -9,8 +9,8 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
- ("entity", "0001_initial"),
("control", "0001_initial"),
+ ("entity", "0001_initial"),
]
operations = [
@@ -131,7 +131,7 @@ class Migration(migrations.Migration):
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to="entity.entitystate",
- verbose_name="Entity State",
+ verbose_name="Item State",
),
),
(
diff --git a/src/hi/apps/location/migrations/0001_initial.py b/src/hi/apps/location/migrations/0001_initial.py
index eb9b3f60..6d5c4ee3 100644
--- a/src/hi/apps/location/migrations/0001_initial.py
+++ b/src/hi/apps/location/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
@@ -85,7 +85,7 @@ class Migration(migrations.Migration):
),
(
"svg_style_name_str",
- models.CharField(max_length=32, verbose_name="Style Name"),
+ models.CharField(max_length=32, verbose_name="Style"),
),
(
"order_id",
diff --git a/src/hi/apps/notify/migrations/0001_initial.py b/src/hi/apps/notify/migrations/0001_initial.py
index babecdeb..28b41fb3 100644
--- a/src/hi/apps/notify/migrations/0001_initial.py
+++ b/src/hi/apps/notify/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
diff --git a/src/hi/apps/sense/migrations/0001_initial.py b/src/hi/apps/sense/migrations/0001_initial.py
index 700a968d..ad9c6b69 100644
--- a/src/hi/apps/sense/migrations/0001_initial.py
+++ b/src/hi/apps/sense/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
diff --git a/src/hi/apps/user/__init__.py b/src/hi/apps/user/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/user/apps.py b/src/hi/apps/user/apps.py
new file mode 100644
index 00000000..ee18b326
--- /dev/null
+++ b/src/hi/apps/user/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class UserConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "hi.apps.user"
diff --git a/src/hi/apps/user/forms.py b/src/hi/apps/user/forms.py
new file mode 100644
index 00000000..e806b26d
--- /dev/null
+++ b/src/hi/apps/user/forms.py
@@ -0,0 +1,19 @@
+from django import forms
+
+from .magic_code_generator import MagicCodeGenerator
+
+
+class SigninMagicCodeForm(forms.Form):
+
+ email_address = forms.CharField(
+ max_length = 128,
+ widget = forms.HiddenInput(),
+ )
+
+ magic_code = forms.CharField(
+ label = '',
+ max_length = 2 * MagicCodeGenerator.MAGIC_CODE_LENGTH,
+ widget = forms.TextInput( attrs = { 'autofocus': 'autofocus',
+ 'placeholder': 'access code',
+ 'width': str(2 * MagicCodeGenerator.MAGIC_CODE_LENGTH) } ),
+ required = True )
diff --git a/src/hi/apps/user/magic_code_generator.py b/src/hi/apps/user/magic_code_generator.py
new file mode 100644
index 00000000..5e197d83
--- /dev/null
+++ b/src/hi/apps/user/magic_code_generator.py
@@ -0,0 +1,92 @@
+from datetime import datetime
+from enum import Enum
+import re
+
+from django.conf import settings
+from django.utils import timezone
+from django.utils.crypto import get_random_string
+
+
+class MagicCodeStatus(Enum):
+
+ INVALID = 0
+ EXPIRED = 1
+ VALID = 2
+
+
+class MagicCodeGenerator:
+ """
+ Used to generate and validate one-time login codes for password-less logins.
+
+ Uses sessions to store code to be validated from user input.
+
+ Usage:
+ Generate:
+ magic_code_generator = MagicCodeGenerator()
+ magic_code = magic_code_generator.make_magic_code( request )
+ <email magic code to user>
+ <show a form to user to accept magic code entry>
+
+ Validate:
+ magic_code = <user submits form with magic code they entered>
+ magic_code_generator = MagicCodeGenerator()
+ is_valid = magic_code_generator.check_magic_code( request, magic_code = magic_code )
+ if is_valid:
+ magic_code_generator.expire_magic_code( request )
+
+ """
+
+ MAGIC_CODE = 'magic_code'
+ MAGIC_CODE_TIMESTAMP = 'magic_code_timestamp'
+
+ MAGIC_CODE_TIMEOUT_SECS = settings.PASSWORD_RESET_TIMEOUT
+ MAGIC_CODE_CHARS = 'abcdefhkpqrstwxy'
+ MAGIC_CODE_LENGTH = 6
+
+ BASE_DATETIME = timezone.make_aware( datetime(2001, 1, 1) )
+
+ def make_magic_code( self, request ):
+
+ magic_code = get_random_string( length = self.MAGIC_CODE_LENGTH,
+ allowed_chars = self.MAGIC_CODE_CHARS )
+ magic_code_origin_timestamp = self.get_elapsed_seconds()
+
+ request.session[self.MAGIC_CODE] = magic_code
+ request.session[self.MAGIC_CODE_TIMESTAMP] = magic_code_origin_timestamp
+
+ return magic_code
+
+ def check_magic_code( self, request, magic_code ) -> MagicCodeStatus:
+
+ magic_code = re.sub( r'[\-\s]', '', magic_code )
+
+ expected_magic_code = request.session.get( self.MAGIC_CODE )
+ if magic_code != expected_magic_code:
+ return MagicCodeStatus.INVALID
+
+ magic_code_origin_timestamp = request.session.get( self.MAGIC_CODE_TIMESTAMP )
+ current_timestamp = self.get_elapsed_seconds()
+ timeout_secs = self.get_timeout_seconds()
+
+ if ( current_timestamp - magic_code_origin_timestamp ) > timeout_secs:
+ return MagicCodeStatus.EXPIRED
+
+ return MagicCodeStatus.VALID
+
+ def expire_magic_code( self, request ):
+ request.session[self.MAGIC_CODE] = None
+ request.session[self.MAGIC_CODE_TIMESTAMP] = None
+ return
+
+ @classmethod
+ def get_elapsed_seconds(cls):
+ return int(( cls.get_datetime_now() - cls.BASE_DATETIME ).total_seconds())
+
+ @classmethod
+ def get_datetime_now(cls):
+ return timezone.now()
+
+ @classmethod
+ def get_timeout_seconds(cls):
+ return cls.MAGIC_CODE_TIMEOUT_SECS
+
diff --git a/src/hi/apps/user/middleware.py b/src/hi/apps/user/middleware.py
new file mode 100644
index 00000000..3657fde0
--- /dev/null
+++ b/src/hi/apps/user/middleware.py
@@ -0,0 +1,33 @@
+from django.conf import settings
+from django.urls import resolve
+
+from .views import UserSigninView
+
+
+class AuthenticationMiddleware(object):
+
+ EXEMPT_VIEW_URL_NAMES = {
+ 'admin',
+ 'user_signin',
+ 'user_signin_magic_code',
+ 'user_signin_magic_link',
+ }
+
+ def __init__(self, get_response):
+ self.get_response = get_response
+ return
+
+ def __call__(self, request):
+
+ if settings.SUPPRESS_AUTHENTICATION or request.user.is_authenticated:
+ return self.get_response( request )
+
+ resolver_match = resolve( request.path )
+ view_url_name = resolver_match.url_name
+ app_name = resolver_match.app_name
+
+ if (( app_name == 'admin' )
+ or ( view_url_name in self.EXEMPT_VIEW_URL_NAMES )):
+ return self.get_response(request)
+
+ return UserSigninView().get( request )
diff --git a/src/hi/apps/user/migrations/__init__.py b/src/hi/apps/user/migrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/user/signin_manager.py b/src/hi/apps/user/signin_manager.py
new file mode 100644
index 00000000..dc8d0150
--- /dev/null
+++ b/src/hi/apps/user/signin_manager.py
@@ -0,0 +1,73 @@
+import logging
+
+from django.contrib.auth import login as django_login
+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 .transient_models import UserAuthenticationData
+
+logger = logging.getLogger(__name__)
+
+
+class SigninManager( Singleton ):
+
+ def __init_singleton__(self):
+ return
+
+ def send_signin_magic_link_email( self,
+ 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',
+ kwargs = { 'token': user_auth_data.token,
+ 'email': user_auth_data.email_address } )
+ )
+
+ email_template_context = {
+ 'page_url': page_url,
+ 'magic_code': user_auth_data.magic_code,
+ }
+ email_sender_data = EmailSenderData(
+ request = request,
+ subject_template_name = subject_template_name,
+ message_text_template_name = message_text_template_name,
+ message_html_template_name = message_html_template_name,
+ to_email_address = to_email_address,
+ template_context = email_template_context,
+ non_blocking = True,
+ )
+
+ email_sender = EmailSender( data = email_sender_data )
+ email_sender.send()
+ return True
+
+ def do_login( self, request, verified_email : str = False ):
+ django_login( request, request.user )
+ if not verified_email:
+ return
+ if request.user.email_verified:
+ return
+ request.user.email_verified = True
+ request.user.save()
+ return
diff --git a/src/hi/apps/user/templates/user/emails/emailer_message.html b/src/hi/apps/user/templates/user/emails/emailer_message.html
new file mode 100644
index 00000000..1863b995
--- /dev/null
+++ b/src/hi/apps/user/templates/user/emails/emailer_message.html
@@ -0,0 +1,45 @@
+{% 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
new file mode 100644
index 00000000..fef1fbb9
--- /dev/null
+++ b/src/hi/apps/user/templates/user/emails/emailer_message.txt
@@ -0,0 +1,5 @@
+{% 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
new file mode 100644
index 00000000..7a2eb03f
--- /dev/null
+++ b/src/hi/apps/user/templates/user/emails/signin_magic_link_message.html
@@ -0,0 +1,14 @@
+{% extends "user/emails/emailer_message.html" %}
+{% load common_template_helpers %}
+{% block title %}Greetings!{% endblock %}
+{% block content %}
+<p>
+ Your access code is:
+ <ul>
+ <span style="font-size:1.5rem; font-weight: bold">{{ magic_code }}</span>
+ </ul>
+</p>
+<p>
+ Note that this code will expire after {{ magic_code_lifetime_minutes }} minutes. The code is not case sensitive.
+</p>
+{% endblock %}
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
new file mode 100644
index 00000000..9b390bec
--- /dev/null
+++ b/src/hi/apps/user/templates/user/emails/signin_magic_link_message.txt
@@ -0,0 +1,10 @@
+{% extends "user/emails/emailer_message.txt" %}
+{% load common_template_helpers %}
+{% block content %}Greetings!
+
+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 %}
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
new file mode 100644
index 00000000..b2fdfe23
--- /dev/null
+++ b/src/hi/apps/user/templates/user/emails/signin_magic_link_subject.txt
@@ -0,0 +1 @@
+Home Information: Access Code
diff --git a/src/hi/apps/user/templates/user/pages/magic_code_signin.html b/src/hi/apps/user/templates/user/pages/magic_code_signin.html
new file mode 100644
index 00000000..1fad8bc1
--- /dev/null
+++ b/src/hi/apps/user/templates/user/pages/magic_code_signin.html
@@ -0,0 +1,44 @@
+{% extends "pages/interstitial_page.html" %}
+
+{% block interstitial_content %}
+<div class="h3" >Email Sent</div>
+<div class="my-3">
+ Look in your inbox for the access code to sign in.
+</div>
+
+<div class="my-3">
+ <form role="form" class="form"
+ method="POST"
+ action="{% url 'user_signin_magic_code' %}"
+ data-synchronous="true">
+ {% csrf_token %}
+ {% for hidden in magic_code_form.hidden_fields %}
+ {{ hidden }}
+ {% endfor %}
+ {{ magic_code_form.non_field_errors }}
+ <div class="d-flex input-group input-group-lg">
+ <input type="text"
+ class="form-control"
+ name="magic_code"
+ autofocus="autofocus"
+ placeholder="access code"
+ maxlength="12"
+ required=""
+ id="hi-magic-code-input"
+ width="8">
+ <div class="input-group-append">
+ <button id="hi-magic-code-submit-button"
+ type="submit" name=submit" value="main"
+ class="main btn btn-primary">SUBMIT</button>
+ </div>
+ </div>
+ <div class=" text-left text-danger mt-2">
+ <small class="form-error">{{ magic_code_form.magic_code.errors }}</small>
+ </div>
+ </form>
+</div>
+
+<div class="text-muted my-4">
+ If you do not receive this email in the next few minutes, check that the email address "{{ magic_code_form.email_address.value }}" is valid and has been registered.
+</div>
+{% endblock %}
diff --git a/src/hi/apps/user/templates/user/pages/signin.html b/src/hi/apps/user/templates/user/pages/signin.html
new file mode 100644
index 00000000..459ca51a
--- /dev/null
+++ b/src/hi/apps/user/templates/user/pages/signin.html
@@ -0,0 +1,27 @@
+{% extends "pages/interstitial_page.html" %}
+
+{% block interstitial_content %}
+<div>
+ <form class="sigin form" method="post"
+ action="{% url 'user_signin' %}"
+ data-synchronous="true">
+ {% csrf_token %}
+ <div class="h3 text-center">Sign In</div>
+ <div class="d-flex mt-3">
+ <input class="" style="width: 20rem;"
+ type="email"
+ name="email"
+ value=""
+ autofocus="autofocus"
+ placeholder="e-mail address" required="" id="hi-signin-email"/>
+ </div>
+ <div>
+ <button id="hi-signin-button"
+ role="button" type="submit"
+ class="btn btn-lg btn-primary my-4">
+ <b>Sign In</b>
+ </button>
+ </div>
+ </form>
+</div>
+{% endblock %}
diff --git a/src/hi/apps/user/templates/user/pages/signin_magic_bad_link.html b/src/hi/apps/user/templates/user/pages/signin_magic_bad_link.html
new file mode 100644
index 00000000..f90ac2ce
--- /dev/null
+++ b/src/hi/apps/user/templates/user/pages/signin_magic_bad_link.html
@@ -0,0 +1,16 @@
+{% extends "pages/interstitial_page.html" %}
+
+{% block interstitial_content %}
+<p>
+ The sign-in link has either expired or has already been used.
+</p>
+<p>
+ Sign-in again to generate a new link.
+</p>
+<div>
+ <a id="player-signin-link" href="{% url 'user_signin' %}"
+ class="btn btn-lg btn-primary">
+ <b>SIGN IN</b>
+ </a>
+</div>
+{% endblock %}
diff --git a/src/hi/apps/user/transient_models.py b/src/hi/apps/user/transient_models.py
new file mode 100644
index 00000000..830a9196
--- /dev/null
+++ b/src/hi/apps/user/transient_models.py
@@ -0,0 +1,55 @@
+import logging
+
+from django.contrib.auth.models import User as UserType
+from django.contrib.auth.tokens import PasswordResetTokenGenerator
+from django.http import HttpRequest
+
+from .magic_code_generator import MagicCodeGenerator
+from . import forms
+
+logger = logging.getLogger(__name__)
+
+
+class UserAuthenticationData:
+
+ def __init__( self, request : HttpRequest, override_user : UserType = None ):
+ if override_user:
+ self._user = override_user
+ else:
+ self._user = request.user
+
+ self._email_address = self._user.email
+
+ # We re-purpose the clever way tokens are used for password resets in Django
+ token_generator = PasswordResetTokenGenerator()
+ self._token = token_generator.make_token( user = self._user )
+
+ magic_code_generator = MagicCodeGenerator()
+ self._magic_code = magic_code_generator.make_magic_code( request )
+
+ self._magic_code_form = forms.SigninMagicCodeForm(
+ initial = { 'email_address': self._email_address }
+ )
+ logger.debug( f'UserAuthenticationData: EMAIL = {self._user},'
+ f'TOKEN = {self._token}, CODE = {self._magic_code}' )
+ return
+
+ @property
+ def user(self):
+ return self._user
+
+ @property
+ def email_address(self):
+ return self._email_address
+
+ @property
+ def token(self):
+ return self._token
+
+ @property
+ def magic_code(self):
+ return self._magic_code
+
+ @property
+ def magic_code_form(self):
+ return self._magic_code_form
diff --git a/src/hi/apps/user/urls.py b/src/hi/apps/user/urls.py
new file mode 100644
index 00000000..83c5a6c9
--- /dev/null
+++ b/src/hi/apps/user/urls.py
@@ -0,0 +1,19 @@
+from django.urls import re_path
+
+from . import views
+
+
+urlpatterns = [
+
+ re_path( r'^signin$',
+ views.UserSigninView.as_view(),
+ name='user_signin'),
+
+ re_path( r"^signin/magic/code$",
+ views.SigninMagicCodeView.as_view(),
+ name="user_signin_magic_code"),
+
+ re_path( r"^signin/magic/link/(?P<token>[\w\-]+)/(?P<email>.+)$",
+ views.SigninMagicLinkView.as_view(),
+ name="user_signin_magic_link"),
+]
diff --git a/src/hi/apps/user/views.py b/src/hi/apps/user/views.py
new file mode 100644
index 00000000..464e79db
--- /dev/null
+++ b/src/hi/apps/user/views.py
@@ -0,0 +1,165 @@
+import logging
+
+from django.contrib.auth import get_user_model
+from django.contrib.auth.models import User as UserType
+from django.contrib.auth.tokens import PasswordResetTokenGenerator
+from django.core.exceptions import BadRequest, ValidationError
+from django.core.validators import validate_email
+from django.http import HttpRequest, HttpResponseRedirect
+from django.shortcuts import render
+from django.urls import reverse
+from django.views.generic import View
+
+from . import forms
+from .magic_code_generator import MagicCodeStatus, MagicCodeGenerator
+from .signin_manager import SigninManager
+from .transient_models import UserAuthenticationData
+
+logger = logging.getLogger(__name__)
+
+
+class UserSigninView( View ):
+
+ def get(self, request, *args, **kwargs):
+ return render( request, 'user/pages/signin.html' )
+
+ def post(self, request, *args, **kwargs):
+ if request.user.is_authenticated:
+ raise BadRequest( 'You are already logged in.' )
+
+ email_address = request.POST.get('email')
+ if not email_address:
+ raise BadRequest( 'No email provided' )
+
+ try:
+ validate_email( email_address )
+ except ValidationError:
+ raise BadRequest( 'Invalid email provided' )
+
+ User = get_user_model()
+ try:
+ existing_user = User.objects.get( email = email_address )
+ logger.debug( f'Found existing user with email: {email_address}' )
+ return SendMagicLinkEmailView().send_signin_magic_link(
+ request = request,
+ override_user = existing_user,
+ )
+ except User.DoesNotExist:
+ # Show the same message so as not to give away whether account exists or not.
+ logger.debug( f'No user exists with email: {email_address}' )
+ return SigninMagicCodeView().get_response(
+ request = request,
+ magic_code_form = forms.SigninMagicCodeForm(
+ initial = { 'email_address': email_address }
+ )
+ )
+
+
+class SendMagicLinkEmailView( View ):
+
+ def send_signin_magic_link( self,
+ request : HttpRequest,
+ override_user : UserType = None ):
+
+ user_auth_data = UserAuthenticationData(
+ request = request,
+ override_user = override_user,
+ )
+ SigninManager().send_signin_magic_link_email(
+ request = request,
+ user_auth_data = user_auth_data,
+ )
+ return SigninMagicCodeView().get_response(
+ request = request,
+ magic_code_form = user_auth_data.magic_code_form,
+ )
+
+
+class SigninMagicCodeView( View ):
+
+ TEMPLATE_NAME = 'user/pages/magic_code_signin.html'
+
+ def get_response( self,
+ request : HttpRequest,
+ magic_code_form : forms.SigninMagicCodeForm,
+ status : int = 200 ):
+ context = {
+ 'magic_code_form': magic_code_form,
+ }
+ return render( request, self.TEMPLATE_NAME, context )
+
+ def post( self, request, *args, **kwargs ):
+
+ magic_code_form = forms.SigninMagicCodeForm( request.POST )
+ if not magic_code_form.is_valid():
+ return self.get_response( request, magic_code_form = magic_code_form, status = 400 )
+
+ email_address = magic_code_form.cleaned_data.get('email_address')
+ magic_code = magic_code_form.cleaned_data.get('magic_code')
+
+ User = get_user_model()
+ try:
+ existing_user = User.objects.get( email = email_address )
+ except User.DoesNotExist:
+ raise BadRequest( 'Email is invalid.' )
+
+ magic_code_generator = MagicCodeGenerator()
+ magic_code_status = magic_code_generator.check_magic_code( request, magic_code = magic_code )
+
+ if magic_code_status == MagicCodeStatus.INVALID:
+ error_message = 'Invalid access code.'
+ elif magic_code_status == MagicCodeStatus.EXPIRED:
+ error_message = 'Access code has expired.'
+ elif magic_code_status == MagicCodeStatus.VALID:
+ error_message = None
+ else:
+ error_message = 'Access code generated an unexpected error.'
+
+ logger.debug( f'Signin Magic: Email={email_address}, Code={magic_code}, Status={magic_code_status}' )
+
+ if error_message:
+ magic_code_form.add_error( 'magic_code', error_message )
+ return self.get_response( request, magic_code_form = magic_code_form, status = 400 )
+
+ logger.debug( f'Signin Magic: Email={email_address}, Code={magic_code}, Status={magic_code_status}' )
+
+ request.user = existing_user
+ SigninManager().do_login( request = request, verified_email = True )
+ magic_code_generator.expire_magic_code( request )
+
+ url = reverse( 'home' )
+ return HttpResponseRedirect( url )
+
+
+class SigninMagicLinkView( View ):
+ """ This is the view for the links we include in emails for logging in. """
+
+ def get( self, request, *args, **kwargs ):
+
+ token = kwargs.get('token')
+ email_address = kwargs.get('email')
+
+ if not token or not email_address:
+ raise BadRequest( 'Malformed request.' )
+
+ User = get_user_model()
+ try:
+ existing_user = User.objects.get( email = email_address )
+ except User.DoesNotExist:
+ return BadRequest( 'Email is not valid.' )
+
+ # We re-purpose the clever way tokens are used for password resets in Django
+ token_generator = PasswordResetTokenGenerator()
+ is_valid = token_generator.check_token( user = existing_user, token = token )
+
+ logger.debug( f'Signin Magic: EMAIL = {email_address}, TOKEN = {token}, VALID = {is_valid}' )
+
+ if not is_valid:
+ return render( request, 'user/pages/signin_magic_bad_link.html' )
+
+ request.user = existing_user
+ SigninManager().do_login( request = request, verified_email = True )
+
+ url = reverse( 'home' )
+ return HttpResponseRedirect( url )
+
diff --git a/src/hi/integrations/migrations/0001_initial.py b/src/hi/integrations/migrations/0001_initial.py
index 42f338c2..4f69d640 100644
--- a/src/hi/integrations/migrations/0001_initial.py
+++ b/src/hi/integrations/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 4.2.15 on 2025-01-23 15:57
+# Generated by Django 4.2.15 on 2025-01-27 18:15
from django.db import migrations, models
import django.db.models.deletion
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index ad97ff55..95c3d8e0 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -31,6 +31,12 @@ BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = get_env_variable('DJANGO_SECRET_KEY')
+DJANGO_SUPERUSER_EMAIL = get_env_variable( 'DJANGO_SUPERUSER_EMAIL', None )
+DJANGO_SUPERUSER_PASSWORD = get_env_variable( 'DJANGO_SUPERUSER_PASSWORD', None )
+
+AUTH_USER_MODEL = "custom.CustomUser"
+SUPPRESS_AUTHENTICATION = bool( get_env_variable( 'HI_SUPPRESS_AUTHENTICATION', 'false' ) == 'true' )
+
ALLOWED_HOSTS = [
'127.0.0.1',
'192.168.100.2',
@@ -135,7 +141,9 @@ INSTALLED_APPS = [
'pipeline',
'django.contrib.humanize',
'constance',
+ 'custom',
'hi.apps.common',
+ 'hi.apps.user',
'hi.apps.config',
'hi.apps.console',
'hi.apps.attribute',
@@ -169,6 +177,7 @@ MIDDLEWARE = [
'hi.middleware.ExceptionMiddleware',
'hi.middleware.ViewMiddleware',
'hi.apps.console.middleware.ConsoleLockMiddleware',
+ 'hi.apps.user.middleware.AuthenticationMiddleware',
]
ROOT_URLCONF = 'hi.urls'
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index a67c825d..3b73c231 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -780,6 +780,11 @@ function hideLoadingIniterstitial() {
$('#antinode-loader').hide();
};
+function synchronousSubmitHandler() {
+ $('#antinode-loader').show();
+ $( this ).find( 'button[type="submit"]' ).prop('disabled', true);
+}
+
//====================
// Adding handlers that look at special HTML tag attributes to determine
// which ones want to be done ansynchonously (aka, AJAX)
@@ -797,6 +802,7 @@ jQuery(function($) {
$('body').on('click', 'a[data-async]', asyncClickHandler );
$('body').on('click', 'div[data-async]', asyncClickHandler );
$('body').on('click', 'form[data-async] button', lastButtonClickHandler );
+ $('body').on('submit', 'form[data-synchronous]', synchronousSubmitHandler );
// This is to support auto-submitting from SELECT elements asnychronously.
//
diff --git a/src/hi/templates/pages/error_base.html b/src/hi/templates/pages/error_base.html
index f1729c28..e4c85ad5 100644
--- a/src/hi/templates/pages/error_base.html
+++ b/src/hi/templates/pages/error_base.html
@@ -1,7 +1,7 @@
-{% extends "pages/base.html" %}
+{% extends "pages/interstitial_page.html" %}
-{% block content %}
-<h1>{% block title %}Error{% endblock %}</h1>
+{% block interstitial_content %}
+<h1 class="text-danger">{% block title %}Error{% endblock %}</h1>
<div>
{{ error_message }}
diff --git a/src/hi/templates/pages/interstitial_page.html b/src/hi/templates/pages/interstitial_page.html
new file mode 100644
index 00000000..b58e58f9
--- /dev/null
+++ b/src/hi/templates/pages/interstitial_page.html
@@ -0,0 +1,19 @@
+{% extends "pages/base.html" %}
+{% load static %}
+
+{% block content %}
+<div class="container-fluid hi-interstitial-page">
+ <div class="hi-start-heading col-4">
+ <div class="">
+ <img class="img-fluid" src="{% static 'img/hi-logo-467x200.png' %}" alt="Home Information Logo" />
+ </div>
+ <div class="">
+ <em>Your home, your data, organized.</em>
+ </div>
+ </div>
+ <div class="hi-interstitial-page-content">
+ {% block interstitial_content %}
+ {% endblock %}
+ </div>
+</div>
+{% endblock %}
diff --git a/src/hi/templates/pages/start.html b/src/hi/templates/pages/start.html
index 65c67e6d..beb1fa33 100644
--- a/src/hi/templates/pages/start.html
+++ b/src/hi/templates/pages/start.html
@@ -1,32 +1,20 @@
-{% extends "pages/base.html" %}
-{% load static %}
+{% extends "pages/interstitial_page.html" %}
-{% block content %}
-<div class="container-fluid hi-interstitial-page">
- <div class="hi-start-heading col-4">
- <div class="">
- <img class="img-fluid" src="{% static 'img/hi-logo-467x200.png' %}" alt="Home Information Logo" />
- </div>
- <div class="">
- <em>Your home, your data, organized.</em>
- </div>
- </div>
-
- <div class="hi-interstitial-page-content">
- <div class="display-4">Welcome!</div>
- <p class="lead mt-2 mb-4">
- To get started, add your home's name to create a new location.
- </p>
- <div class="">
- <a role="button" class="btn btn-primary"
- href="{% url 'location_edit_location_add_first' %}"
- data-async="modal">
- ADD MY LOCATION
- </a>
- </div>
- <p class="text-muted mt-4">
- Optionally, you can upload an SVG image of your home or property layout.
- </p>
+{% block interstitial_content %}
+<div>
+ <div class="display-4">Welcome!</div>
+ <p class="lead mt-2 mb-4">
+ To get started, add your home's name to create a new location.
+ </p>
+ <div class="">
+ <a role="button" class="btn btn-primary"
+ href="{% url 'location_edit_location_add_first' %}"
+ data-async="modal">
+ ADD MY LOCATION
+ </a>
</div>
+ <p class="text-muted mt-4">
+ Optionally, you can upload an SVG image of your home or property layout.
+ </p>
</div>
{% endblock %}
diff --git a/src/hi/urls.py b/src/hi/urls.py
index a77bb86f..885eda41 100644
--- a/src/hi/urls.py
+++ b/src/hi/urls.py
@@ -27,6 +27,7 @@ urlpatterns = [
re_path( r'^index.html$', views.HomeView.as_view(), name='home_index' ),
re_path( r'^start$', views.StartView.as_view(), name='start' ),
+ re_path( r'^user/', include('hi.apps.user.urls' )),
re_path( r'^api/', include('hi.apps.api.urls' )),
re_path( r'^config/', include('hi.apps.config.urls' )),
re_path( r'^edit/', include('hi.apps.edit.urls' )),