Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Create entries in EmailAddress for users created by gym and auth headers

Roland Geider9ea02be8a5d6
diff --git a/wger/core/backends.py b/wger/core/backends.py
index e4afd0721..05f061499 100644
--- a/wger/core/backends.py
+++ b/wger/core/backends.py
@@ -19,6 +19,10 @@ import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import BaseBackend
+from django.db import IntegrityError
+
+# Third Party
+from allauth.account.models import EmailAddress
logger = logging.getLogger(__name__)
@@ -60,6 +64,23 @@ class AuthProxyUserBackend(BaseBackend):
except Exception as e:
logger.error(f"AuthProxy: Failed to create user '{username}': {e}")
return None
+
+ # Register the email with allauth so login by email works. The
+ # proxy is a trusted identity source, so the address counts as
+ # verified.
+ if email:
+ try:
+ EmailAddress.objects.create(
+ user=user,
+ email=email,
+ verified=True,
+ primary=True,
+ )
+ except IntegrityError:
+ logger.warning(
+ f"AuthProxy: email '{email}' already registered, "
+ f"skipping EmailAddress row for '{username}'"
+ )
else:
logger.warning(
f"AuthProxy: User '{username}' not found and auto-creation is disabled."
diff --git a/wger/core/migrations/0023_backfill_emailaddress.py b/wger/core/migrations/0023_backfill_emailaddress.py
new file mode 100644
index 000000000..a2399dfd1
--- /dev/null
+++ b/wger/core/migrations/0023_backfill_emailaddress.py
@@ -0,0 +1,48 @@
+from django.db import migrations
+
+
+"""
+Backfill allauth EmailAddress rows for users that have a User.email but no
+EmailAddress row at all.
+
+Migration 0022 backfilled all users that existed at the time, but some code
+paths (gym member creation, the auth proxy backend) created users without an
+EmailAddress row afterwards.
+"""
+
+
+def backfill_email_addresses(apps, schema_editor):
+ User = apps.get_model('auth', 'User')
+ EmailAddress = apps.get_model('account', 'EmailAddress')
+
+ users_with_row = set(EmailAddress.objects.values_list('user_id', flat=True))
+ existing_emails = {e.lower() for e in EmailAddress.objects.values_list('email', flat=True)}
+
+ rows = []
+ for user in User.objects.exclude(email='').exclude(email__isnull=True):
+ if user.pk in users_with_row:
+ continue
+ if user.email.lower() in existing_emails:
+ continue
+ existing_emails.add(user.email.lower())
+ rows.append(
+ EmailAddress(
+ user=user,
+ email=user.email,
+ verified=False,
+ primary=True,
+ )
+ )
+
+ EmailAddress.objects.bulk_create(rows, ignore_conflicts=True)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ('core', '0022_move_email_verified_to_emailaddress'),
+ ('account', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_email_addresses, migrations.RunPython.noop),
+ ]
diff --git a/wger/gym/views/gym.py b/wger/gym/views/gym.py
index 96d449e85..b8f4e9ff1 100644
--- a/wger/gym/views/gym.py
+++ b/wger/gym/views/gym.py
@@ -55,6 +55,7 @@ from django.views.generic import (
)
# Third Party
+from allauth.account.models import EmailAddress
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
@@ -410,6 +411,11 @@ class GymAddUserView(
user.userprofile.birthdate = form.cleaned_data['birthdate']
user.userprofile.save()
+ # Register the email with allauth so the member can log in by email
+ # and receive a confirmation link
+ if user.email:
+ EmailAddress.objects.add_email(self.request, user, user.email, confirm=True)
+
# Set appropriate permission groups
if 'user' in form.cleaned_data['role']:
user.groups.add(Group.objects.get(name='gym_member'))