def process_request(self, request): # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ("HTTP_X_FORWARDED_HOST" in request.META): host = request.META["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in request.META: host = request.META["HTTP_HOST"] else: # Reconstruct the host using the algorithm from PEP 333. host = request.META["SERVER_NAME"] server_port = str(request.META["SERVER_PORT"]) if server_port != ("443" if request.is_secure() else "80"): host = "%s:%s" % (host, server_port) domain, port = split_domain_port(host) default_domain, default_port = split_domain_port(urlparse(settings.SITE_URL).netloc) if domain: request.host = domain request.port = int(port) if port else None try: kd = KnownDomain.objects.get(domainname=domain) # noqa request.domain = kd except: if settings.DEBUG or domain in LOCAL_HOST_NAMES or domain == default_domain: request.urlconf = "pretix.multidomain.maindomain_urlconf" else: raise DisallowedHost("Unknown host: %r" % host) else: request.organizer = kd.organizer request.urlconf = "pretix.multidomain.subdomain_urlconf" else: raise DisallowedHost("Invalid HTTP_HOST header: %r." % host) # We need to manually set the urlconf for the whole thread. Normally, Django's basic request # would do this for us, but we already need it in place for the other middlewares. set_urlconf(request.urlconf)
def new_get_current(self, request=None): from django.conf import settings if getattr(settings, 'SITE_ID', ''): site_id = settings.SITE_ID if site_id not in THREADED_SITE_CACHE: with lock: site = self.prefetch_related('settings').filter(pk=site_id)[0] THREADED_SITE_CACHE[site_id] = site return THREADED_SITE_CACHE[site_id] elif request: host = request.get_host() try: # First attempt to look up the site by host with or without port. if host not in THREADED_SITE_CACHE: with lock: site = self.prefetch_related('settings').filter( domain__iexact=host)[0] THREADED_SITE_CACHE[host] = site return THREADED_SITE_CACHE[host] except Site.DoesNotExist: # Fallback to looking up site after stripping port from the host. domain, dummy_port = split_domain_port(host) if domain not in THREADED_SITE_CACHE: with lock: site = self.prefetch_related('settings').filter( domain__iexact=domain)[0] THREADED_SITE_CACHE[domain] = site return THREADED_SITE_CACHE[domain] raise ImproperlyConfigured( "You're using the Django sites framework without having" " set the SITE_ID setting. Create a site in your database and" " set the SITE_ID setting or pass a request to" " Site.objects.get_current() to fix this error.")
def validate_redirect_url(self, sub=False): """ Returns the next_url path if next_url matches allowed hosts. """ next_url = self.request.GET.get(REDIRECT_FIELD_NAME, None) if not next_url: return None parts = urlparse.urlparse(next_url) if parts.netloc: domain, _ = split_domain_port(parts.netloc) allowed_hosts = (['*'] if django_settings.DEBUG else django_settings.ALLOWED_HOSTS) if not (domain and validate_host(domain, allowed_hosts)): return None path = parts.path if sub: try: # We replace all ':slug/' by '%(slug)s/' so that we can further # create an instantiated url through Python string expansion. path = re.sub(r':(%s)/' % settings.ACCT_REGEX, r'%(\1)s/', path) % self.kwargs except KeyError: # We don't have all keys necessary. A safe defaults is to remove # them. Most likely a redirect URL is present to pick between # multiple choices. path = re.sub(r'%(\S+)s/', '', path) return urlparse.urlunparse((None, '', path, parts.params, parts.query, parts.fragment))
def _is_host_included(self, host): """ Mirrors the behavior of django.http.request.validate_host(), but does not match '*' (which would exclude all hosts). To exclude all requests from being processed by LocaleMiddleware one should simply remove this class from settings.MIDDLEWARE. """ domain, _ = split_domain_port(host) return not any(is_same_domain(domain, pattern) for pattern in self._excluded_hosts)
def process_request(self, request): # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ('HTTP_X_FORWARDED_HOST' in request.META): host = request.META['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in request.META: host = request.META['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = request.META['SERVER_NAME'] server_port = str(request.META['SERVER_PORT']) if server_port != ('443' if request.is_secure() else '80'): host = '%s:%s' % (host, server_port) domain, port = split_domain_port(host) default_domain, default_port = split_domain_port(urlparse(settings.SITE_URL).netloc) if domain: request.host = domain request.port = int(port) if port else None orga = cache.get('pretix_multidomain_organizer_instance_{}'.format(domain)) if orga is None: try: kd = KnownDomain.objects.select_related('organizer').get(domainname=domain) # noqa orga = kd.organizer except KnownDomain.DoesNotExist: orga = False cache.set('pretix_multidomain_organizer_instance_{}'.format(domain), orga, 3600) if orga: request.organizer_domain = True request.organizer = orga if isinstance(orga, Organizer) else Organizer.objects.get(pk=orga) request.urlconf = "pretix.multidomain.subdomain_urlconf" else: if settings.DEBUG or domain in LOCAL_HOST_NAMES or domain == default_domain: request.urlconf = "pretix.multidomain.maindomain_urlconf" else: raise DisallowedHost("Unknown host: %r" % host) else: raise DisallowedHost("Invalid HTTP_HOST header: %r." % host) # We need to manually set the urlconf for the whole thread. Normally, Django's basic request # would do this for us, but we already need it in place for the other middlewares. set_urlconf(request.urlconf)
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
def validate(self, data): response_id = data.get('response_id') form_continue_url = data.get('form_continue_url') form_response = FormDocumentResponse.objects.get(pk=response_id) subdomain = form_response.form_document.owner.site.domain netloc = urlparse(form_continue_url).netloc continue_url_origin, _ = split_domain_port(netloc) if continue_url_origin == subdomain: return data else: raise serializers.ValidationError( "Request origin does not match form continue origin")
def get_cookie_domain(request): if "." not in request.host: # As per spec, browsers do not accept cookie domains without dots in it, # e.g. "localhost", see http://curl.haxx.se/rfc/cookie_spec.html return None default_domain, _ = split_domain_port(settings.SITE_NETLOC) # If we are on our main domain, set the cookie domain the user has chosen. Else # we are on an organiser's custom domain, set no cookie domain, as we do not want # the cookies to be present on any other domain. Setting an explicit value can be # dangerous, see http://erik.io/blog/2014/03/04/definitive-guide-to-cookie-domains/ return settings.SESSION_COOKIE_DOMAIN if request.host == default_domain else None
def __call__(self, request): domain, port = split_domain_port(request.get_host()) try: current_site = Site.objects.get(domain=domain) except Site.DoesNotExist: current_site = Site.objects.get(id=settings.SITE_ID) request.site = current_site _thread_local.request = request return self.get_response(request)
def test_re_usage(self): """ e.g.: django.http.request.split_domain_port used RE in test environment :return: """ host = self.fnmatch_ips[0] self.assertTrue(host_validation_re.match(host)) domain, port = split_domain_port(host) assert_pformat_equal(domain, "127.0.0.1") assert_pformat_equal(port, "")
def get_domains(self): """ Yields domains *without* any ports defined, as that's what `validate_host` wants """ from django.http.request import split_domain_port raw_sites = self.get_raw_sites() domains = set() raw_domains = (site.domain for site in raw_sites) for domain in raw_domains: domain_host, domain_port = split_domain_port(domain) domains.add(domain_host) return frozenset(domains)
def _get_site_by_request(self, request): host = request.get_host() try: # First attempt to look up the site by host with or without port. if host not in SITE_CACHE: SITE_CACHE[host] = self.get(domain__iexact=host) return SITE_CACHE[host] except Site.DoesNotExist: # Fallback to looking up site after stripping port from the host. domain, port = split_domain_port(host) if domain not in SITE_CACHE: SITE_CACHE[domain] = self.get(domain__iexact=domain) return SITE_CACHE[domain]
def process_request(self, request): dom, port = split_domain_port(request.get_host()) matching_domains = [ domain for domain in settings.RESELLER_DOMAINS if dom.endswith(domain) ] if len(matching_domains) > 0: settings.CSRF_COOKIE_DOMAIN = settings.RESELLER_DOMAINS[ matching_domains[0]]['cookie_domain'] settings.CSRF_COOKIE_NAME = 'csrftoken' else: settings.CSRF_COOKIE_DOMAIN = None settings.CSRF_COOKIE_NAME = 'csrftoken'
def validate_redirect_url(next_url): """ Returns the next_url path if next_url matches allowed hosts. """ if not next_url: return None parts = urlparse.urlparse(next_url) if parts.netloc: domain, _ = split_domain_port(parts.netloc) allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS if not (domain and validate_host(domain, allowed_hosts)): return None return parts.path
def __call__(self, request): """Enforce the host name""" host = request.get_host() domain, port = split_domain_port(host) if domain in self.allowed_hosts or is_ip_address(domain): return self.get_response(request) # redirect to the proper host name\ new_url = "%s://%s%s" % ( 'https' if request.is_secure() else 'http', self.allowed_hosts[0], request.get_full_path()) return HttpResponsePermanentRedirect(new_url)
def validate_redirect_url(next_url): """ Returns the next_url path if next_url matches allowed hosts. """ if not next_url: return None parts = urlparse.urlparse(next_url) if parts.netloc: domain, _ = split_domain_port(parts.netloc) allowed_hosts = ["*"] if settings.DEBUG else settings.ALLOWED_HOSTS if not (domain and validate_host(domain, allowed_hosts)): return None return urlparse.urlunparse((parts.scheme, "", parts.path, parts.params, parts.query, parts.fragment))
def __call__(self, request): """Enforce the host name""" host = request.get_host() domain, port = split_domain_port(host) if domain in self.allowed_hosts or is_ip_address(domain): return self.get_response(request) # redirect to the proper host name\ new_url = "%s://%s%s" % ('https' if request.is_secure() else 'http', self.allowed_hosts[0], request.get_full_path()) return HttpResponsePermanentRedirect(new_url)
def _get_host(request=None): if request is None: if 'airavata.middleware.ThreadLocalMiddleware' in settings.MIDDLEWARE_CLASSES: from threadlocals.threadlocals import get_thread_variable host = get_thread_variable('requested_host') if host is None: raise NoRequestFound("HostName could not be retrieved") return host else: raise ImproperlyConfigured( "You should either provide a request or install threadlocals") domain_host, domain_port = split_domain_port(request.get_host()) return domain_host
def process_request(self, request): # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ('HTTP_X_FORWARDED_HOST' in request.META): host = request.META['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in request.META: host = request.META['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = request.META['SERVER_NAME'] server_port = str(request.META['SERVER_PORT']) if server_port != ('443' if request.is_secure() else '80'): host = '%s:%s' % (host, server_port) domain, port = split_domain_port(host) default_domain, default_port = split_domain_port( urlparse(settings.SITE_URL).netloc) if domain: request.host = domain request.port = int(port) if port else None try: kd = KnownDomain.objects.get(domainname=domain) # noqa request.domain = kd except: if settings.DEBUG or domain in ( 'testserver', 'localhost') or domain == default_domain: request.urlconf = "pretix.multidomain.maindomain_urlconf" else: raise DisallowedHost("Unknown host: %r" % host) else: request.organizer = kd.organizer request.urlconf = "pretix.multidomain.subdomain_urlconf" else: raise DisallowedHost("Invalid HTTP_HOST header: %r." % host) # We need to manually set the urlconf for the whole thread. Normally, Django's basic request # would do this for us, but we already need it in place for the other middlewares. set_urlconf(request.urlconf)
def _get_dropbox_auth_flow(request): redirect_uri = request.build_absolute_uri(reverse('dropbox_auth_finish')) domain, port = split_domain_port(request.get_host()) local_domains = ('localhost', '127.0.0.1', '[::1]') if (request.scheme == 'http' and domain not in local_domains): # Force redirect_uri to use https, even if scheme is http redirect_uri = 'https://' + redirect_uri[7:] return DropboxOAuth2Flow( settings.DROPBOX_APP_KEY, settings.DROPBOX_APP_SECRET, redirect_uri, request.session, 'dropbox-auth-csrf-token' )
def get_cookie_domain(request): if "." not in request.host: # As per spec, browsers do not accept cookie domains without dots in it, # e.g. "localhost", see http://curl.haxx.se/rfc/cookie_spec.html return None default_domain, default_port = split_domain_port(urlparse(settings.SITE_URL).netloc) if request.host == default_domain: # We are on our main domain, set the cookie domain the user has chosen return settings.SESSION_COOKIE_DOMAIN else: # We are on an organizer's custom domain, set no cookie domain, as we do not want # the cookies to be present on any other domain. Setting an explicit value can be # dangerous, see http://erik.io/blog/2014/03/04/definitive-guide-to-cookie-domains/ return None
def post(self, request): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file = file_serializer.save() host = request.get_host() domain, _ = split_domain_port(host) port = request.get_port() file_url = "http://{0}:{1}{2}{3}".format(domain, port, settings.MEDIA_URL, file) return Response({'url': file_url}, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def validate_redirect_url(next_url): """ Returns the next_url path if next_url matches allowed hosts. """ if not next_url: return None parts = six.moves.urllib.parse.urlparse(next_url) if parts.netloc: domain, _ = split_domain_port(parts.netloc) allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS if not (domain and validate_host(domain, allowed_hosts)): return None return six.moves.urllib.parse.urlunparse( ("", "", parts.path, parts.params, parts.query, parts.fragment))
def get_site_from_request_origin(request): origin = request.META.get('HTTP_ORIGIN', None) if not origin: return None if not origin.startswith('http'): # During the test, the ORIGIN has not schema origin = '//' + origin netloc = urlparse(origin).netloc domain, port = split_domain_port(netloc) try: return Site.objects.get(domain=domain) except Site.DoesNotExist: return None
def validate_storefront_url(url): """Validate the storefront URL. Raise ValidationError if URL isn't in RFC 1808 format or it isn't allowed by ALLOWED_CLIENT_HOSTS in settings. """ try: parsed_url = urlparse(url) domain, _ = split_domain_port(parsed_url.netloc) except ValueError as error: raise ValidationError({"redirectUrl": str(error)}) if not validate_host(domain, settings.ALLOWED_CLIENT_HOSTS): error_message = (f"{domain or url} is not allowed. Please check " "`ALLOWED_CLIENT_HOSTS` configuration.") raise ValidationError({"redirectUrl": error_message})
def _get_domain_by_request(self, request): host = request.get_host() d = re.compile('www.(.*?).example.com') d = d.search(host) d = d.group(1) try: if host not in DOMAINS_CACHE: DOMAINS_CACHE[host] = self.get(name__icontains=d) return DOMAINS_CACHE[host] except Website.DoesNotExist: domain, port = split_domain_port(host) if domain not in DOMAINS_CACHE: print(d) DOMAINS_CACHE[domain] = self.get(name__icontains=d) return DOMAINS_CACHE[domain]
def process_request(self, request): domain, port = split_domain_port(request.get_host()) self._changes = {} for site in settings.SITES: site = site.copy() try: if validate_host(domain, site['HOSTS']): site_settings = '.'.join( [self.top_module, site['NAME'], 'settings']) self._enter(import_module(site_settings)) break except ImportError: pass
def get_next_redirect_url(self, request: HttpRequest) -> Optional[str]: user = getattr(request, 'user', None) if user.is_authenticated: self.logout(request) next_url = get_social_next_from_referer_url(request) next_url = build_absolute_uri(request, next_url) r = urlparse(next_url) host = r.netloc domain, port = split_domain_port(host) allowed_hosts = settings.ALLOWED_HOSTS if domain and validate_host(domain, allowed_hosts): return next_url raise DisallowedRedirect("Attempted access from '%s' denied." % next_url)
def get_domains(self): """ Yields domains *without* any ports defined, as that's what `validate_host` wants """ raw_sites = self.get_raw_sites() raw_aliases = self.get_raw_aliases() domains = set() for domain_list in (raw_sites, raw_aliases): raw_domains = (item.domain for item in domain_list) for domain in raw_domains: domain_host, domain_port = split_domain_port(domain) domains.add(domain_host) return frozenset(domains)
def process_request(self, request): host = request.get_host() domain, port = split_domain_port(host) if domain and validate_host(domain, ORIG_ALLOWED_HOSTS): return None for net in self.allowed_cidr_nets: try: if domain in net: return None except AddrFormatError: # not an IP break raise DisallowedHost("Invalid HTTP_HOST header: %r." % host)
def get_current(self, request=None): try: return old_get_current(self, request) except (ImproperlyConfigured, Site.DoesNotExist): if not request: return Site(domain='localhost', name='localhost') host = request.get_host() domain, port = split_domain_port(host) protocol = request.META['wsgi.url_scheme'] Site.objects.create( name=domain.capitalize(), domain=host, port=port or 443 if protocol == 'https' else 80, protocol=protocol, ) return old_get_current(self, request)
def validate_redirect_url(next_url): """ Returns the next_url path if next_url matches allowed hosts. """ # This method is copy/pasted from signup.auth so we donot need # to add djaodjin-signup as a prerequisites. It is possible # the functionality has already moved into Django proper. if not next_url: return None parts = urlparse.urlparse(next_url) if parts.netloc: domain, _ = split_domain_port(parts.netloc) allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS if not (domain and validate_host(domain, allowed_hosts)): return None return parts.path
def get_context_data(self, **kwargs): ctx = super(PaymentDetailsView, self).get_context_data(**kwargs) extra = Source.get_provider( self.checkout_session.payment_method()).extra ctx["payment_method"] = extra.get("verbose_name", extra["name"]) host = ctx.get("source", None) if host: host = host.temp_form if host: host = host.action ctx["is_local_url"] = (host == "") if host is not None and not ctx["is_local_url"]: #try harder domain = split_domain_port(host)[0] if domain and validate_host(domain, self._allowed_hosts): ctx["is_local_url"] = True return ctx
def __call__(self, request): domain, _ = split_domain_port(request.get_host()) # Get the production domain corresponding to the current site in dev mode. if settings.DEBUG: try: domain = MultiSiteMiddleware.OVERLOADING_MATCHING_TABLE[domain] except KeyError: raise ImproperlyConfigured( f'No matching overloaded domain for {domain}') # Get current site object and set SITE_ID. try: current_site = Site.objects.get(domain=domain) except Site.DoesNotExist: current_site = Site.objects.get(id=settings.DEFAULT_SITE_ID) request.current_site = current_site settings.SITE_ID = current_site.id settings.site_domain = domain # Determine the module path which contains site-wise assets. site_path = settings.site_domain.replace('.', '-') # Override settings. try: new_settings = import_module(f'overload.{site_path}.settings') except (ModuleNotFoundError, ImportError): new_settings = import_module(f'overload.default_settings') finally: for field in self.OVERRIDING_FIELDS: if hasattr(new_settings, field): new_value = getattr(new_settings, field) setattr(settings, field, new_value) # Override URL patterns. try: override_urls = import_module(f'overload.{site_path}.urls') if hasattr(override_urls, 'urlpatterns'): settings.override_urlpatterns = override_urls.urlpatterns request.urlconf = f'overload.{site_path}.urls' except ImportError: # fallback to the default URL pass response = self.get_response(request) return response
def process_request(self, request): domain, _ = split_domain_port(request.get_host()) for site in settings.SITES: site = site.copy() try: if validate_host(domain, site["HOSTS"]): urlconf = ".".join([self.top_module, site["NAME"], "urls"]) import_module(urlconf) break except ImportError: pass except Exception: # pylint: disable=broad-except pass else: urlconf = settings.ROOT_URLCONF request.urlconf = urlconf
def validate_safesens_url(url): """Validate the safesens URL. Raise ValidationError if URL isn't in RFC 1808 format or it isn't allowed by ALLOWED_CLIENT_HOSTS in settings. """ try: parsed_url = urlparse(url) domain, _ = split_domain_port(parsed_url.netloc) if not parsed_url.netloc: raise ValidationError( "Invalid URL. Please check if URL is in RFC 1808 format.") except ValueError as error: raise ValidationError(error) if not validate_host(domain, settings.ALLOWED_CLIENT_HOSTS): error_message = (f"{domain or url} is not allowed. Please check " "`ALLOWED_CLIENT_HOSTS` configuration.") raise ValidationError(error_message)
def patched_get_site_by_request(self, request): host = request.get_host() key = _cache_key_for_site_host(host) site = cache.get(key) if site is None: try: # First attempt to look up the site by host with or without port. site = self.get(domain__iexact=host) except Site.DoesNotExist: # Fallback to looking up site after stripping port from the host. domain, port = split_domain_port(host) if not port: raise site = self.get(domain__iexact=domain) SITE_CACHE[host] = site cache.add(key, site) return site
def process_request(self, request): domain, port = split_domain_port(request.get_host()) for site in settings.SITES: site = site.copy() try: if validate_host(domain, site['HOSTS']): urlconf = '.'.join([self.top_module, site['NAME'], 'urls']) import_module(urlconf) break except ImportError: pass except Exception: pass else: urlconf = settings.ROOT_URLCONF request.urlconf = urlconf
def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(callback, 'origin_poikkeus', False): return None elif 'HTTP_ORIGIN' not in request.META: return None origin = split_domain_port( urlparse(request.META['HTTP_ORIGIN']).netloc.lower())[0] if not validate_host(origin, settings.ALLOWED_HOSTS): virhe = 'Websocket: Origin=%r ei vastaa ALLOWED_HOSTS-asetusta.' % origin response = HttpResponseForbidden(virhe) log_response( virhe, request=request, response=response, logger=logger, ) return response # if not validate_host return None
def __call__(self, request): host = request._get_raw_host() domain, port = split_domain_port(host) # Set request.site request.site = self.default_site for name, config in settings.XMPP_HOSTS.items(): if validate_host(domain, config.get('ALLOWED_HOSTS', [])): request.site = config # Attach any messages from the database to the messages system # These messages usually come from asynchronous tasks (-> Celery) if request.user.is_anonymous is False: with transaction.atomic(): stored_msgs = CachedMessage.objects.filter(user=request.user) for msg in stored_msgs: messages.add_message( request, msg.level, _(msg.message) % json.loads(msg.payload)) stored_msgs.delete() # Attach OS information to request request.os = self.get_os(request) request.os_mobile = request.os in ['android', 'ios', 'any'] # Get data that is used with every request and requires database access and cache it cache_key = 'request_context' cached = cache.get(cache_key) if cached is None: cached = { 'menuitems': MenuItem.objects.all(), } for item in cached['menuitems']: item.cached_data # touch cached_data to make sure that all properties serialized cache.set(cache_key, cached) request.hp_request_context = cached response = self.get_response(request) return response
def __call__(self, request): host = request._get_raw_host() domain, port = split_domain_port(host) # Set request.site request.site = self.default_site for name, config in settings.XMPP_HOSTS.items(): if validate_host(domain, config.get('ALLOWED_HOSTS', [])): request.site = config # Attach any messages from the database to the messages system # These messages usually come from asynchronous tasks (-> Celery) if request.user.is_anonymous is False: with transaction.atomic(): stored_msgs = CachedMessage.objects.filter(user=request.user) for msg in stored_msgs: messages.add_message(request, msg.level, _(msg.message) % json.loads(msg.payload)) stored_msgs.delete() # Attach OS information to request request.os = self.get_os(request) request.os_mobile = request.os in ['android', 'ios', 'any'] # Get data that is used with every request and requires database access and cache it cache_key = 'request_context' cached = cache.get(cache_key) if cached is None: cached = { 'menuitems': MenuItem.objects.all(), } for item in cached['menuitems']: item.cached_data # touch cached_data to make sure that all properties serialized cache.set(cache_key, cached) request.hp_request_context = cached response = self.get_response(request) return response
def send_new_user_email(request, username, email, first_name, last_name): """Send new user email notification to portal admins.""" new_user_email_template = models.EmailTemplate.objects.get( pk=models.NEW_USER_EMAIL_TEMPLATE) domain, port = split_domain_port(request.get_host()) context = Context({ "username": username, "email": email, "first_name": first_name, "last_name": last_name, "portal_title": settings.PORTAL_TITLE, "gateway_id": settings.GATEWAY_ID, "http_host": domain, }) subject = Template(new_user_email_template.subject).render(context) body = Template(new_user_email_template.body).render(context) msg = EmailMessage(subject=subject, body=body, from_email="{} <{}>".format(settings.PORTAL_TITLE, settings.SERVER_EMAIL), to=[a[1] for a in settings.PORTAL_ADMINS]) msg.content_subtype = 'html' msg.send()
def assert_redirects(response, expected_url, status_code=302, target_status_code=200, fetch_redirect_response=True): ''' Assert that a response redirected to a specific URL and that the redirect URL can be loaded. Won't work for external links since it uses the test client to do a request (use fetch_redirect_response=False to check such links without fetching them). ''' __tracebackhide__ = True if hasattr(response, 'redirect_chain'): # The request was a followed redirect assert len(response.redirect_chain) > 0, _error( 'Response didn\'t redirect as expected: ' 'Response code was {0} (expected {1})', response.status_code, status_code ) assert response.redirect_chain[0][1] == status_code, _error( 'Initial response didn\'t redirect as expected: ' 'Response code was {0} (expected {1})', response.redirect_chain[0][1], status_code ) url, status_code = response.redirect_chain[-1] scheme, netloc, path, query, fragment = urlsplit(url) assert response.status_code == target_status_code, _error( 'Response didn\'t redirect as expected: ' 'Final Response code was {0} (expected {1})', response.status_code, target_status_code ) else: # Not a followed redirect assert response.status_code == status_code, _error( 'Response didn\'t redirect as expected: ' 'Response code was {0} (expected {1})', response.status_code, status_code ) url = response.url scheme, netloc, path, query, fragment = urlsplit(url) # Prepend the request path to handle relative path redirects. if not path.startswith('/'): url = urljoin(response.request['PATH_INFO'], url) path = urljoin(response.request['PATH_INFO'], path) if fetch_redirect_response: # netloc might be empty, or in cases where Django tests the # HTTP scheme, the convention is for netloc to be 'testserver'. # Trust both as "internal" URLs here. domain, port = split_domain_port(netloc) if domain and not validate_host(domain, settings.ALLOWED_HOSTS): raise ValueError( 'The test client is unable to fetch remote URLs (got {0}). ' 'If the host is served by Django, add "{1}" to ALLOWED_HOSTS. ' 'Otherwise, use assertRedirects(..., fetch_redirect_response=False).' ''.format(url, domain) ) redirect_response = response.client.get(path, QueryDict(query), secure=(scheme == 'https')) # Get the redirection page, using the same client that was used # to obtain the original response. assert redirect_response.status_code == target_status_code, _error( 'Couldn\'t retrieve redirection page "{0}": ' 'response code was {1} (expected {2})', path, redirect_response.status_code, target_status_code ) assert url == expected_url, 'Response redirected to "{0}", expected "{1}"'.foramt(url, expected_url)
def validate(request): domain, port = split_domain_port(request.META['HTTP_HOST']) if not validate_host(domain, settings.CC_ALLOWED_HOSTS): return HttpResponseForbidden('forbiden') return func(request)
def test_split_domain_port_removes_trailing_dot(self): domain, port = split_domain_port('example.com.:8080') self.assertEqual(domain, 'example.com') self.assertEqual(port, '8080')
from __future__ import unicode_literals
def process_request(self, request): if 'HTTP_HOST' in request.META: host = request.META['HTTP_HOST'] domain, port = split_domain_port(host) if domain in ['111.11.84.251', '111.11.84.252']: request.META['HTTP_HOST'] = domain
def getOmeroHost(request, host=None): if not host or host in ("localhost", "127.0.0.1"): hostport = request.get_host() host, port = split_domain_port(hostport) return host