Ejemplo n.º 1
0
    def __init__(self):
        """Disable the middleware if the feature is not enabled. """
        if not settings.FEATURES.get('ENABLE_CROSS_DOMAIN_CSRF_COOKIE'):
            raise MiddlewareNotUsed()

        if not getattr(settings, 'CROSS_DOMAIN_CSRF_COOKIE_NAME', ''):
            raise ImproperlyConfigured(
                "You must set `CROSS_DOMAIN_CSRF_COOKIE_NAME` when "
                "`FEATURES['ENABLE_CROSS_DOMAIN_CSRF_COOKIE']` is True.")

        if not getattr(settings, 'CROSS_DOMAIN_CSRF_COOKIE_DOMAIN', ''):
            raise ImproperlyConfigured(
                "You must set `CROSS_DOMAIN_CSRF_COOKIE_DOMAIN` when "
                "`FEATURES['ENABLE_CROSS_DOMAIN_CSRF_COOKIE']` is True.")
Ejemplo n.º 2
0
 def __init__(self, get_response=None):
     if not settings.YADP_ENABLED:
         # Disable the middleware completely when YADP_ENABLED = False
         raise MiddlewareNotUsed()
     self.get_response = get_response
     self.error = None
     self.profiler = None
     self.get_parameters = None
     self.post_parameters = None
     self.clock_parameter = None
     self.fraction_parameter = None
     self.max_calls_parameter = None
     self.pattern_parameter = None
     self.profile_parameter = None
Ejemplo n.º 3
0
    def __init__(self):
        """
        Middleware init is called once per server on startup - do the heavy
        lifting here.
        """
        # If disabled or not enabled raise MiddleWareNotUsed so django
        # processes next middleware.
        self.ENABLED = getattr(settings, 'BANISH_ENABLED', False)
        self.DEBUG = getattr(settings, 'BANISH_DEBUG', False)
        self.ABUSE_THRESHOLD = getattr(settings, 'BANISH_ABUSE_THRESHOLD', 75)
        self.USE_HTTP_X_FORWARDED_FOR = getattr(
            settings, 'BANISH_USE_HTTP_X_FORWARDED_FOR', False)
        self.BANISH_EMPTY_UA = getattr(settings, 'BANISH_EMPTY_UA', True)
        self.BANISH_MESSAGE = getattr(settings, 'BANISH_MESSAGE',
                                      'You are banned.')

        if not self.ENABLED:
            raise MiddlewareNotUsed(
                "django-banish is not enabled via settings.py")

        if self.DEBUG:
            print >> sys.stderr, "[django-banish] status = enabled"

        # Prefix All keys in cache to avoid key collisions
        self.BANISH_PREFIX = 'DJANGO_BANISH:'
        self.ABUSE_PREFIX = 'DJANGO_BANISH_ABUSE:'
        self.WHITELIST_PREFIX = 'DJANGO_BANISH_WHITELIST:'

        self.BANNED_AGENTS = []

        if self.BANISH_EMPTY_UA:
            self.BANNED_AGENTS.append(None)

        # Populate various 'banish' buckets
        for ban in Banishment.objects.all():
            if self.DEBUG:
                print >> sys.stderr, "IP BANISHMENT: ", ban.type

            if ban.type == 'ip-address':
                cache_key = self.BANISH_PREFIX + ban.condition
                cache.set(cache_key, "1")

            if ban.type == 'user-agent':
                self.BANNED_AGENTS.append(ban.condition)

        for whitelist in Whitelist.objects.all():
            if whitelist.type == 'ip-address-whitelist':
                cache_key = self.WHITELIST_PREFIX + whitelist.condition
                cache.set(cache_key, "1")
Ejemplo n.º 4
0
    def __init__(self, get_response):
        if getattr(settings, 'ALLOWED_IP_BLOCKS', False):
            self.ip_blocks = [
                item.strip() for item in settings.ALLOWED_IP_BLOCKS.split(',')
            ]  # type: ignore
        else:
            # this will make Django skip this middleware for all future requests
            raise MiddlewareNotUsed()

        if getattr(settings, 'TRUSTED_PROXIES', False):
            self.trusted_proxies = [
                item.strip()
                for item in getattr(settings, 'TRUSTED_PROXIES').split(',')
            ]
        self.get_response = get_response
Ejemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        redis_handler = RedisHandler()
        RedisHandler.instance = redis_handler
        redis_handler.register("UserJoinedMeetingEvtMsg", on_join)
        redis_handler.register("UserLeftMeetingEvtMsg", on_leave)
        redis_handler.register("GroupChatMessageBroadcastEvtMsg", on_chat_msg)
        redis_handler.register("ClearPublicChatHistoryPubMsg", on_chat_clear)
        redis_handler.start()

        threads = [RequestThread() for i in range(1)]
        for thread in threads:
            thread.start()

        StateLoader().start()
        raise MiddlewareNotUsed("Good.Design")
Ejemplo n.º 6
0
    def __init__(self, *args, **kwargs):
        """Disable the middleware if the feature is not enabled. """
        if not settings.FEATURES.get('ENABLE_CROSS_DOMAIN_CSRF_COOKIE'):
            raise MiddlewareNotUsed()

        if not getattr(settings, 'CROSS_DOMAIN_CSRF_COOKIE_NAME', ''):
            raise ImproperlyConfigured(
                "You must set `CROSS_DOMAIN_CSRF_COOKIE_NAME` when "
                "`FEATURES['ENABLE_CROSS_DOMAIN_CSRF_COOKIE']` is True.")

        if not getattr(settings, 'CROSS_DOMAIN_CSRF_COOKIE_DOMAIN', ''):
            raise ImproperlyConfigured(
                "You must set `CROSS_DOMAIN_CSRF_COOKIE_DOMAIN` when "
                "`FEATURES['ENABLE_CROSS_DOMAIN_CSRF_COOKIE']` is True.")
        super(CsrfCrossDomainCookieMiddleware, self).__init__(*args, **kwargs)  # lint-amnesty, pylint: disable=super-with-arguments
Ejemplo n.º 7
0
 def __init__(self, get_response):
     if not settings.SECURE_PROXY_SSL_HEADER:
         # For Django to be able to detect if a request is secure
         # some configuration is required, e.g..
         #
         # The nginx proxy should set:
         #
         #   proxy_set_header X-Forwarded-Proto $scheme;
         #
         # The Django project should set:
         #
         #   SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
         raise MiddlewareNotUsed(
             "SECURE_PROXY_SSL_HEADER is not configured")
     self.get_response = get_response
Ejemplo n.º 8
0
    def __init__(self,
                 logger=None,
                 format=None,
                 logging_level=logging.INFO,
                 logger_name='wsgi',
                 setup_console_handler=True,
                 set_logger_level=logging.DEBUG,
                 disable_on_devel=True):

        # Because __init__ is called manually by __new__, it is invoked twice:
        # bail out early the second time as we are already configured.
        if self.__dict__:
            return

        if format is not None:
            self.format = format
        self.logging_level = logging_level
        self.logger_name = logger_name
        if logger is None:
            self.logger = logging.getLogger(self.logger_name)
            if setup_console_handler:
                console = logging.StreamHandler()
                console.setLevel(logging.DEBUG)
                # We need to control the exact format:
                console.setFormatter(logging.Formatter('%(message)s'))
                self.logger.addHandler(console)
                self.logger.propagate = False
            if set_logger_level is not None:
                self.logger.setLevel(set_logger_level)
        else:
            self.logger = logger

        # If running under the development server, it will try to log as well
        if 'django.core.management.commands.runserver' in sys.modules:
            if disable_on_devel:
                from django.core.exceptions import MiddlewareNotUsed
                raise MiddlewareNotUsed("development server detected")

            else:
                self.logger.info(
                    "development server detected: disabling its logs")
                try:
                    from django.core.servers.basehttp import WSGIRequestHandler
                    WSGIRequestHandler.log_message = (
                        lambda self, format, *args: None)
                except Exception as e:
                    self.logger.warn("disbling logs failed: %s - %s",
                                     e.__class__.__name__, e)
Ejemplo n.º 9
0
    def __init__(self):
        if system_layout.current_value is not None:
            raise MiddlewareNotUsed()

        class FarmNotConfiguredView(APIView):
            permission_classes = (AllowAny, )

            def get(self, request):
                raise FarmNotConfiguredError()

            post = get
            put = get
            patch = get
            delete = get

        self.view = FarmNotConfiguredView.as_view()
