|
| 1 | +from django.core.management.base import BaseCommand |
| 2 | +from django.db.models import Count |
| 3 | +from django.db.models.functions import Lower |
| 4 | +import logging |
| 5 | +from users.models import UserPermission |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | + |
| 10 | +class Command(BaseCommand): |
| 11 | + """ |
| 12 | + Django management command for cleaning up tribal access emails. |
| 13 | + This includes lowercasing all emails, and also deleting duplicates (with null user field). |
| 14 | + """ |
| 15 | + |
| 16 | + def add_arguments(self, parser): |
| 17 | + parser.add_argument( |
| 18 | + "--count", |
| 19 | + action="store_true", |
| 20 | + help="Only logs the number of duplicates without modifying the database.", |
| 21 | + ) |
| 22 | + |
| 23 | + def handle(self, *args, **options): |
| 24 | + |
| 25 | + fixed_emails = 0 |
| 26 | + removed_duplicates = 0 |
| 27 | + |
| 28 | + # first, gather number of duplicate emails that exist. |
| 29 | + duplicates = ( |
| 30 | + UserPermission.objects.values(loweremail=Lower("email")) |
| 31 | + .annotate(ecount=Count("id")) |
| 32 | + .filter(ecount__gt=1) |
| 33 | + ) |
| 34 | + logger.info( |
| 35 | + f"Identified {duplicates.count()} duplicate emails for tribal access." |
| 36 | + ) |
| 37 | + |
| 38 | + if options.get("count"): |
| 39 | + exit(0) |
| 40 | + |
| 41 | + # then, lowercase all emails. |
| 42 | + userpermissions = UserPermission.objects.all() |
| 43 | + for userpermission in userpermissions: |
| 44 | + if userpermission.email: |
| 45 | + if userpermission.email != userpermission.email.lower(): |
| 46 | + userpermission.email = userpermission.email.lower() |
| 47 | + userpermission.save() |
| 48 | + fixed_emails += 1 |
| 49 | + logger.info(f"Removed uppercasing on {fixed_emails} tribal access emails.") |
| 50 | + |
| 51 | + # finally, remove duplicates (that have a null user field). |
| 52 | + userpermissions = UserPermission.objects.filter(user=None) |
| 53 | + for userpermission in userpermissions: |
| 54 | + if ( |
| 55 | + UserPermission.objects.filter(email=userpermission.email) |
| 56 | + .exclude(user=None) |
| 57 | + .exists() |
| 58 | + ): |
| 59 | + userpermission.delete() |
| 60 | + removed_duplicates += 1 |
| 61 | + logger.info( |
| 62 | + f"Removed 'blank user' for {removed_duplicates} duplicate tribal access emails." |
| 63 | + ) |
0 commit comments