<commit_before>from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.db.models.signals import pre_save, post_save
from django.db import IntegrityError
from django.utils.functional import curry
from awx.main.models import ActivityStream, AuthToken
import json
import uuid
import urllib2

import logging
logger = logging.getLogger('awx.main.middleware')

class ActivityStreamMiddleware(object):

    def __init__(self):
        self.disp_uid = None

    def process_request(self, request):
        if hasattr(request, 'user') and hasattr(request.user, 'is_authenticated') and request.user.is_authenticated():
            user = request.user
        else:
            user = None

        self.instances = []
        set_actor = curry(self.set_actor, user)
        self.disp_uid = str(uuid.uuid1())
        post_save.connect(set_actor, sender=ActivityStream, dispatch_uid=self.disp_uid, weak=False)

    def process_response(self, request, response):
        drf_request = getattr(request, 'drf_request', None)
        drf_user = getattr(drf_request, 'user', None)
        if self.disp_uid is not None:
            post_save.disconnect(dispatch_uid=self.disp_uid)
        for instance_id in self.instances:
            instance = ActivityStream.objects.filter(id=instance_id)
            if instance.exists():
                instance = instance[0]
            else:
                logger.debug("Failed to look up Activity Stream instance for id : " + str(instance_id))
                continue

            if drf_user is not None and drf_user.__class__ != AnonymousUser:
                instance.user = drf_user
                try:
                    instance.save()
                except IntegrityError, e:
                    logger.debug("Integrity Error saving Activity Stream instance for id : " + str(instance_id))
            else:
                obj1_type_actual = instance.object1_type.split(".")[-1]
                if obj1_type_actual in ("InventoryUpdate", "ProjectUpdate", "Job") and instance.id is not None:
                    instance.delete()
        return response<commit_msg>Fix issue AC-761, issue with the activity stream middleware could throw exception during authentication<commit_after>from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.db.models.signals import pre_save, post_save
from django.db import IntegrityError
from django.utils.functional import curry
from awx.main.models import ActivityStream, AuthToken
import json
import uuid
import urllib2

import logging
logger = logging.getLogger('awx.main.middleware')

class ActivityStreamMiddleware(object):

    def __init__(self):
        self.disp_uid = None
        self.instances = []

    def process_request(self, request):
        if hasattr(request, 'user') and hasattr(request.user, 'is_authenticated') and request.user.is_authenticated():
            user = request.user
        else:
            user = None

        set_actor = curry(self.set_actor, user)
        self.disp_uid = str(uuid.uuid1())
        post_save.connect(set_actor, sender=ActivityStream, dispatch_uid=self.disp_uid, weak=False)

    def process_response(self, request, response):
        drf_request = getattr(request, 'drf_request', None)
        drf_user = getattr(drf_request, 'user', None)
        if self.disp_uid is not None:
            post_save.disconnect(dispatch_uid=self.disp_uid)
        for instance_id in self.instances:
            instance = ActivityStream.objects.filter(id=instance_id)
            if instance.exists():
                instance = instance[0]
            else:
                logger.debug("Failed to look up Activity Stream instance for id : " + str(instance_id))
                continue

            if drf_user is not None and drf_user.__class__ != AnonymousUser:
                instance.user = drf_user
                try:
                    instance.save()
                except IntegrityError, e:
                    logger.debug("Integrity Error saving Activity Stream instance for id : " + str(instance_id))
            else:
                obj1_type_actual = instance.object1_type.split(".")[-1]
                if obj1_type_actual in ("InventoryUpdate", "ProjectUpdate", "Job") and instance.id is not None:
                    instance.delete()
        return response
{'fraction_non_alphanumeric': 0.08386508659981769, 'fraction_numerical': 0.0038742023701002735, 'mean_word_length': 2.5366639806607574, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7183108', 'n_tokens_mistral': 1204, 'n_tokens_neox': 1159, 'n_words': 312}