Ejemplo n.º 10
0
 def __init__(self, get_response=None):
     for error in cache.get('configuration-errors', []):
         ConfigurationError.objects.add(
             error['name'],
             error['message'],
             error['timestamp'] if 'timestamp' in error else now(),
         )
     if self.does_fire(run_index_queue):
         ConfigurationError.objects.add(
             'Offloaded index', 'The processing seems to be slow, '
             'there are more than 20000 entries to process.')
     if self.does_fire(run_cache):
         ConfigurationError.objects.add(
             'Cache', 'The configured cache backend will lead to serious '
             'performance or consistency issues.')
     raise MiddlewareNotUsed()
Ejemplo n.º 11
0
 def __init__(self):
     """Creates the IrcBot and reports that the bot is not used.
     """
     try:
         self.bots
     except AttributeError:
         self.bots = [
             SpoilerBot(host='vilma.hsin.hr',
                        port=6667,
                        channels=['#zadaci'],
                        nick='SpoilerBot',
                        identity='SpoilerBot',
                        real_name='I like to spoil things!',
                        owner='brahle'),
         ]
     raise MiddlewareNotUsed()
Ejemplo n.º 12
0
    def __init__(self):
        # we'll never get into process request in case HTTP_AUTH is disabled
        if not local_settings.HTTP_AUTH_ENABLED:
            msg = "Basic authentication is not used, this removes it from middleware"
            raise MiddlewareNotUsed(msg)
            # if looking only for blocking access for bad-behaved crawlers SSL is not required
            # BEWARE: without encryption the basic auth credentials are sent in plain text
            # self.basic_auth_requires_ssl = getattr(settings, 'BASIC_HTTP_AUTH_USE_SSL', '')

        self.exception_patterns = [
            re.compile(exception_pattern) for exception_pattern
            in local_settings.HTTP_AUTH_URL_EXCEPTIONS
        ]
        logger.debug("Using %s URLs for basic auth exceptions",
                     local_settings.HTTP_AUTH_URL_EXCEPTIONS)
        self.site_checker = get_custom_site_checker()
Ejemplo n.º 13
0
def InstallJavascriptCatalog(get_response=None):
    """
    Middleware ensuring that 'django.views.i18n.javascript_catalog' is wired.
    This middleware can be configured using settings :
        * JSI18N_PACKAGES : default is ()
        * JSI18N_VIEWNAME : default is 'jsi18n'
        * JSI18N_USE_I18NPATTERN : default is True
    """

    import django.core.urlresolvers as URL
    jsi18nView = "django.views.i18n.javascript_catalog"

    try:

        # check if javascript_catalog exists in settings.ROOT_URLCONF
        URL.reverse(jsi18nView)

    except URL.NoReverseMatch :

        # we fix ROOT_URLCONF urlpatterns...

        if getattr(settings,'JSI18N_USE_I18NPATTERN',True):

            from django.conf.urls.i18n import i18n_patterns as patterns
        else:

            from django.conf.urls import patterns

        resolver = URL.get_resolver(None)

        # define missing jsi18npatterns ...
        jsi18nParams = dict(packages=getattr(settings,'JSI18N_PACKAGES',()))
        jsi18nViewName = getattr(settings,'JSI18N_VIEWNAME',"jsi18n")
        jsi18npatterns = patterns('',
                (r"^jsi18n$",jsi18nView,jsi18nParams,jsi18nViewName),
                )

        # correct default urlpatterns
        urlpatterns = resolver.urlconf_module.urlpatterns
        urlpatterns += jsi18npatterns
        resolver.urlconf_module.urlpatterns = urlpatterns

        # reset resolver
        for cachename in ['_reverse_dict','_namespace_dict','_app_dict']:
            setattr(resolver,cachename,{})

    raise MiddlewareNotUsed()
