Update post_save to work with Contact

This commit is contained in:
Seamus Johnston 2023-03-07 11:07:20 -06:00
parent 7815d58c2c
commit b65f1a63d3
No known key found for this signature in database
GPG key ID: 2F21225985069105
5 changed files with 180 additions and 19 deletions

View file

@ -5,7 +5,7 @@ from django.core.management import call_command
from django.db.models.signals import post_save, post_migrate
from django.dispatch import receiver
from .models import User, UserProfile
from .models import User, Contact
logger = logging.getLogger(__name__)
@ -15,18 +15,46 @@ logger = logging.getLogger(__name__)
def handle_profile(sender, instance, **kwargs):
"""Method for when a User is saved.
If the user is being created, then create a matching UserProfile. Otherwise
save an updated profile or create one if it doesn't exist.
A first time registrant may have been invited, so we'll search for a matching
Contact record, by email address, and associate them, if possible.
A first time registrant may not have a matching Contact, so we'll create one,
copying the contact values we received from Login.gov in order to initialize it.
During subsequent login, a User record may be updated with new data from Login.gov,
but in no case will we update contact values on an existing Contact record.
"""
if kwargs.get("created", False):
UserProfile.objects.create(user=instance)
first_name = getattr(instance, "first_name", "")
last_name = getattr(instance, "last_name", "")
email = getattr(instance, "email", "")
phone = getattr(instance, "phone", "")
is_new_user = kwargs.get("created", False)
if is_new_user:
contacts = Contact.objects.filter(email=email)
else:
# the user is not being created.
if hasattr(instance, "userprofile"):
instance.userprofile.save()
else:
UserProfile.objects.create(user=instance)
contacts = Contact.objects.filter(user=instance)
if len(contacts) == 0: # no matching contact
Contact.objects.create(
user=instance,
first_name=first_name,
last_name=last_name,
email=email,
phone=phone,
)
if len(contacts) >= 1 and is_new_user: # a matching contact
contacts[0].user = instance
contacts[0].save()
if len(contacts) > 1: # multiple matches
logger.warning(
"There are multiple Contacts with the same email address."
f" Picking #{contacts[0].id} for User #{instance.id}."
)
@receiver(post_migrate)