<commit_before>import json
import logging
from calendar import timegm

from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.exceptions import ImproperlyConfigured, RequestDataTooBig
from django.urls import reverse
from django.http.request import RawPostDataException
from django.shortcuts import render
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
from lockdown import settings as lockdown_settings
from lockdown.middleware import (LockdownMiddleware as BaseLockdownMiddleware,
                                 compile_url_exceptions, get_lockdown_form)
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings

from bluebottle.clients import properties
from bluebottle.utils.utils import get_client_ip

LAST_SEEN_DELTA = 10  # in minutes


def isAdminRequest(request):
    parts = request.path.split('/')
    base_path = None
    if len(parts) > 2:
        base_path = parts[2]
    return request.path.startswith('/downloads') or base_path in ['jet', 'admin', 'jet-dashboard']


class UserJwtTokenMiddleware(MiddlewareMixin):
    """
    Custom middleware to set the User on the request when using
    Jwt Token authentication.
    """

    def process_request(self, request):
        """ Override only the request to add the user """
        try:
            return request.user
        except AttributeError:
            pass

        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        if user_auth_tuple is not None:
            request.user, _ = user_auth_tuple

            # Set last_seen on the user record if it has been > 10 mins
            # since the record was set.
            if not request.user.last_seen or (request.user.last_seen <
               timezone.now() - timedelta(minutes=LAST_SEEN_DELTA)):
                request.user.last_seen = timezone.now()
                request.user.save()
            return


class SlidingJwtTokenMiddleware(MiddlewareMixin):
    """
    Custom middleware to set a sliding window for the jwt auth token expiration.
    """

    def process_response(self, request, response):
        """ Override only the request to add the new token """
        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        # Check if request includes valid token
        if user_auth_tuple is not None:
            user, _auth = user_auth_tuple

            # Get the payload details
            jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
            payload = jwt_decode_handler(_auth)
            logging.debug('JWT payload found: {0}'.format(payload))

            # Check whether we need to renew the token. This will happen if the token
            # hasn't been renewed in JWT_TOKEN_RENEWAL_DELTA
            exp = payload.get('exp')
            created_timestamp = exp - int(
                properties.JWT_EXPIRATION_DELTA.total_seconds())
            renewal_timestamp = created_timestamp + int(
                settings.JWT_TOKEN_RENEWAL_DELTA.total_seconds())
            now_timestamp = timegm(datetime.utcnow().utctimetuple())

            # If it has been less than JWT_TOKEN_RENEWAL_DELTA time since the
            # token was created then we will pass on created a renewed token
            # and just return the response unchanged.
            if now_timestamp < renewal_timestamp:
                logging.debug(
                    'JWT_TOKEN_RENEWAL_DELTA not exceeded: returning response unchanged.')
                return response

            # Get and check orig_iat
            orig_iat = payload.get('orig_iat')

            if orig_iat:
                # verify expiration
                expiration_timestamp = orig_iat + int(
                    settings.JWT_TOKEN_RENEWAL_LIMIT.total_seconds())
                if now_timestamp > expiration_timestamp:
                    # Token has passed renew time limit - just return existing
                    # response. We need to test this process because it is
                    # probably the case that the response has already been
                    # set to an unauthorized status
                    # now_timestamp > expiration_timestamp.
                    logging.debug(
                        'JWT token has expired: returning response unchanged.')
                    return response

            else:
                # orig_iat field is required - just return existing response
                logging.debug(
                    'JWT token orig_iat field not defined: returning response unchanged.')
                return response

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            new_payload = jwt_payload_handler(user)
            new_payload['orig_iat'] = orig_iat

            # Attach the renewed token to the response
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER<commit_msg>Make it possible to set token renewal in properties<commit_after>import json
import logging
from calendar import timegm

