def proxy_request(request, path): if sys.version_info > (3, 0): # Python 3 code in this block get_keys = request.GET.keys() else: # Python 2 code in this block get_keys = request.GET.iterkeys() parameters = [] for key in get_keys: value_list = request.GET.getlist(key) if key == 'viewparams': parameters.extend(['%s=%s' % ( key, urllib.quote(val)) for val in value_list]) else: parameters.extend(['%s=%s' % (key, val) for val in value_list]) if parameters: path += '?' + '&'.join(parameters) # If somehow we get malformed url if len(path.split('://')) == 1: new_path = path.split(':/') path = '://'.join(new_path) request.session['access_token'] = None return proxy(request, url=path)
def service_proxy(request, service_id): service = get_object_or_404(Service, pk=service_id) if not service.proxy_base: service_url = service.base_url else: service_url = f"{service.base_url}?{request.META['QUERY_STRING']}" if urljoin(settings.SITEURL, reverse('proxy')) != service.proxy_base: service_url = f"{service.proxy_base}?url={quote(service_url, safe='')}" return proxy(request, url=service_url, sec_chk_hosts=False)
def geoserver_proxy(request, proxy_path, downstream_path, workspace=None, layername=None): """ WARNING: Decorators are applied in the order they appear in the source. """ affected_datasets = None allowed_hosts = [urlsplit(ogc_server_settings.public_url).hostname, ] raw_url, headers, access_token = check_geoserver_access( request, proxy_path, downstream_path, workspace=workspace, layername=layername, allowed_hosts=allowed_hosts) url = urlsplit(raw_url) if request.method in ("POST", "PUT", "DELETE"): if downstream_path in ('rest/styles', 'rest/layers', 'rest/workspaces'): if not style_change_check(request, downstream_path, access_token=access_token): return HttpResponse( _("You don't have permissions to change style for this layer"), content_type="text/plain", status=401) elif downstream_path == 'rest/styles': logger.debug( f"[geoserver_proxy] Updating Style ---> url {url.geturl()}") _style_name, _style_ext = os.path.splitext(os.path.basename(urlsplit(url.geturl()).path)) _parsed_get_args = dict(parse_qsl(urlsplit(url.geturl()).query)) if _style_name == 'styles.json' and request.method == "PUT": if _parsed_get_args.get('name'): _style_name, _style_ext = os.path.splitext(_parsed_get_args.get('name')) else: _style_name, _style_ext = os.path.splitext(_style_name) if _style_name != 'style-check' and (_style_ext == '.json' or _parsed_get_args.get('raw')) and \ not re.match(temp_style_name_regex, _style_name): affected_datasets = style_update(request, raw_url, workspace) elif downstream_path == 'rest/layers': logger.debug(f"[geoserver_proxy] Updating Dataset ---> url {url.geturl()}") try: _dataset_name = os.path.splitext(os.path.basename(request.path))[0] _dataset = Dataset.objects.get(name=_dataset_name) affected_datasets = [_dataset] except Exception: logger.warn(f"Could not find any Dataset {os.path.basename(request.path)} on DB") kwargs = {'affected_datasets': affected_datasets} raw_url = unquote(raw_url) timeout = getattr(ogc_server_settings, 'TIMEOUT') or 60 response = proxy(request, url=raw_url, response_callback=_response_callback, timeout=timeout, allowed_hosts=allowed_hosts, headers=headers, access_token=access_token, **kwargs) return response
def service_proxy(request, service_id): service = get_object_or_404(Service, pk=service_id) if not service.proxy_base: service_url = service.base_url else: service_url = "{ows_url}?{ows_request}".format( ows_url=service.base_url, ows_request=request.META['QUERY_STRING']) if urljoin(settings.SITEURL, reverse('proxy')) != service.proxy_base: service_url = "{proxy_base}?url={service_url}".format(proxy_base=service.proxy_base, service_url=quote(service_url, safe='')) return proxy(request, url=service_url, sec_chk_hosts=False)
def print_map(request): from django.conf import settings from geonode.proxy.views import proxy from geonode.layers.models import Layer permissions = {} params = json.loads(request.body) for layer in params['layers']: for layer_name in layer['layers']: layer_obj = Layer.objects.get(typename=layer_name) permissions[layer_obj] = {} permissions[layer_obj]['anonymous'] = layer_obj.get_gen_level(ANONYMOUS_USERS) permissions[layer_obj]['authenticated'] = layer_obj.get_gen_level(AUTHENTICATED_USERS) layer_obj.set_gen_level(ANONYMOUS_USERS,'layer_readonly') try: resp = proxy(request) except Exception, e: return HttpResponse('There was an error connecting to the printing server: %s' % e)
def geoserver_proxy(request, proxy_path, downstream_path, workspace=None, layername=None): """ WARNING: Decorators are applied in the order they appear in the source. """ # AF: No need to authenticate first. We will check if "access_token" is present # or not on session # @dismissed # if not request.user.is_authenticated(): # return HttpResponse( # "You must be logged in to access GeoServer", # content_type="text/plain", # status=401) def strip_prefix(path, prefix): assert prefix in path prefix_idx = path.index(prefix) _prefix = path[:prefix_idx] + prefix full_prefix = "%s/%s/%s" % (_prefix, layername, downstream_path) if layername else _prefix return path[len(full_prefix):] path = strip_prefix(request.get_full_path(), proxy_path) raw_url = str("".join( [ogc_server_settings.LOCATION, downstream_path, path])) if settings.DEFAULT_WORKSPACE or workspace: ws = (workspace or settings.DEFAULT_WORKSPACE) if ws and ws in path: # Strip out WS from PATH try: path = "/%s" % strip_prefix(path, "/%s:" % (ws)) except BaseException: pass if proxy_path == '/gs/%s' % settings.DEFAULT_WORKSPACE and layername: import posixpath raw_url = urljoin( ogc_server_settings.LOCATION, posixpath.join(workspace, layername, downstream_path, path)) if downstream_path in ('rest/styles') and len(request.body) > 0: if ws: # Lets try # http://localhost:8080/geoserver/rest/workspaces/<ws>/styles/<style>.xml _url = str("".join([ ogc_server_settings.LOCATION, 'rest/workspaces/', ws, '/styles', path ])) else: _url = str("".join( [ogc_server_settings.LOCATION, 'rest/styles', path])) raw_url = _url if downstream_path in 'ows' and ( 'rest' in path or re.match(r'/(w.*s).*$', path, re.IGNORECASE) or re.match(r'/(ows).*$', path, re.IGNORECASE)): _url = str("".join([ogc_server_settings.LOCATION, '', path[1:]])) raw_url = _url url = urlsplit(raw_url) affected_layers = None if '%s/layers' % ws in path: downstream_path = 'rest/layers' elif '%s/styles' % ws in path: downstream_path = 'rest/styles' if request.method in ("POST", "PUT", "DELETE"): if downstream_path in ('rest/styles', 'rest/layers', 'rest/workspaces'): if not style_change_check(request, downstream_path): return HttpResponse(_( "You don't have permissions to change style for this layer" ), content_type="text/plain", status=401) elif downstream_path == 'rest/styles': logger.info("[geoserver_proxy] Updating Style ---> url %s" % url.geturl()) affected_layers = style_update(request, raw_url) elif downstream_path == 'rest/layers': logger.debug("[geoserver_proxy] Updating Layer ---> url %s" % url.geturl()) try: _layer_name = os.path.splitext( os.path.basename(request.path))[0] _layer = Layer.objects.get(name__icontains=_layer_name) affected_layers = [_layer] except BaseException: logger.warn("Could not find any Layer %s on DB" % os.path.basename(request.path)) kwargs = {'affected_layers': affected_layers} import urllib raw_url = urllib.unquote(raw_url).decode('utf8') timeout = getattr(ogc_server_settings, 'TIMEOUT') or 10 allowed_hosts = [ urlsplit(ogc_server_settings.public_url).hostname, ] return proxy(request, url=raw_url, response_callback=_response_callback, timeout=timeout, allowed_hosts=allowed_hosts, **kwargs)
def geoserver_proxy(request, proxy_path, downstream_path, workspace=None, layername=None): """ WARNING: Decorators are applied in the order they appear in the source. """ # AF: No need to authenticate first. We will check if "access_token" is present # or not on session # @dismissed # if not request.user.is_authenticated: # return HttpResponse( # "You must be logged in to access GeoServer", # content_type="text/plain", # status=401) def strip_prefix(path, prefix): if prefix not in path: _s_prefix = prefix.split('/', 3) _s_path = path.split('/', 3) assert _s_prefix[1] == _s_path[1] _prefix = f'/{_s_path[1]}/{_s_path[2]}' else: _prefix = prefix assert _prefix in path prefix_idx = path.index(_prefix) _prefix = path[:prefix_idx] + _prefix full_prefix = f"{_prefix}/{layername}/{downstream_path}" if layername else _prefix return path[len(full_prefix):] path = strip_prefix(request.get_full_path(), proxy_path) raw_url = str("".join( [ogc_server_settings.LOCATION, downstream_path, path])) if settings.DEFAULT_WORKSPACE or workspace: ws = (workspace or settings.DEFAULT_WORKSPACE) if ws and ws in path: # Strip out WS from PATH try: path = f'/{strip_prefix(path, f"/{ws}:")}' except Exception: pass if proxy_path == f'/gs/{settings.DEFAULT_WORKSPACE}' and layername: import posixpath raw_url = urljoin( ogc_server_settings.LOCATION, posixpath.join(workspace, layername, downstream_path, path)) if downstream_path in ('rest/styles') and len(request.body) > 0: if ws: # Lets try # http://localhost:8080/geoserver/rest/workspaces/<ws>/styles/<style>.xml _url = str("".join([ ogc_server_settings.LOCATION, 'rest/workspaces/', ws, '/styles', path ])) else: _url = str("".join( [ogc_server_settings.LOCATION, 'rest/styles', path])) raw_url = _url if downstream_path in 'ows' and ( 'rest' in path or re.match(r'/(w.*s).*$', path, re.IGNORECASE) or re.match(r'/(ows).*$', path, re.IGNORECASE)): _url = str("".join([ogc_server_settings.LOCATION, '', path[1:]])) raw_url = _url url = urlsplit(raw_url) affected_layers = None if f'{ws}/layers' in path: downstream_path = 'rest/layers' elif f'{ws}/styles' in path: downstream_path = 'rest/styles' if request.method in ("POST", "PUT", "DELETE"): if downstream_path in ('rest/styles', 'rest/layers', 'rest/workspaces'): if not style_change_check(request, downstream_path): return HttpResponse(_( "You don't have permissions to change style for this layer" ), content_type="text/plain", status=401) elif downstream_path == 'rest/styles': logger.debug( f"[geoserver_proxy] Updating Style ---> url {url.geturl()}" ) _style_name, _style_ext = os.path.splitext( os.path.basename(urlsplit(url.geturl()).path)) if _style_name == 'styles.json' and request.method == "PUT": _parsed_get_args = dict( parse_qsl(urlsplit(url.geturl()).query)) if 'name' in _parsed_get_args: _style_name, _style_ext = os.path.splitext( _parsed_get_args['name']) else: _style_name, _style_ext = os.path.splitext(_style_name) if _style_name != 'style-check' and _style_ext == '.json' and \ not re.match(temp_style_name_regex, _style_name): affected_layers = style_update(request, raw_url) elif downstream_path == 'rest/layers': logger.debug( f"[geoserver_proxy] Updating Layer ---> url {url.geturl()}" ) try: _layer_name = os.path.splitext( os.path.basename(request.path))[0] _layer = Layer.objects.get(name__icontains=_layer_name) affected_layers = [_layer] except Exception: logger.warn( f"Could not find any Layer {os.path.basename(request.path)} on DB" ) kwargs = {'affected_layers': affected_layers} raw_url = unquote(raw_url) timeout = getattr(ogc_server_settings, 'TIMEOUT') or 60 allowed_hosts = [ urlsplit(ogc_server_settings.public_url).hostname, ] response = proxy(request, url=raw_url, response_callback=_response_callback, timeout=timeout, allowed_hosts=allowed_hosts, **kwargs) return response
def geoserver_proxy(request, proxy_path, downstream_path, workspace=None, layername=None): """ WARNING: Decorators are applied in the order they appear in the source. """ # AF: No need to authenticate first. We will check if "access_token" is present # or not on session # @dismissed # if not request.user.is_authenticated(): # return HttpResponse( # "You must be logged in to access GeoServer", # content_type="text/plain", # status=401) def strip_prefix(path, prefix): assert path.startswith(prefix) full_prefix = "%s/%s/%s" % (prefix, layername, downstream_path) if layername else prefix return path[len(full_prefix):] path = strip_prefix(request.get_full_path(), proxy_path) access_token = None if request and 'access_token' in request.session: access_token = request.session['access_token'] if access_token and 'access_token' not in path: query_separator = '&' if '?' in path else '?' path = ('%s%saccess_token=%s' % (path, query_separator, access_token)) raw_url = str("".join( [ogc_server_settings.LOCATION, downstream_path, path])) if settings.DEFAULT_WORKSPACE or workspace: ws = (workspace or settings.DEFAULT_WORKSPACE) if ws and ws in path: # Strip out WS from PATH try: path = "/%s" % strip_prefix(path, "/%s:" % (ws)) except BaseException: pass if proxy_path == '/gs/%s' % settings.DEFAULT_WORKSPACE and layername: import posixpath raw_url = urljoin( ogc_server_settings.LOCATION, posixpath.join(workspace, layername, downstream_path, path)) if downstream_path in ('rest/styles') and len(request.body) > 0: # Lets try # http://localhost:8080/geoserver/rest/workspaces/<ws>/styles/<style>.xml _url = str("".join([ ogc_server_settings.LOCATION, 'rest/workspaces/', ws, '/styles', path ])) raw_url = _url if downstream_path in 'ows' and ( 'rest' in path or re.match(r'/(w.*s).*$', path, re.IGNORECASE) or re.match(r'/(ows).*$', path, re.IGNORECASE)): _url = str("".join([ogc_server_settings.LOCATION, '', path[1:]])) raw_url = _url url = urlsplit(raw_url) affected_layers = None if request.method in ("POST", "PUT"): if downstream_path in ('rest/styles', 'rest/layers', 'rest/workspaces') and len(request.body) > 0: if not style_change_check(request, downstream_path): return HttpResponse(_( "You don't have permissions to change style for this layer" ), content_type="text/plain", status=401) elif downstream_path == 'rest/styles': logger.info("[geoserver_proxy] Updating Style to ---> url %s" % url.path) affected_layers = style_update(request, raw_url) kwargs = {'affected_layers': affected_layers} return proxy(request, url=raw_url, response_callback=_response_callback, **kwargs)
def geoserver_proxy(request, proxy_path, downstream_path, workspace=None, layername=None): """ WARNING: Decorators are applied in the order they appear in the source. """ # AF: No need to authenticate first. We will check if "access_token" is present # or not on session # @dismissed # if not request.user.is_authenticated(): # return HttpResponse( # "You must be logged in to access GeoServer", # content_type="text/plain", # status=401) def strip_prefix(path, prefix): assert path.startswith(prefix) full_prefix = "%s/%s/%s" % ( prefix, layername, downstream_path) if layername else prefix return path[len(full_prefix):] path = strip_prefix(request.get_full_path(), proxy_path) access_token = None if request and 'access_token' in request.session: access_token = request.session['access_token'] if access_token and 'access_token' not in path: query_separator = '&' if '?' in path else '?' path = ('%s%saccess_token=%s' % (path, query_separator, access_token)) raw_url = str( "".join([ogc_server_settings.LOCATION, downstream_path, path])) if settings.DEFAULT_WORKSPACE or workspace: ws = (workspace or settings.DEFAULT_WORKSPACE) if ws and ws in path: # Strip out WS from PATH try: path = "/%s" % strip_prefix(path, "/%s:" % (ws)) except BaseException: pass if proxy_path == '/gs/%s' % settings.DEFAULT_WORKSPACE and layername: import posixpath raw_url = urljoin(ogc_server_settings.LOCATION, posixpath.join(workspace, layername, downstream_path, path)) if downstream_path in ('rest/styles') and len(request.body) > 0: # Lets try # http://localhost:8080/geoserver/rest/workspaces/<ws>/styles/<style>.xml _url = str("".join([ogc_server_settings.LOCATION, 'rest/workspaces/', ws, '/styles', path])) raw_url = _url if downstream_path in 'ows' and ( 'rest' in path or re.match(r'/(w.*s).*$', path, re.IGNORECASE) or re.match(r'/(ows).*$', path, re.IGNORECASE)): _url = str("".join([ogc_server_settings.LOCATION, '', path[1:]])) raw_url = _url url = urlsplit(raw_url) affected_layers = None if request.method in ("POST", "PUT"): if downstream_path in ('rest/styles', 'rest/layers', 'rest/workspaces') and len(request.body) > 0: if not style_change_check(request, downstream_path): return HttpResponse( _( "You don't have permissions to change style for this layer"), content_type="text/plain", status=401) elif downstream_path == 'rest/styles': logger.info( "[geoserver_proxy] Updating Style to ---> url %s" % url.path) affected_layers = style_update(request, raw_url) kwargs = {'affected_layers': affected_layers} return proxy(request, url=raw_url, response_callback=_response_callback, **kwargs)
def geoserver_proxy(request, proxy_path, downstream_path, workspace=None, layername=None): """ WARNING: Decorators are applied in the order they appear in the source. """ # AF: No need to authenticate first. We will check if "access_token" is present # or not on session # @dismissed # if not request.user.is_authenticated(): # return HttpResponse( # "You must be logged in to access GeoServer", # content_type="text/plain", # status=401) def strip_prefix(path, prefix): assert prefix in path prefix_idx = path.index(prefix) _prefix = path[:prefix_idx] + prefix full_prefix = "%s/%s/%s" % ( _prefix, layername, downstream_path) if layername else _prefix return path[len(full_prefix):] path = strip_prefix(request.get_full_path(), proxy_path) raw_url = str( "".join([ogc_server_settings.LOCATION, downstream_path, path])) if settings.DEFAULT_WORKSPACE or workspace: ws = (workspace or settings.DEFAULT_WORKSPACE) if ws and ws in path: # Strip out WS from PATH try: path = "/%s" % strip_prefix(path, "/%s:" % (ws)) except BaseException: pass if proxy_path == '/gs/%s' % settings.DEFAULT_WORKSPACE and layername: import posixpath raw_url = urljoin(ogc_server_settings.LOCATION, posixpath.join(workspace, layername, downstream_path, path)) if downstream_path in ('rest/styles') and len(request.body) > 0: if ws: # Lets try # http://localhost:8080/geoserver/rest/workspaces/<ws>/styles/<style>.xml _url = str("".join([ogc_server_settings.LOCATION, 'rest/workspaces/', ws, '/styles', path])) else: _url = str("".join([ogc_server_settings.LOCATION, 'rest/styles', path])) raw_url = _url if downstream_path in 'ows' and ( 'rest' in path or re.match(r'/(w.*s).*$', path, re.IGNORECASE) or re.match(r'/(ows).*$', path, re.IGNORECASE)): _url = str("".join([ogc_server_settings.LOCATION, '', path[1:]])) raw_url = _url url = urlsplit(raw_url) affected_layers = None if '%s/layers' % ws in path: downstream_path = 'rest/layers' elif '%s/styles' % ws in path: downstream_path = 'rest/styles' if request.method in ("POST", "PUT", "DELETE"): if downstream_path in ('rest/styles', 'rest/layers', 'rest/workspaces'): if not style_change_check(request, downstream_path): return HttpResponse( _( "You don't have permissions to change style for this layer"), content_type="text/plain", status=401) elif downstream_path == 'rest/styles': logger.info( "[geoserver_proxy] Updating Style ---> url %s" % url.geturl()) affected_layers = style_update(request, raw_url) elif downstream_path == 'rest/layers': logger.info( "[geoserver_proxy] Updating Layer ---> url %s" % url.geturl()) try: _layer_name = os.path.splitext(os.path.basename(request.path))[0] _layer = Layer.objects.get(name__icontains=_layer_name) affected_layers = [_layer] except BaseException: logger.warn("Could not find any Layer %s on DB" % os.path.basename(request.path)) kwargs = {'affected_layers': affected_layers} import urllib raw_url = urllib.unquote(raw_url).decode('utf8') timeout = getattr(ogc_server_settings, 'TIMEOUT') or 10 return proxy(request, url=raw_url, response_callback=_response_callback, timeout=timeout, **kwargs)