Esempio n. 1
0
def update_hitcount(session_key, ip_address, user_agent, user_id, app_label, model, object_id):

    try:
        user = get_user_model().objects.get(pk=user_id)
    except ObjectDoesNotExist:
        user = AnonymousUser()

    ctype = ContentType.objects.get(app_label=app_label, model=model)

    hitcount, created = HitCount.objects.get_or_create(
        content_type=ctype, object_pk=object_id)

    hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)
    exclude_user_group = getattr(settings, 'HITCOUNT_EXCLUDE_USER_GROUP', None)

    # first, check our request against the IP blacklist
    if BlacklistIP.objects.filter(ip__exact=ip_address):
        return False

    # second, check our request against the user agent blacklist
    if BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
        return False

    # third, see if we are excluding a specific user group or not
    if exclude_user_group and not isinstance(user, AnonymousUser):
        if user.groups.filter(name__in=exclude_user_group):
            return False

    # eliminated first three possible exclusions, now on to checking our database of
    # active hits to see if we should count another one
    
    # start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE)
    qs = Hit.objects.filter_active()

    # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
    if hits_per_ip_limit:
        if qs.filter(ip__exact=ip_address).count() >= hits_per_ip_limit:
            return False

    # create a generic Hit object with request data
    hit = Hit(session=session_key, hitcount=hitcount, ip=ip_address,
              user_agent=user_agent)

    # first, use a user's authentication to see if they made an earlier hit
    if not isinstance(user, AnonymousUser):
        if not qs.filter(user=user, hitcount=hitcount):
            hit.user = user  # associate this hit with a user
            hit.save()

            return True

    # if not authenticated, see if we have a repeat session
    else:
        if not qs.filter(session=session_key, hitcount=hitcount):
            hit.save()

            return True

    return False
Esempio n. 2
0
    def __importHitCountDetails(self, zip, fingerprint, hitmap, replacing):
        hitdetails = json.loads(zip.read('hitcount_detail.json'), object_hook=json_util.object_hook)

        for hitdetail in hitdetails:

            this_hitdetail = Hit()

            if replacing:
                hitdetail['hitcount_id'] = hitmap[hitdetail['hitcount_id']]

                del hitdetail['id']

            try:
                this_user = User.objects.get(id=hitdetail['user_id'])
            except:
                hitdetail['user_id'] = -1

            this_hitdetail.__dict__.update(hitdetail)

            this_hitdetail.save()
    def __importHitCountDetails(self, zip, fingerprint, hitmap, replacing):
        hitdetails = json.loads(zip.read('hitcount_detail.json'),
                                object_hook=json_util.object_hook)

        for hitdetail in hitdetails:

            this_hitdetail = Hit()

            if replacing:
                hitdetail['hitcount_id'] = hitmap[hitdetail['hitcount_id']]

                del hitdetail['id']

            try:
                this_user = User.objects.get(id=hitdetail['user_id'])
            except:
                hitdetail['user_id'] = -1

            this_hitdetail.__dict__.update(hitdetail)

            this_hitdetail.save()
Esempio n. 4
0
def _update_hit_count(request, hitcount):
    '''
    Evaluates a request's Hit and corresponding HitCount object and,
    after a bit of clever logic, either ignores the request or registers
    a new Hit.

    This is NOT a view!  But should be used within a view ...

    Returns True if the request was considered a Hit; returns False if not.
    '''
    user = request.user
    session_key = request.session.session_key
    ip = get_ip(request)
    user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
    hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)
    exclude_user_group = getattr(settings, 
                            'HITCOUNT_EXCLUDE_USER_GROUP', None)

    # first, check our request against the blacklists before continuing
    if BlacklistIP.objects.filter(ip__exact=ip) or \
            BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
        return False

    # second, see if we are excluding a specific user group or not
    if exclude_user_group and user.is_authenticated():
        if user.groups.filter(name__in=exclude_user_group):
            return False

    #start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE )
    qs = Hit.objects.filter_active() 

    # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
    if hits_per_ip_limit:
        if qs.filter(ip__exact=ip).count() > hits_per_ip_limit:
            return False

    # create a generic Hit object with request data
    hit = Hit(  session=session_key,
                hitcount=hitcount,
                ip=get_ip(request),
                user_agent=request.META.get('HTTP_USER_AGENT', '')[:255],)

    # first, use a user's authentication to see if they made an earlier hit
    if user.is_authenticated():
        if not qs.filter(user=user,hitcount=hitcount):
            hit.user = user #associate this hit with a user
            hit.save()
            return True

    # if not authenticated, see if we have a repeat session
    else:
        if not qs.filter(session=session_key,hitcount=hitcount):
            hit.save()

            # forces a save on this anonymous users session
            request.session.modified = True

            return True

    return False 
