<commit_before>import contextlib
import re
import urllib

from django.conf import settings
from django.contrib.auth import logout
from django.contrib import messages
from django.core.exceptions import MiddlewareNotUsed
from django.core.urlresolvers import is_valid_path
from django.core.validators import validate_ipv4_address, ValidationError
from django.db.utils import DatabaseError
from django.http import (HttpResponse, HttpResponseRedirect,
                         HttpResponsePermanentRedirect, HttpResponseForbidden)
from django.http.request import split_domain_port
from django.shortcuts import render
from django.utils import translation
from django.utils.cache import add_never_cache_headers, patch_response_headers, patch_vary_headers
from django.utils.encoding import iri_to_uri, smart_str, smart_unicode

import mobility
from mozilla_django_oidc.middleware import SessionRefresh
from enforce_host import EnforceHostMiddleware

from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.urlresolvers import Prefixer, set_url_prefixer, split_path
from kitsune.sumo.views import handle403


try:
    from django.utils.deprecation import MiddlewareMixin
except ImportError:
    MiddlewareMixin = object


class EnforceHostIPMiddleware(EnforceHostMiddleware):
    """Modify the `EnforceHostMiddleware` to allow IP addresses"""
    def process_request(self, request):
        host = request.get_host()
        domain, port = split_domain_port(host)
        try:
            validate_ipv4_address(domain)
        except ValidationError:
            # not an IP address. Call the superclass
            return super(EnforceHostIPMiddleware, self).process_request(request)

        # it is an IP address
        return


class HttpResponseRateLimited(HttpResponse):
    status_code = 429


class SUMORefreshIDTokenAdminMiddleware(SessionRefresh):
    def __init__(self, *args, **kwargs):
        if not settings.OIDC_ENABLE or settings.DEV:
            raise MiddlewareNotUsed

    def process_request(self, request):
        """Only allow refresh and enforce OIDC auth on admin URLs"""
        if request.path.startswith('/admin/') and request.path != '/admin/login/':
            if 'oidc_id_token_expiration' not in request.session:
                logout(request)
                messages.error(request, 'OIDC login required for admin access')
                return HttpResponseRedirect('/admin/login/')

            return super(SUMORefreshIDTokenAdminMiddleware, self).process_request(request)


class LocaleURLMiddleware(object):
    """
    Based on zamboni.amo.middleware.<commit_msg>Enforce the SumoOIDC backend for staff members.<commit_after>import contextlib
import re
import urllib

from django.conf import settings
from django.contrib import messages
from django.contrib.auth import BACKEND_SESSION_KEY, logout
from django.core.exceptions import MiddlewareNotUsed
from django.core.urlresolvers import is_valid_path
from django.core.validators import validate_ipv4_address, ValidationError
from django.db.utils import DatabaseError
from django.http import (HttpResponse, HttpResponseRedirect,
                         HttpResponsePermanentRedirect, HttpResponseForbidden)
from django.http.request import split_domain_port
from django.shortcuts import render
from django.utils import translation
from django.utils.cache import add_never_cache_headers, patch_response_headers, patch_vary_headers
from django.utils.encoding import iri_to_uri, smart_str, smart_unicode

import mobility
from mozilla_django_oidc.middleware import SessionRefresh
from enforce_host import EnforceHostMiddleware

from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.urlresolvers import Prefixer, set_url_prefixer, split_path
from kitsune.sumo.views import handle403


try:
    from django.utils.deprecation import MiddlewareMixin
except ImportError:
    MiddlewareMixin = object


class EnforceHostIPMiddleware(EnforceHostMiddleware):
    """Modify the `EnforceHostMiddleware` to allow IP addresses"""
    def process_request(self, request):
        host = request.get_host()
        domain, port = split_domain_port(host)
        try:
            validate_ipv4_address(domain)
        except ValidationError:
            # not an IP address. Call the superclass
            return super(EnforceHostIPMiddleware, self).process_request(request)

        # it is an IP address
        return


class HttpResponseRateLimited(HttpResponse):
    status_code = 429


class SUMORefreshIDTokenAdminMiddleware(SessionRefresh):
    def __init__(self, *args, **kwargs):
        if not settings.OIDC_ENABLE or settings.DEV:
            raise MiddlewareNotUsed

    def process_request(self, request):
        """Only allow refresh and enforce OIDC auth on admin URLs"""
        # If the admin is targeted let's check the backend used, if any
        if request.path.startswith('/admin/') and request.path != '/admin/login/':
            backend = request.session.get(BACKEND_SESSION_KEY)
            if backend and backend.split('.')[-1] != 'SumoOIDCAuthBackend':
                logout(request)
                messages.error(request, 'OIDC login required for admin access')
                return HttpResponseRedirect('/admin/login/')

            return super(SUMORefreshIDTokenAdminMiddleware, self).process_request(request)


class LocaleURLMiddleware(object):
    """
    Based on zamboni.amo.middleware.
{'fraction_non_alphanumeric': 0.0639470782800441, 'fraction_numerical': 0.0031238515251745683, 'mean_word_length': 3.966240875912409, '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': '1330061', 'n_tokens_mistral': 1487, 'n_tokens_neox': 1442, 'n_words': 408}