<commit_before>
from django.contrib.auth import logout
from django.core.urlresolvers import reverse
from django.http import (HttpResponse, HttpResponseRedirect,
                         HttpResponsePermanentRedirect)
from django.utils.cache import get_max_age
from django.template import Template, RequestContext

# try to import PermissionDenied, since it is new in 1.4 fall back to 404
try:
    from django.core.exceptions import PermissionDenied
except:
    from django.http import Http404 as PermissionDenied

from mezzanine.conf import settings
from mezzanine.utils.cache import (cache_key_prefix, nevercache_token,
                                   cache_get, cache_set, cache_installed)
from mezzanine.utils.device import templates_for_device
from mezzanine.utils.sites import can_access_admin_site, templates_for_host

_deprecated = {
    "AdminLoginInterfaceSelector": "AdminLoginInterfaceSelectorMiddleware",
    "DeviceAwareUpdateCacheMiddleware": "UpdateCacheMiddleware",
    "DeviceAwareFetchFromCacheMiddleware": "FetchFromCacheMiddleware",
}


class _Deprecated(object):
    def __init__(self, *args, **kwargs):
        from warnings import warn
        msg = "mezzanine.core.middleware.%s is deprecated." % self.old
        if self.new:
            msg += (" Please change the MIDDLEWARE_CLASSES setting to use "
                    "mezzanine.core.middleware.%s" % self.new)
        warn(msg)

for old, new in _deprecated.items():
    globals()[old] = type(old, (_Deprecated,), {"old": old, "new": new})


class AdminLoginInterfaceSelectorMiddleware(object):
    """
    Checks for a POST from the admin login view and if authentication is
    successful and the "site" interface is selected, redirect to the site.

    TODO: Just make this a view and post to it.
    """
    def process_view(self, request, view_func, view_args, view_kwargs):
        login_type = request.POST.get("mezzanine_login_interface")
        if login_type and not request.user.is_authenticated():
            response = view_func(request, *view_args, **view_kwargs)
            if request.user.is_authenticated():
                if login_type == "admin":
                    next = request.get_full_path()
                else:
                    next = request.GET.get("next", "/")
                return HttpResponseRedirect(next)
            else:
                return response
        return None

class AdminSiteMiddleware(object):
    """
    Checks if an admin user has access to the current site.  If not returns a forbidden.
    """
    def process_view(self, request, view_func, view_args, view_kwargs):
        if request.path.startswith(reverse('admin:index')):
            if request.user.is_staff and request.user.is_active:
                if not can_access_admin_site(request.user):
                    logout(request)
                    raise PermissionDenied

class TemplateForDeviceMiddleware(object):
    """
    Inserts device-specific templates to the template list.
    """
    def process_template_response(self, request, response):
        if hasattr(response, "template_name"):
            templates = templates_for_device(request, response.template_name)
            response.template_name = templates
        return response


class TemplateForHostMiddleware(object):
    """
    Inserts host-specific templates to the template list.
    """<commit_msg>Check if the user is_staff first to avoid unecessarily reversing admin:index on every request.<commit_after>
from django.contrib.auth import logout
from django.core.urlresolvers import reverse
from django.http import (HttpResponse, HttpResponseRedirect,
                         HttpResponsePermanentRedirect)
from django.utils.cache import get_max_age
from django.template import Template, RequestContext

# try to import PermissionDenied, since it is new in 1.4 fall back to 404
try:
    from django.core.exceptions import PermissionDenied
except:
    from django.http import Http404 as PermissionDenied

from mezzanine.conf import settings
from mezzanine.utils.cache import (cache_key_prefix, nevercache_token,
                                   cache_get, cache_set, cache_installed)
from mezzanine.utils.device import templates_for_device
from mezzanine.utils.sites import can_access_admin_site, templates_for_host

_deprecated = {
    "AdminLoginInterfaceSelector": "AdminLoginInterfaceSelectorMiddleware",
    "DeviceAwareUpdateCacheMiddleware": "UpdateCacheMiddleware",
    "DeviceAwareFetchFromCacheMiddleware": "FetchFromCacheMiddleware",
}


class _Deprecated(object):
    def __init__(self, *args, **kwargs):
        from warnings import warn
        msg = "mezzanine.core.middleware.%s is deprecated." % self.old
        if self.new:
            msg += (" Please change the MIDDLEWARE_CLASSES setting to use "
                    "mezzanine.core.middleware.%s" % self.new)
        warn(msg)

for old, new in _deprecated.items():
    globals()[old] = type(old, (_Deprecated,), {"old": old, "new": new})


class AdminLoginInterfaceSelectorMiddleware(object):
    """
    Checks for a POST from the admin login view and if authentication is
    successful and the "site" interface is selected, redirect to the site.

    TODO: Just make this a view and post to it.
    """
    def process_view(self, request, view_func, view_args, view_kwargs):
        login_type = request.POST.get("mezzanine_login_interface")
        if login_type and not request.user.is_authenticated():
            response = view_func(request, *view_args, **view_kwargs)
            if request.user.is_authenticated():
                if login_type == "admin":
                    next = request.get_full_path()
                else:
                    next = request.GET.get("next", "/")
                return HttpResponseRedirect(next)
            else:
                return response
        return None

class AdminSiteMiddleware(object):
    """
    Checks if an admin user has access to the current site.  If not returns a forbidden.
    """
    def process_view(self, request, view_func, view_args, view_kwargs):
        if request.user.is_staff and request.user.is_active and \
            request.path.startswith(reverse('admin:index')):
            if not can_access_admin_site(request.user):
                    logout(request)
                    raise PermissionDenied

class TemplateForDeviceMiddleware(object):
    """
    Inserts device-specific templates to the template list.
    """
    def process_template_response(self, request, response):
        if hasattr(response, "template_name"):
            templates = templates_for_device(request, response.template_name)
            response.template_name = templates
        return response


class TemplateForHostMiddleware(object):
    """
    Inserts host-specific templates to the template list.
    """
{'fraction_non_alphanumeric': 0.08039760268966525, 'fraction_numerical': 0.00233883935097208, 'mean_word_length': 2.9802210587550904, 'pattern_counts': {'":': 12, '<': 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': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '942158', 'n_tokens_mistral': 1852, 'n_tokens_neox': 1783, 'n_words': 525}