Esempio n. 5
0
def _update_hit_count(request, hitcount):
    '''
    Evaluates a request's Hit and corresponding HitCount object and,
    after a bit of clever logic, either ignores the request or registers
    a new Hit.

    This is NOT a view!  But should be used within a view ...

    Returns True if the request was considered a Hit; returns False if not.
    '''
    user = request.user

    if not request.session.session_key:
        request.session.save()

    session_key = request.session.session_key
    ip = get_ip(request)
    user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
    hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)
    exclude_user_group = getattr(settings, 'HITCOUNT_EXCLUDE_USER_GROUP', None)

    # first, check our request against the blacklists before continuing
    if BlacklistIP.objects.filter(ip__exact=ip) or \
            BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
        return False

    # second, see if we are excluding a specific user group or not
    if exclude_user_group and user.is_authenticated():
        if user.groups.filter(name__in=exclude_user_group):
            return False

    #start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE )
    qs = Hit.objects.filter_active()

    # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
    if hits_per_ip_limit:
        if qs.filter(ip__exact=ip).count() > hits_per_ip_limit:
            return False

    # create a generic Hit object with request data
    hit = Hit(
        session=session_key,
        hitcount=hitcount,
        ip=get_ip(request),
        user_agent=request.META.get('HTTP_USER_AGENT', '')[:255],
    )

    # first, use a user's authentication to see if they made an earlier hit
    if user.is_authenticated():
        if not qs.filter(user=user, hitcount=hitcount):
            hit.user = user  #associate this hit with a user
            hit.save()
            return True

    # if not authenticated, see if we have a repeat session
    else:
        if not qs.filter(session=session_key, hitcount=hitcount):
            hit.save()

            # forces a save on this anonymous users session
            request.session.modified = True

            return True

    return False