Ejemplo n.º 14
0
    def process_view(self, request, callback, callback_args, callback_kwargs):
        """
        Enable the profiler and begin collecting data about the view
        Note that this misses the rest of Django's request processing (other middleware, etc.)
        """
        # Ensure the profiler being requested is actually installed/available
        if THREAD_LOCAL.profiler_type is None:
            THREAD_LOCAL.profiler_type = request.GET.get(
                'profiler_type', 'hotshot')
        if self.profiler_type() == THREAD_LOCAL.profiler_type:
            if not self.profiler_installed():
                return MiddlewareNotUsed()

            THREAD_LOCAL.profiler = self.profiler_start()
            return THREAD_LOCAL.profiler.runcall(callback, request,
                                                 *callback_args,
                                                 **callback_kwargs)
Ejemplo n.º 15
0
    def __init__(
        self,
        get_response: Callable,
        *,
        enabled: Optional[bool] = None,
        trusted_proxy_set: Optional[Iterable[str]] = None,
    ):
        """

        Keyword arguments:
            enabled: Whether this middleware should be enabled.
                If None, respects the ``USE_HTTP_FORWARDED`` Django setting.

            trusted_proxy_set: Base set of trusted proxies.
                If None, the value is taken
                from the ``HTTP_FORWARDED_TRUSTED_PROXY_SET`` Django setting.
        """

        log = logging.LoggerAdapter(_log, {"forwarded": None})

        if enabled is None:
            enabled = getattr(settings, "USE_HTTP_FORWARDED", False)
        if trusted_proxy_set is None:
            trusted_proxy_set = getattr(settings,
                                        "HTTP_FORWARDED_TRUSTED_PROXY_SET",
                                        frozenset())

        if not enabled:
            raise MiddlewareNotUsed()

        # Split trusted proxies on IP adddresses and host names
        trusted_addr = set()
        trusted_fqdn = set()

        for host in trusted_proxy_set:
            try:
                trusted_addr.add(ip_address(host))
            except ValueError:
                trusted_fqdn.add(getfqdn(host))

        self._get_response = get_response
        log.debug("Trusting by address: %s", trusted_addr)
        self._trusted_addr_set = frozenset(trusted_addr)
        log.debug("Trusting by name: %s", trusted_fqdn)
        self._trusted_fqdn_set = frozenset(trusted_fqdn)
Ejemplo n.º 16
0
 def __init__(self):
     if getattr(settings, 'IS_DEV_SERVER', False
                ) or 'django.contrib.sites' not in settings.INSTALLED_APPS:
         raise MiddlewareNotUsed()
     try:
         from django.contrib.gis.utils import GeoIP, GeoIPException
         self.g = GeoIP()
         self.redirect_sites = dict(settings.SITE_GEOIP_REDIRECT)
     except (ImportError, GeoIPException, ValueError, TypeError,
             AttributeError):
         raise ImproperlyConfigured(
             "The GeoIPRedirectMiddleware requires the"
             " setting SITE_GEOIP_REDIRECT and GEOIP_PATH to be defined"
             " along with a working GeoIP installation."
             " Please see 'django.contrib.gis.utils.geoip.py'.")
     self.srs_url_re = re.compile("^/siteinfo/srs/?$")
     self.srs_getvarname = getattr(settings,
                                   'SITE_GEOIP_REDIRECT_GETVARNAME', 'srs')
Ejemplo n.º 17
0
def admin_requires_2fa_middleware(get_response):
    try:
        admin_prefix = reverse("admin:index")
    except NoReverseMatch:
        # The admin site isn't installed, likely because
        # we are running tests with a custom urlconf that
        # doesn't register the admin site.
        raise MiddlewareNotUsed()

    ignored_paths = {reverse("admin:login"), reverse("admin:logout")}

    def middleware(request):
        path = request.path
        if (path.startswith(admin_prefix) and path not in ignored_paths
                and request.user.is_authenticated
                and not is_request_user_verified(request)):
            return redirect_request_to_verify(request)
        return get_response(request)

    return middleware
Ejemplo n.º 18
0
def google_analytics(get_response):
    """Report a page view to Google Analytics."""

    if not settings.GOOGLE_ANALYTICS_TRACKING_ID:
        raise MiddlewareNotUsed()

    def middleware(request):
        client_id = analytics.get_client_id(request)
        path = request.path
        language = get_language()
        headers = request.META
        try:
            analytics.report_view(
                client_id, path=path, language=language, headers=headers
            )
        except Exception:
            logger.exception("Unable to update analytics")
        return get_response(request)

    return middleware
