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.

41 lines
1.4 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
  5. from django.utils import timezone
  6. class Command(BaseCommand):
  7. help = """Prune old, inactive user accounts.
  8. Conditions for removing an user account:
  9. - created 6 months ago and never logged in. Does not belong
  10. to any team.
  11. Use case: visitor types in their email at the website but
  12. never follows through with login.
  13. - not logged in for 6 months, and has no checks. Does not
  14. belong to any team.
  15. Use case: user wants to remove their account. So they
  16. remove all checks and leave the account at that.
  17. """
  18. def handle(self, *args, **options):
  19. cutoff = timezone.now() - timedelta(days=180)
  20. # Old accounts, never logged in, no team memberships
  21. q = User.objects
  22. q = q.annotate(n_teams=Count("memberships"))
  23. q = q.filter(date_joined__lt=cutoff, last_login=None, n_teams=0)
  24. n1, _ = q.delete()
  25. # Not logged in for 1 month, 0 checks, no team memberships
  26. q = User.objects
  27. q = q.annotate(n_checks=Count("check"))
  28. q = q.annotate(n_teams=Count("memberships"))
  29. q = q.filter(last_login__lt=cutoff, n_checks=0, n_teams=0)
  30. n2, _ = q.delete()
  31. return "Done! Pruned %d user accounts." % (n1 + n2)