Esempio n. 6
0
    def hit_count(self, request, hitcount):
        """
        Called with a HttpRequest and HitCount object it will return a
        namedtuple:

        UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message').

        `hit_counted` will be True if the hit was counted and False if it was
        not.  `'hit_message` will indicate by what means the Hit was either
        counted or ignored.
        """
        UpdateHitCountResponse = namedtuple(
            'UpdateHitCountResponse', 'hit_counted hit_message')

        # as of Django 1.8.4 empty sessions are not being saved
        # https://code.djangoproject.com/ticket/25489
        if request.session.session_key is None:
            request.session.save()

        user = request.user
        try:
            is_authenticated_user = user.is_authenticated()
        except:
            is_authenticated_user = user.is_authenticated
        session_key = request.session.session_key
        ip = get_ip(request)
        user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
        hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)
        exclude_user_group = getattr(settings, 'HITCOUNT_EXCLUDE_USER_GROUP', None)

        # first, check our request against the IP blacklist
        if BlacklistIP.objects.filter(ip__exact=ip):
            return UpdateHitCountResponse(
                False, 'Not counted: user IP has been blacklisted')

        # second, check our request against the user agent blacklist
        if BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
            return UpdateHitCountResponse(
                False, 'Not counted: user agent has been blacklisted')

        # third, see if we are excluding a specific user group or not
        if exclude_user_group and is_authenticated_user:
            if user.groups.filter(name__in=exclude_user_group):
                return UpdateHitCountResponse(
                    False, 'Not counted: user excluded by group')

        # eliminated first three possible exclusions, now on to checking our database of
        # active hits to see if we should count another one

        # start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE)
        qs = Hit.objects.filter_active()

        # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
        if hits_per_ip_limit:
            if qs.filter(ip__exact=ip).count() >= hits_per_ip_limit:
                return UpdateHitCountResponse(
                    False, 'Not counted: hits per IP address limit reached')

        # create a generic Hit object with request data
        hit = Hit(session=session_key, hitcount=hitcount, ip=get_ip(request),
                  user_agent=request.META.get('HTTP_USER_AGENT', '')[:255],)

        # first, use a user's authentication to see if they made an earlier hit
        if is_authenticated_user:
            if not qs.filter(user=user, hitcount=hitcount):
                hit.user = user  # associate this hit with a user
                hit.save()

                response = UpdateHitCountResponse(
                    True, 'Hit counted: user authentication')
            else:
                response = UpdateHitCountResponse(
                    False, 'Not counted: authenticated user has active hit')

        # if not authenticated, see if we have a repeat session
        else:
            if not qs.filter(session=session_key, hitcount=hitcount):
                hit.save()
                response = UpdateHitCountResponse(
                    True, 'Hit counted: session key')
            else:
                response = UpdateHitCountResponse(
                    False, 'Not counted: session key has active hit')

        return response
Esempio n. 7
0
def _update_hit_count(request, hitcount):
    """
    Evaluates a request's Hit and corresponding HitCount object and,
    after a bit of clever logic, either ignores the request or registers
    a new Hit.

    This is NOT a view!  But should be used within a view ...

    Returns True if the request was considered a Hit; returns False if not.
    """

    UpdateHitCountResponse = namedtuple('UpdateHitCountResponse',
        'hit_counted hit_message')

    user = request.user
    session_key = request.session.session_key
    ip = get_ip(request)
    user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
    hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)
    exclude_user_group = getattr(settings, 'HITCOUNT_EXCLUDE_USER_GROUP', None)

    # first, check our request against the IP blacklist
    if BlacklistIP.objects.filter(ip__exact=ip):
        response = UpdateHitCountResponse(False,
            'Not counted: user IP has been blacklisted')
        return response

    # second, check our request against the user agent blacklist
    if BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
        response = UpdateHitCountResponse(False,
            'Not counted: user agent has been blacklisted')
        return response

    # third, see if we are excluding a specific user group or not
    if exclude_user_group and user.is_authenticated():
        if user.groups.filter(name__in=exclude_user_group):
            response = UpdateHitCountResponse(False,
                'Not counted: user excluded by group')
            return response

    # eliminated first three possible exclusions, now on to checking our database of
    # active hits to see if we should count another one

    # start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE)
    qs = Hit.objects.filter_active()

    # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
    if hits_per_ip_limit:
        if qs.filter(ip__exact=ip).count() >= hits_per_ip_limit:
            response = UpdateHitCountResponse(False,
                'Not counted: hits per IP address limit reached')
            return response

    # create a generic Hit object with request data
    hit = Hit(session=session_key, hitcount=hitcount, ip=get_ip(request),
        user_agent=request.META.get('HTTP_USER_AGENT', '')[:255],)

    # first, use a user's authentication to see if they made an earlier hit
    if user.is_authenticated():
        if not qs.filter(user=user, hitcount=hitcount):
            hit.user = user  # associate this hit with a user
            hit.save()

            response = UpdateHitCountResponse(True,
                'Hit counted: user authentication')
        else:
            response = UpdateHitCountResponse(False,
                'Not counted: authenticated user has active hit')

    # if not authenticated, see if we have a repeat session
    else:
        if not qs.filter(session=session_key, hitcount=hitcount):
            hit.save()
            response = UpdateHitCountResponse(True,
                'Hit counted: session key')
        else:
            response = UpdateHitCountResponse(False,
                'Not counted: session key has active hit')

    return response