Ejemplo n.º 19
0
    def __init__(self):
        """Initialise the logging setup from settings.

        Logging setup is initialized only in the first request.
        """
        logging_setting = getattr(settings, 'LOGGING_SETUP', None)
        if logging_setting:
            # Disable handlers that are not used by any logger.
            active_handlers = set()
            loggers = logging_setting.get('loggers', {})
            for logger in loggers.values():
                active_handlers.update(logger.get('handlers', []))
            handlers = logging_setting.get('handlers', {})
            for handler in handlers:
                if handler not in active_handlers:
                    handlers[handler] = {'class': 'logging.NullHandler'}

            logging.NullHandler = NullHandler
            dictConfig(logging_setting)
        raise MiddlewareNotUsed('Logging setup only.')
Ejemplo n.º 20
0
    def __init__(self, *args, **kwargs):
        global PATCHES_APPLIED
        if not PATCHES_APPLIED:
            # json module does not escape HTML metacharacters by default.
            replace_default_argument(json.dump, 'cls', _JsonEncoderForHtml)
            replace_default_argument(json.dumps, 'cls', _JsonEncoderForHtml)

            # YAML.  The Python tag scheme allows arbitrary code execution:
            # yaml.load('!!python/object/apply:os.system ["ls"]')
            replace_default_argument(yaml.compose, 'Loader',
                                     yaml.loader.SafeLoader)
            replace_default_argument(yaml.compose_all, 'Loader',
                                     yaml.loader.SafeLoader)
            replace_default_argument(yaml.load, 'Loader',
                                     yaml.loader.SafeLoader)
            replace_default_argument(yaml.load_all, 'Loader',
                                     yaml.loader.SafeLoader)
            replace_default_argument(yaml.parse, 'Loader',
                                     yaml.loader.SafeLoader)
            replace_default_argument(yaml.scan, 'Loader',
                                     yaml.loader.SafeLoader)

            # AppEngine urlfetch.
            # Does not validate certificates by default.
            replace_default_argument(urlfetch.fetch, 'validate_certificate',
                                     True)
            replace_default_argument(urlfetch.make_fetch_call,
                                     'validate_certificate', True)
            urlfetch.fetch = _HttpUrlLoggingWrapper(urlfetch.fetch)
            urlfetch.make_fetch_call = _HttpUrlLoggingWrapper(
                urlfetch.make_fetch_call)

            for setting in ("CSRF_COOKIE_SECURE", "SESSION_COOKIE_HTTPONLY",
                            "SESSION_COOKIE_SECURE"):
                if not getattr(settings, setting, False):
                    logging.warning(
                        "settings.%s is not set to True, this is insecure",
                        setting)

            PATCHES_APPLIED = True
        raise MiddlewareNotUsed()
Ejemplo n.º 21
0
    def __init__(self):
        from tardis.tardis_portal.models import Dataset_File
        for f in settings.POST_SAVE_FILTERS:
            cls = f[0]
            args = []
            kw = {}

            if len(f) == 2:
                args = f[1]

            if len(f) == 3:
                kw = f[2]

            hook = self._safe_import(cls, args, kw)
            # XXX seems to requre a strong ref else it won't fire,
            # could be because some hooks are classes not functions.
            post_save.connect(hook, sender=Dataset_File, weak=False)
            logger.debug('Initialised postsave hook %s' % post_save.receivers)

        # disable middleware
        raise MiddlewareNotUsed()
Ejemplo n.º 22
0
    def __init__(self):

        print 'Executing CoG initialization tasks'

        # update name, domain of current site into database
        current_site = Site.objects.get_current()
        current_site.name = settings.SITE_NAME
        current_site.domain = settings.SITE_DOMAIN
        current_site.save()
        print 'Updated current site: name=%s domain=%s' % (current_site.name,
                                                           current_site.domain)

        # update list of ESGF peers into database
        filepath = siteManager.get('PEER_NODES')
        pnl = PeerNodesList(filepath)
        pnl.reload()  # delete=False

        # read IdP whitelist

        # remove this class from the middleware that is invoked for every request
        raise MiddlewareNotUsed('Do not invoke ever again')
