clean_user_accounts.py 1.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import logging

from django.contrib.sessions.management.commands.clearsessions import (
    Command as ClearSessionCommand,
)
from django.core.management.base import BaseCommand
from django_cas_ng.models import ProxyGrantingTicket, SessionTicket

from backend_app.models.recommendationList import RecommendationList
from backend_app.models.userData import UserData
from backend_app.utils import get_default_theme_settings
from base_app.models import User

logger = logging.getLogger("django")


class Command(BaseCommand):
    help = "Command to handle user accounts emptying"

    def handle(self, *args, **options):
        logger.info("here")
        for user in User.objects.filter(delete_next_time=True):
            logger.info("Emptying account of user {}".format(user.pk))

            # for user Data we don't delete it but restore it to default
            # We do this to be consistent with the assumption that each user has some userData
            user_data = UserData.objects.get(pk=user.pk)
            user_data.theme = get_default_theme_settings()
            user_data.save()

            # deleting all owned private lists
            RecommendationList.objects.filter(owner=user, is_public=False).delete()

            # Emptying user model
            user.allow_sharing_personal_info = False
            user.secondary_email = ""
            user.pseudo = "Del."
            user.has_validated_cgu_rgpd = False
            user.is_banned = False

            user.username = "__Deleted__{}".format(user.pk)
            user.email = ""
            user.is_active = False

            user.delete_next_time = False
            user.is_deleted = True

            user.save()

        # Finally we clear the sessions
        ClearSessionCommand().handle()
        ProxyGrantingTicket.clean_deleted_sessions()
        SessionTicket.clean_deleted_sessions()
        # Still error 500 on delete then reconnect... Unknown