Esempio n. 8
0
def _update_hit_count(request, hitcount):
    '''
    Desn't store IP nor user_agent,
    but check that IP is not blacklisted

    Evaluates a request's Hit and corresponding HitCount object and,
    after a bit of clever logic, either ignores the request or registers
    a new Hit.

    This is NOT a view!  But should be used within a view ...

    Returns True if the request was considered a Hit; returns False if not.
    '''

    # when this is not called by ajax
    if type(request) == RequestContext:
        request = request['request']

    user = request.user

    if not request.session.session_key:
        request.session.save()

    session_key = request.session.session_key
    ip = get_ip(request)
    user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
    logger.debug('session key: ' + session_key)
    logger.debug('CSRF_COOKIE: ' + request.META.get('CSRF_COOKIE'))


    hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)


    # first, check our request against the blacklists before continuing
    # exclude hits from localhost when not debugging
    # currently the list of bots doesn't have the entire text

    if BlacklistIP.objects.filter(ip__exact=ip) or \
            BlacklistUserAgent.objects.filter(user_agent__contains=user_agent):
        return False

    # don't store hit if user authenticated
    if user.is_authenticated():
        return False

    #start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE )
    qs = Hit.objects.filter_active()

    # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
    if hits_per_ip_limit:
        if qs.filter(ip__exact=ip).count() > hits_per_ip_limit:
            return False

    # create a generic Hit object with request data
    hit = Hit(  session=session_key,
                hitcount=hitcount,)

    if not qs.filter(session=session_key,hitcount=hitcount):
        hit.save()
        logger.debug('hit saved')

        # forces a save on this anonymous users session
        request.session.modified = True

        return True
    return False
Esempio n. 9
0
    def hit_count(self, request, hitcount):
        """
        Called with a HttpRequest and HitCount object it will return a
        namedtuple:

        UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message').

        `hit_counted` will be True if the hit was counted and False if it was
        not.  `'hit_message` will indicate by what means the Hit was either
        counted or ignored.
        """
        UpdateHitCountResponse = namedtuple(
            'UpdateHitCountResponse', 'hit_counted hit_message')

        # as of Django 1.8.4 empty sessions are not being saved
        # https://code.djangoproject.com/ticket/25489
        if request.session.session_key is None:
            request.session.save()

        user = request.user
        try:
            is_authenticated_user = user.is_authenticated()
        except:
            is_authenticated_user = user.is_authenticated
        session_key = request.session.session_key
        ip = get_ip(request)
        user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
        hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)
        exclude_user_group = getattr(settings, 'HITCOUNT_EXCLUDE_USER_GROUP', None)

        # first, check our request against the IP blacklist
        if BlacklistIP.objects.filter(ip__exact=ip):
            return UpdateHitCountResponse(
                False, 'Not counted: user IP has been blacklisted')

        # second, check our request against the user agent blacklist
        if BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
            return UpdateHitCountResponse(
                False, 'Not counted: user agent has been blacklisted')

        # third, see if we are excluding a specific user group or not
        if exclude_user_group and is_authenticated_user:
            if user.groups.filter(name__in=exclude_user_group):
                return UpdateHitCountResponse(
                    False, 'Not counted: user excluded by group')

        # eliminated first three possible exclusions, now on to checking our database of
        # active hits to see if we should count another one

        # start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE)
        qs = Hit.objects.filter_active()

        # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
        if hits_per_ip_limit:
            if qs.filter(ip__exact=ip).count() >= hits_per_ip_limit:
                return UpdateHitCountResponse(
                    False, 'Not counted: hits per IP address limit reached')

        # create a generic Hit object with request data
        hit = Hit(session=session_key, hitcount=hitcount, ip=get_ip(request),
                  user_agent=request.META.get('HTTP_USER_AGENT', '')[:255],)

        # first, use a user's authentication to see if they made an earlier hit
        if is_authenticated_user:
            if not qs.filter(user=user, hitcount=hitcount):
                hit.user = user  # associate this hit with a user
                hit.save()

                response = UpdateHitCountResponse(
                    True, 'Hit counted: user authentication')
            else:
                response = UpdateHitCountResponse(
                    False, 'Not counted: authenticated user has active hit')

        # if not authenticated, see if we have a repeat session
        else:
            if not qs.filter(session=session_key, hitcount=hitcount):
                hit.save()
                response = UpdateHitCountResponse(
                    True, 'Hit counted: session key')
            else:
                response = UpdateHitCountResponse(
                    False, 'Not counted: session key has active hit')

        return response