Ejemplo n.º 23
0
    def __init__(self):
        """
        Middleware init is called once per server on startup - do the heavy
        lifting here.
        """
        # If disabled or not enabled raise MiddleWareNotUsed so django
        # processes next middleware.
        self.ENABLED = getattr(settings, 'BANS_ENABLED', False)
        self.DEBUG = getattr(settings, 'BANS_DEBUG', False)

        if not self.ENABLED:
            raise MiddlewareNotUsed("bans are not enabled via settings.py")

        if self.DEBUG:
            print "Bans status = enabled"

        # Populate various 'banish' buckets
        for ban in Ban.objects.all():
            if self.DEBUG:
                print ban
            cache.add('BAN:'+ban.address, '1', None)
    def __init__(self, param):
        self.logger.info('Startup: Setup started')
        call_command('makemigrations', 'management_app')
        call_command('migrate', 'management_app')
        call_command('migrate')
        # load data
        call_command('loaddata', 'tournament.json')

        # create users and groups
        try:
            self.create_user_groups()
            self.create_users()
            self.logger.info('Startup: Created users and groups')
        except IntegrityError:
            self.logger.info('Startup: Users already exist')

        self.logger.info('Startup: Loaded data')
        set_team_average()
        set_player_average_score()
        set_won_by()
        print('Startup: Setup complete')
        raise MiddlewareNotUsed('Setup complete')
Ejemplo n.º 25
0
    def __init__(self):
        """
        Middleware init is called once per server on startup - do the heavy
        lifting here.
        """
        # If disabled or not enabled raise MiddleWareNotUsed so django
        # processes next middleware.
        self.ENABLED = getattr(settings, 'ADMIN_ACCESS_WHITELIST_ENABLED', False)
        self.USE_HTTP_X_FORWARDED_FOR = getattr(settings, 'ADMIN_ACCESS_WHITELIST_USE_HTTP_X_FORWARDED_FOR', False)
        self.ADMIN_ACCESS_WHITELIST_MESSAGE = getattr(settings, 'ADMIN_ACCESS_WHITELIST_MESSAGE', 'You are banned.')

        if not self.ENABLED:
            raise MiddlewareNotUsed("django-admin-ip-whitelist is not enabled via settings.py")

        log.debug("[django-admin-ip-whitelist] status = enabled")

        # Prefix All keys in cache to avoid key collisions
        self.ABUSE_PREFIX = 'DJANGO_ADMIN_ACCESS_WHITELIST_ABUSE:'
        self.WHITELIST_PREFIX = ADMIN_ACCESS_WHITELIST_PREFIX

        for whitelist in DjangoAdminAccessIPWhitelist.objects.all():
            cache_key = self.WHITELIST_PREFIX + whitelist.ip
            cache.set(cache_key, "1")
Ejemplo n.º 26
0
 def __init__(self):
     current_pid = os.getpid()
     print "Checking for an already running supervisor"
     if os.path.exists('columbus-supervisor.pid'):
         with open('columbus-supervisor.pid', 'rb') as handle:
             existing_pid = int(handle.read())
         if existing_pid != current_pid:
             try:
                 os.kill(existing_pid, 0)
                 print "found a supervisor running in a different process with id " + str(
                     existing_pid)
                 print "killing the existing supervisor"
                 os.kill(existing_pid, signal.SIGTERM)
                 print "killed the existing supervisor successfully"
             except OSError:
                 pass
         else:
             return
     with open('columbus-supervisor.pid', 'wb') as handle:
         handle.write(str(current_pid))
     from pyedf.coreengine import Supervisor
     supervisor = Supervisor()
     supervisor.start()
     raise MiddlewareNotUsed("Supervisor is up and running")
Ejemplo n.º 27
0
 def __init__(self, get_response: typing.Callable) -> None:
     if RECORDING_DISABLED:
         raise MiddlewareNotUsed("UserVisit recording has been disabled")
     self.get_response = get_response
Ejemplo n.º 28
0
 def __init__(self, get_response):
     if settings.DEBUG is True:
         raise MiddlewareNotUsed()
     self.get_response = get_response
Ejemplo n.º 29
0
 def __init__(self):
     # If embargoing is turned off, make this middleware do nothing
     if not settings.FEATURES.get('EMBARGO'):
         raise MiddlewareNotUsed()
Ejemplo n.º 30
0
 def __init__(self):
     if not settings.DEBUG:
         raise MiddlewareNotUsed()