You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.5 KiB

  1. from datetime import timedelta
  2. from django.contrib.auth.models import User
  3. from django.core.management.base import BaseCommand
  4. from django.db.models import Count, F
  5. from django.utils.timezone import now
  6. from hc.accounts.models import Profile
  7. class Command(BaseCommand):
  8. help = """Prune old, inactive user accounts.
  9. Conditions for removing an user account:
  10. - created 1 month ago and never logged in. Does not belong
  11. to any team.
  12. Use case: visitor types in their email at the website but
  13. never follows through with login.
  14. """
  15. def handle(self, *args, **options):
  16. month_ago = now() - timedelta(days=30)
  17. # Old accounts, never logged in, no team memberships
  18. q = User.objects.order_by("id")
  19. q = q.annotate(n_teams=Count("memberships"))
  20. q = q.filter(date_joined__lt=month_ago, last_login=None, n_teams=0)
  21. n, summary = q.delete()
  22. count = summary.get("auth.User", 0)
  23. self.stdout.write("Pruned %d never-logged-in user accounts." % count)
  24. # Profiles scheduled for deletion
  25. q = Profile.objects.order_by("id")
  26. q = q.filter(deletion_notice_date__lt=month_ago)
  27. # Exclude users who have logged in after receiving deletion notice
  28. q = q.exclude(user__last_login__gt=F("deletion_notice_date"))
  29. for profile in q:
  30. self.stdout.write("Deleting inactive %s" % profile.user.email)
  31. profile.user.delete()
  32. return "Done!"