Esempio n. 10
0
def _update_hit_count(request, hitcount):
    '''
    Evaluates a request's Hit and corresponding HitCount object and,
    after a bit of clever logic, either ignores the request or registers
    a new Hit.

    This is NOT a view!  But should be used within a view ...

    Returns True if the request was considered a Hit; returns False if not.
    '''

    UpdateHitCountResponse = namedtuple('UpdateHitCountResponse',
                                        'hit_counted hit_message')

    user = request.user
    session_key = request.session.session_key
    ip = get_ip(request)
    user_agent = request.META.get('HTTP_USER_AGENT', '')[:255]
    hits_per_ip_limit = getattr(settings, 'HITCOUNT_HITS_PER_IP_LIMIT', 0)
    exclude_user_group = getattr(settings, 'HITCOUNT_EXCLUDE_USER_GROUP', None)

    # first, check our request against the IP blacklist
    if BlacklistIP.objects.filter(ip__exact=ip):
        response = UpdateHitCountResponse(
            False, 'Not counted: user IP has been blacklisted')
        return response

    # second, check our request against the user agent blacklist
    if BlacklistUserAgent.objects.filter(user_agent__exact=user_agent):
        response = UpdateHitCountResponse(
            False, 'Not counted: user agent has been blacklisted')
        return response

    # third, see if we are excluding a specific user group or not
    if exclude_user_group and user.is_authenticated():
        if user.groups.filter(name__in=exclude_user_group):
            response = UpdateHitCountResponse(
                False, 'Not counted: user excluded by group')
            return response

    # eliminated first three possible exclusions, now on to checking our database of
    # active hits to see if we should count another one

    #start with a fresh active query set (HITCOUNT_KEEP_HIT_ACTIVE)
    qs = Hit.objects.filter_active()

    # check limit on hits from a unique ip address (HITCOUNT_HITS_PER_IP_LIMIT)
    if hits_per_ip_limit:
        if qs.filter(ip__exact=ip).count() > hits_per_ip_limit:
            response = UpdateHitCountResponse(
                False, 'Not counted: hits per IP address limit reached')
            return response

    # create a generic Hit object with request data
    hit = Hit(
        session=session_key,
        hitcount=hitcount,
        ip=get_ip(request),
        user_agent=request.META.get('HTTP_USER_AGENT', '')[:255],
    )

    # first, use a user's authentication to see if they made an earlier hit
    if user.is_authenticated():
        if not qs.filter(user=user, hitcount=hitcount):
            hit.user = user  #associate this hit with a user
            hit.save()

            response = UpdateHitCountResponse(
                True, 'Hit counted: user authentication')
        else:
            response = UpdateHitCountResponse(
                False, 'Not counted: authenticated user has active hit')

    # if not authenticated, see if we have a repeat session
    else:
        if not qs.filter(session=session_key, hitcount=hitcount):
            hit.save()
            response = UpdateHitCountResponse(True, 'Hit counted: session key')
        else:
            response = UpdateHitCountResponse(
                False, 'Not counted: session key has active hit')

    return response