from datetime import datetime, timedelta
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.exceptions import ImproperlyConfigured, RequestDataTooBig
from django.urls import reverse
from django.http.request import RawPostDataException
from django.shortcuts import render
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
from lockdown import settings as lockdown_settings
from lockdown.middleware import (LockdownMiddleware as BaseLockdownMiddleware,
                                 compile_url_exceptions, get_lockdown_form)
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings

from bluebottle.clients import properties
from bluebottle.utils.utils import get_client_ip

LAST_SEEN_DELTA = 10  # in minutes


def isAdminRequest(request):
    parts = request.path.split('/')
    base_path = None
    if len(parts) > 2:
        base_path = parts[2]
    return request.path.startswith('/downloads') or base_path in ['jet', 'admin', 'jet-dashboard']


class UserJwtTokenMiddleware(MiddlewareMixin):
    """
    Custom middleware to set the User on the request when using
    Jwt Token authentication.
    """

    def process_request(self, request):
        """ Override only the request to add the user """
        try:
            return request.user
        except AttributeError:
            pass

        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        if user_auth_tuple is not None:
            request.user, _ = user_auth_tuple

            # Set last_seen on the user record if it has been > 10 mins
            # since the record was set.
            if not request.user.last_seen or (request.user.last_seen <
               timezone.now() - timedelta(minutes=LAST_SEEN_DELTA)):
                request.user.last_seen = timezone.now()
                request.user.save()
            return


class SlidingJwtTokenMiddleware(MiddlewareMixin):
    """
    Custom middleware to set a sliding window for the jwt auth token expiration.
    """

    def process_response(self, request, response):
        """ Override only the request to add the new token """
        obj = JSONWebTokenAuthentication()

        try:
            user_auth_tuple = obj.authenticate(request)
        except exceptions.APIException:
            user_auth_tuple = None

        # Check if request includes valid token
        if user_auth_tuple is not None:
            user, _auth = user_auth_tuple

            # Get the payload details
            jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
            payload = jwt_decode_handler(_auth)
            logging.debug('JWT payload found: {0}'.format(payload))

            # Check whether we need to renew the token. This will happen if the token
            # hasn't been renewed in JWT_TOKEN_RENEWAL_DELTA
            exp = payload.get('exp')
            created_timestamp = exp - int(
                properties.JWT_EXPIRATION_DELTA.total_seconds())
            renewal_timestamp = created_timestamp + int(
                properties.JWT_TOKEN_RENEWAL_DELTA.total_seconds())
            now_timestamp = timegm(datetime.utcnow().utctimetuple())

            # If it has been less than JWT_TOKEN_RENEWAL_DELTA time since the
            # token was created then we will pass on created a renewed token
            # and just return the response unchanged.
            if now_timestamp < renewal_timestamp:
                logging.debug(
                    'JWT_TOKEN_RENEWAL_DELTA not exceeded: returning response unchanged.')
                return response

            # Get and check orig_iat
            orig_iat = payload.get('orig_iat')

            if orig_iat:
                # verify expiration
                expiration_timestamp = orig_iat + int(
                    properties.JWT_TOKEN_RENEWAL_LIMIT.total_seconds())
                if now_timestamp > expiration_timestamp:
                    # Token has passed renew time limit - just return existing
                    # response. We need to test this process because it is
                    # probably the case that the response has already been
                    # set to an unauthorized status
                    # now_timestamp > expiration_timestamp.
                    logging.debug(
                        'JWT token has expired: returning response unchanged.')
                    return response

            else:
                # orig_iat field is required - just return existing response
                logging.debug(
                    'JWT token orig_iat field not defined: returning response unchanged.')
                return response

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            new_payload = jwt_payload_handler(user)
            new_payload['orig_iat'] = orig_iat

            # Attach the renewed token to the response
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
{'fraction_non_alphanumeric': 0.05507408442829186, 'fraction_numerical': 0.001304631441617743, 'mean_word_length': 2.2859767299448865, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5804972', 'n_tokens_mistral': 2755, 'n_tokens_neox': 2635, 'n_words': 835}