Exemplo n.º 1
0
    def get_cgxp_index_vars(self, templates_params={}):
        extra_params = {}

        if self.lang:
            extra_params["lang"] = self.lang

        # specific permalink_themes handling
        if "permalink_themes" in templates_params:
            extra_params["permalink_themes"] = templates_params["permalink_themes"]

        d = {
            "lang": self.lang,
            "debug": self.debug,
            "no_redirect": self.request.params.get("no_redirect") is not None,
            "extra_params": extra_params,
        }

        # general templates_params handling
        d.update(templates_params)

        # check if route to mobile app exists
        try:
            d["mobile_url"] = self.request.route_url("mobile_index_prod")
        except:  # pragma: no cover
            d["mobile_url"] = None

        set_common_headers(self.request, "cgxp_index", NO_CACHE)

        return d
Exemplo n.º 2
0
    def read_one(self):
        set_common_headers(self.request, "layers", NO_CACHE)

        layer = self._get_layer_for_request()
        protocol = self._get_protocol_for_layer(layer)
        feature_id = self.request.matchdict.get("feature_id", None)
        feature = protocol.read(self.request, id=feature_id)
        if not isinstance(feature, Feature):
            return feature
        if layer.public:
            return feature
        if self.request.user is None:
            raise HTTPForbidden()
        geom = feature.geometry
        if not geom or isinstance(geom, geojson.geometry.Default):  # pragma: no cover
            return feature
        shape = asShape(geom)
        srid = self._get_geom_col_info(layer)[1]
        spatial_elt = from_shape(shape, srid=srid)
        allowed = DBSession.query(func.count(RestrictionArea.id))
        allowed = allowed.join(RestrictionArea.roles)
        allowed = allowed.join(RestrictionArea.layers)
        allowed = allowed.filter(Role.id == self.request.user.role.id)
        allowed = allowed.filter(Layer.id == layer.id)
        allowed = allowed.filter(or_(
            RestrictionArea.area.is_(None),
            RestrictionArea.area.ST_Contains(spatial_elt)
        ))
        if allowed.scalar() == 0:
            raise HTTPForbidden()

        return feature
Exemplo n.º 3
0
 def json(self):
     """answers to /profile.json"""
     layer, points = self._compute_points()
     set_common_headers(
         self.request, "profile", NO_CACHE, add_cors=True
     )
     return {"profile": points}
Exemplo n.º 4
0
    def loginform(self):
        set_common_headers(self.request, "loginform", PUBLIC_CACHE, vary=True)

        return {
            "lang": self.lang,
            "came_from": self.request.params.get("came_from") or "/",
        }
Exemplo n.º 5
0
    def loginchange(self):
        set_common_headers(self.request, "loginchange", NO_CACHE)

        new_password = self.request.params.get("newPassword", None)
        new_password_confirm = self.request.params.get("confirmNewPassword", None)
        if new_password is None or new_password_confirm is None:
            raise HTTPBadRequest(
                "'newPassword' and 'confirmNewPassword' should be "
                "available in request params"
            )

        # check if loggedin
        if not self.request.user:
            raise HTTPUnauthorized("bad credentials")
        if new_password != new_password_confirm:
            raise HTTPBadRequest(
                "The new password and the new password "
                "confirmation don't match"
            )

        u = self.request.user
        u._set_password(new_password)
        u.is_password_changed = True
        DBSession.flush()
        log.info("Password changed for user: %s" % self.request.user.username)

        return {
            "success": "true"
        }
Exemplo n.º 6
0
    def delete(self):
        set_common_headers(self.request, "layers", NO_CACHE, add_cors=True)

        if self.request.user is None:
            raise HTTPForbidden()

        self.request.response.cache_control.no_cache = True

        feature_id = self.request.matchdict.get("feature_id", None)
        layer = self._get_layer_for_request()

        def security_cb(r, o):
            geom_attr = getattr(o, self._get_geom_col_info(layer)[0])
            allowed = DBSession.query(func.count(RestrictionArea.id))
            allowed = allowed.join(RestrictionArea.roles)
            allowed = allowed.join(RestrictionArea.layers)
            allowed = allowed.filter(RestrictionArea.readwrite.is_(True))
            allowed = allowed.filter(Role.id == self.request.user.role.id)
            allowed = allowed.filter(Layer.id == layer.id)
            allowed = allowed.filter(or_(
                RestrictionArea.area.is_(None),
                RestrictionArea.area.ST_Contains(geom_attr)
            ))
            if allowed.scalar() == 0:
                raise HTTPForbidden()

        protocol = self._get_protocol_for_layer(layer, before_delete=security_cb)
        return protocol.delete(self.request, feature_id)
Exemplo n.º 7
0
    def xapihelp(self):
        set_common_headers(self.request, "xapihelp", NO_CACHE)

        return {
            "lang": self.lang,
            "debug": self.debug,
        }
Exemplo n.º 8
0
    def delete(self):
        if self.request.user is None:
            raise HTTPForbidden()

        feature_id = self.request.matchdict.get("feature_id", None)
        layer = self._get_layer_for_request()

        def security_cb(r, o):
            geom_attr = getattr(o, self._get_geom_col_info(layer)[0])
            allowed = DBSession.query(func.count(RestrictionArea.id))
            allowed = allowed.join(RestrictionArea.roles)
            allowed = allowed.join(RestrictionArea.layers)
            allowed = allowed.filter(RestrictionArea.readwrite.is_(True))
            allowed = allowed.filter(Role.id == self.request.user.role.id)
            allowed = allowed.filter(Layer.id == layer.id)
            allowed = allowed.filter(or_(
                RestrictionArea.area.is_(None),
                RestrictionArea.area.ST_Contains(geom_attr)
            ))
            if allowed.scalar() == 0:
                raise HTTPForbidden()

        protocol = self._get_protocol_for_layer(layer, before_delete=security_cb)
        response = protocol.delete(self.request, feature_id)
        set_common_headers(
            self.request, "layers", NO_CACHE,
            response=response,
        )
        return response
Exemplo n.º 9
0
    def read_one(self):
        set_common_headers(self.request, "layers", NO_CACHE, add_cors=True)

        layer = self._get_layer_for_request()
        protocol = self._get_protocol_for_layer(layer)
        feature_id = self.request.matchdict.get("feature_id", None)
        feature = protocol.read(self.request, id=feature_id)
        if not isinstance(feature, Feature):
            return feature
        if layer.public:
            return feature
        if self.request.user is None:
            raise HTTPForbidden()
        geom = feature.geometry
        if not geom or isinstance(geom, geojson.geometry.Default):  # pragma: no cover
            return feature
        shape = asShape(geom)
        srid = self._get_geom_col_info(layer)[1]
        spatial_elt = from_shape(shape, srid=srid)
        allowed = DBSession.query(func.count(RestrictionArea.id))
        allowed = allowed.join(RestrictionArea.roles)
        allowed = allowed.join(RestrictionArea.layers)
        allowed = allowed.filter(Role.id == self.request.user.role.id)
        allowed = allowed.filter(Layer.id == layer.id)
        allowed = allowed.filter(or_(
            RestrictionArea.area.is_(None),
            RestrictionArea.area.ST_Contains(spatial_elt)
        ))
        if allowed.scalar() == 0:
            raise HTTPForbidden()

        return feature
Exemplo n.º 10
0
 def json(self):
     if self.valid_request:
         """answers to /profile.json"""
         layer, points = self._compute_points()
         set_common_headers(self.request, "profile", NO_CACHE)
         return {"profile": points}
     else:
         return {"profile": []}
Exemplo n.º 11
0
 def json(self):
     if self.valid_request:
         """answers to /profile.json"""
         layer, points = self._compute_points()
         set_common_headers(self.request, "profile", NO_CACHE)
         return {"profile": points}
     else:
         return {"profile": []}
Exemplo n.º 12
0
    def metadata(self):
        set_common_headers(self.request, "layers", PRIVATE_CACHE, add_cors=True)

        layer = self._get_layer_for_request()
        if not layer.public and self.request.user is None:
            raise HTTPForbidden()

        return self._metadata(str(layer.geo_table), layer.exclude_properties)
Exemplo n.º 13
0
    def get_ngeo_index_vars(self, vars={}):
        set_common_headers(self.request, "ngeo_index", NO_CACHE)

        vars.update({
            "debug": self.debug,
            "functionality": self._functionality(),
            "queryer_attribute_urls": self._get_layers_enum(),
        })
        return vars
Exemplo n.º 14
0
    def loginform403(self):
        if self.request.authenticated_userid:
            return HTTPForbidden()  # pragma: no cover

        set_common_headers(self.request, "loginform403", NO_CACHE)

        return {
            "lang": self.lang,
            "came_from": self.request.path,
        }
Exemplo n.º 15
0
    def read_many(self):
        set_common_headers(self.request, "layers", NO_CACHE, add_cors=True)

        features = []
        for layer in self._get_layers_for_request():
            for f in self._proto_read(layer).features:
                f.properties["__layer_id__"] = layer.id
                features.append(f)

        return FeatureCollection(features)
Exemplo n.º 16
0
    def read_many(self):
        set_common_headers(self.request, "layers", NO_CACHE)

        features = []
        for layer in self._get_layers_for_request():
            for f in self._proto_read(layer).features:
                f.properties["__layer_id__"] = layer.id
                features.append(f)

        return FeatureCollection(features)
Exemplo n.º 17
0
    def enumerate_attribute_values(self):
        set_common_headers(self.request, "layers", PUBLIC_CACHE)

        if self.layers_enum_config is None:  # pragma: no cover
            raise HTTPInternalServerError("Missing configuration")
        layername = self.request.matchdict["layer_name"]
        fieldname = self.request.matchdict["field_name"]
        # TODO check if layer is public or not

        return self._enumerate_attribute_values(layername, fieldname)
Exemplo n.º 18
0
 def __init__(self, request):
     self.request = request
     set_common_headers(request, "fulltextsearch", NO_CACHE)
     self.settings = request.registry.settings.get("fulltextsearch", {})
     if "languages" in self.settings:  # pragma: nocover
         self.languages = self.settings["languages"]
     else:
         self.languages = {
             "fr": "french",
             "en": "english",
             "de": "german",
         }
Exemplo n.º 19
0
    def get(self):
        ref = self.request.matchdict["ref"]
        short_urls = DBSession.query(Shorturl).filter(
            Shorturl.ref == ref).all()

        if len(short_urls) != 1:
            raise HTTPNotFound("Ref '%s' not found" % ref)

        short_urls[0].nb_hits += 1
        short_urls[0].last_hit = datetime.now()

        set_common_headers(self.request, "shortner", NO_CACHE)
        return HTTPFound(location=short_urls[0].url)
Exemplo n.º 20
0
    def enumerate_attribute_values(self):
        set_common_headers(self.request, "layers", PUBLIC_CACHE, add_cors=True)

        if self.layers_enum_config is None:  # pragma: no cover
            raise HTTPInternalServerError("Missing configuration")
        general_dbsession_name = self.layers_enum_config.get("dbsession", "dbsession")
        layername = self.request.matchdict["layer_name"]
        fieldname = self.request.matchdict["field_name"]
        # TODO check if layer is public or not

        return self._enumerate_attribute_values(
            general_dbsession_name, layername, fieldname
        )
Exemplo n.º 21
0
    def get(self):
        ref = self.request.matchdict["ref"]
        short_urls = DBSession.query(Shorturl).filter(Shorturl.ref == ref).all()

        if len(short_urls) != 1:
            raise HTTPNotFound("Ref '%s' not found" % ref)

        short_urls[0].nb_hits += 1
        short_urls[0].last_hit = datetime.now()

        set_common_headers(
            self.request, "shortner", NO_CACHE
        )
        return HTTPFound(location=short_urls[0].url)
Exemplo n.º 22
0
    def update(self):
        set_common_headers(self.request, "layers", NO_CACHE)

        if self.request.user is None:
            raise HTTPForbidden()

        self.request.response.cache_control.no_cache = True

        feature_id = self.request.matchdict.get("feature_id", None)
        layer = self._get_layer_for_request()

        def check_geometry(r, feature, o):
            # we need both the "original" and "new" geometry to be
            # within the restriction area
            geom_attr, srid = self._get_geom_col_info(layer)
            geom_attr = getattr(o, geom_attr)
            geom = feature.geometry
            allowed = DBSession.query(func.count(RestrictionArea.id))
            allowed = allowed.join(RestrictionArea.roles)
            allowed = allowed.join(RestrictionArea.layers)
            allowed = allowed.filter(RestrictionArea.readwrite.is_(True))
            allowed = allowed.filter(Role.id == self.request.user.role.id)
            allowed = allowed.filter(Layer.id == layer.id)
            allowed = allowed.filter(or_(
                RestrictionArea.area.is_(None),
                RestrictionArea.area.ST_Contains(geom_attr)
            ))
            spatial_elt = None
            if geom and not isinstance(geom, geojson.geometry.Default):
                shape = asShape(geom)
                spatial_elt = from_shape(shape, srid=srid)
                allowed = allowed.filter(or_(
                    RestrictionArea.area.is_(None),
                    RestrictionArea.area.ST_Contains(spatial_elt)
                ))
            if allowed.scalar() == 0:
                raise HTTPForbidden()

            # check is geometry is valid
            self._validate_geometry(spatial_elt)

        protocol = self._get_protocol_for_layer(layer, before_update=check_geometry)
        try:
            feature = protocol.update(self.request, feature_id)
            self._log_last_update(layer, feature)
            return feature
        except TopologicalError, e:
            self.request.response.status_int = 400
            return {"validation_error": str(e)}
Exemplo n.º 23
0
    def loginresetpassword(self):  # pragma: no cover
        set_common_headers(self.request, "loginresetpassword", NO_CACHE)

        user, username, password = self._loginresetpassword()
        settings = self.request.registry.settings["reset_password"]
        send_email(
            settings["email_from"], [user.email],
            settings["email_body"].format(user=username, password=password).encode("utf-8"),
            settings["email_subject"],
            settings["smtp_server"],
        )

        return {
            "success": True
        }
Exemplo n.º 24
0
    def _build_response(
        self, resp, content, cache_control, service_name, headers=None, headers_update=None, content_type=None
    ):
        if headers_update is None:
            headers_update = {}
        headers = dict(resp) if headers is None else headers

        # Hop-by-hop Headers are not supported by WSGI
        # See:
        # https://www.python.org/dev/peps/pep-3333/#other-http-features
        # chapter 13.5.1 at http://www.faqs.org/rfcs/rfc2616.html
        for header in [
            "connection",
            "keep-alive",
            "proxy-authenticate",
            "proxy-authorization",
            "te",
            "trailers",
            "transfer-encoding",
            "upgrade",
        ]:  # pragma: no cover
            if header in headers:
                del headers[header]
        # Other problematic headers
        for header in ["content-length", "content-location"]:  # pragma: no cover
            if header in headers:
                del headers[header]

        headers.update(headers_update)

        response = Response(content, status=resp.status, headers=headers)

        return set_common_headers(
            self.request, service_name, cache_control, response=response, content_type=content_type
        )
Exemplo n.º 25
0
    def csv(self):
        """answers to /profile.csv"""
        layers, points = self._compute_points()

        result = _("distance") + "," + ",".join(layers) + ",x,y"
        template = ",".join("%s" for l in layers)
        for point in points:
            # Handles cases when a layer is undefined, thus when not all raster
            # have the same geographical coverage
            for l in layers:
                if l not in point["values"]:
                    point["values"][l] = -9999

            r = template % tuple((str(point["values"][l]) for l in layers))
            result += "\n%s,%s,%d,%d" % (str(
                point["dist"]), r, point["x"], point["y"])

        return set_common_headers(self.request,
                                  "profile",
                                  NO_CACHE,
                                  response=Response(
                                      result,
                                      headers={
                                          "Content-Disposition":
                                          'attachment; filename="profile.csv"',
                                      }),
                                  content_type="text/csv; charset=utf-8",
                                  vary=True)
Exemplo n.º 26
0
def echo(request):
    csv = request.params.get("csv", None)
    if csv is None:
        return HTTPBadRequest("csv parameter is required")

    request.response.cache_control.no_cache = True

    csv_extension = request.params.get("csv_extension", DEFAULT_CSV_EXTENSION)
    csv_encoding = request.params.get("csv_encoding", DEFAULT_CSV_ENCODING)
    name = request.params.get("name", "export")

    response = request.response
    content = ""
    if csv_encoding == DEFAULT_CSV_ENCODING:
        content += codecs.BOM_UTF8
    content += csv.encode(csv_encoding)
    request.response.body = content
    response.charset = csv_encoding.encode(csv_encoding)
    response.content_disposition = "attachment; filename=%s.%s" % (
        name.replace(" ", "_"), csv_extension
    )
    return set_common_headers(
        request, "csvecho", NO_CACHE,
        content_type="text/csv"
    )
Exemplo n.º 27
0
def exportgpxkml(request):
    """
    View used to export a GPX or KML document.
    """

    fmt = request.params.get("format")
    if fmt is None:
        return HTTPBadRequest("format parameter is required")
    if fmt not in _CONTENT_TYPES:
        return HTTPBadRequest("format is not supported")

    name = request.params.get("name")
    if name is None:
        return HTTPBadRequest("name parameter is required")

    doc = request.params.get("doc")
    if doc is None:
        return HTTPBadRequest("doc parameter is required")

    charset = "utf-8"
    response = request.response
    response.body = doc.encode(charset)
    response.charset = charset
    response.content_disposition = ("attachment; filename={0!s}.{1!s}".format(name.replace(" ", "_"), fmt))
    return set_common_headers(
        request, "exportgpxkml", NO_CACHE,
        content_type=_CONTENT_TYPES[fmt]
    )
Exemplo n.º 28
0
    def _do_print(self, spec):
        """ Get created PDF. """
        url = self.config["print_url"] + "/print/buildreport.pdf"
        http = httplib2.Http()
        h = dict(self.request.headers)
        h["Content-Type"] = "application/json"
        if urlparse(url).hostname != "localhost":
            h.pop("Host")
        try:
            resp, content = http.request(
                url, method="POST", headers=h, body=dumps(spec)
            )
        except:
            return HTTPBadGateway()

        headers = {}
        if "content-disposition" in resp:
            headers["content-disposition"] = resp["content-disposition"]
        return set_common_headers(
            self.request, "pdfreport", NO_CACHE,
            response=Response(
                content, status=resp.status, headers=headers
            ),
            content_type=resp.get("content-type")
        )
Exemplo n.º 29
0
def exportcsv(request):
    csv = request.params.get("csv")
    if csv is None:
        return HTTPBadRequest("csv parameter is required")

    request.response.cache_control.no_cache = True

    csv_extension = request.params.get("csv_extension", DEFAULT_CSV_EXTENSION)
    csv_encoding = request.params.get("csv_encoding", DEFAULT_CSV_ENCODING)
    name = request.params.get("name", "export")

    response = request.response
    content = b""
    if csv_encoding == DEFAULT_CSV_ENCODING:
        content += codecs.BOM_UTF8
    content += csv.encode(csv_encoding)
    request.response.body = content
    response.charset = csv_encoding.encode(csv_encoding)
    response.content_disposition = "attachment; filename={0!s}.{1!s}".format(
        name.replace(" ", "_"), csv_extension
    )
    return set_common_headers(
        request, "csvecho", NO_CACHE,
        content_type="text/csv"
    )
Exemplo n.º 30
0
def exportgpxkml(request):
    """
    View used to export a GPX or KML document.
    """

    fmt = request.params.get("format")
    if fmt is None:
        return HTTPBadRequest("format parameter is required")
    if fmt not in _CONTENT_TYPES:
        return HTTPBadRequest("format is not supported")

    name = request.params.get("name")
    if name is None:
        return HTTPBadRequest("name parameter is required")

    doc = request.params.get("doc")
    if doc is None:
        return HTTPBadRequest("doc parameter is required")

    charset = "utf-8"
    response = request.response
    response.body = doc.encode(charset)
    response.charset = charset
    response.content_disposition = ("attachment; filename=%s.%s"
                                    % (name.replace(" ", "_"), fmt))
    return set_common_headers(
        request, "exportgpxkml", NO_CACHE,
        content_type=_CONTENT_TYPES[fmt]
    )
Exemplo n.º 31
0
    def themes(self):
        role_id = self.request.params.get("role_id", None)
        if role_id is None and self.request.user is not None:
            role_id = self.request.user.role.id
        elif self.request.client_addr != "127.0.0.1":
            role_id = None

        interface = self.request.params.get("interface", "main")
        sets = self.request.params.get("set", "all")
        version = int(self.request.params.get("version", 1))
        catalogue = self.request.params.get("catalogue", "false") == "true"
        min_levels = int(self.request.params.get("min_levels", 1))
        group = self.request.params.get("group", None)
        background_layers_group = self.request.params.get("background", None)

        export_themes = sets in ("all", "themes")
        export_group = group is not None and sets in ("all", "group")
        export_background = background_layers_group is not None and sets in ("all", "background")

        set_common_headers(self.request, "themes", PRIVATE_CACHE)

        result = {}
        all_errors = set()
        if export_themes:
            themes, errors = self._themes(
                role_id, interface, True, version, catalogue, min_levels
            )

            if version == 1:
                return themes

            result["themes"] = themes
            all_errors |= errors

        if export_group:
            group, errors = self._get_group(group, role_id, interface, version)
            result["group"] = group
            all_errors |= errors

        if export_background:
            group, errors = self._get_group(background_layers_group, role_id, interface, version)
            result["background_layers"] = group["children"]
            all_errors |= errors

        result["errors"] = list(all_errors)
        return result
Exemplo n.º 32
0
    def metadata(self):
        set_common_headers(self.request, "layers", PRIVATE_CACHE)

        layer = self._get_layer_for_request()
        if not layer.public and self.request.user is None:
            raise HTTPForbidden()

        # exclude the columns used to record the last features update
        exclude = [] if layer.exclude_properties is None else layer.exclude_properties.split(",")
        last_update_date = self._get_metadata(layer, "lastUpdateDateColumn")
        if last_update_date is not None:
            exclude.append(last_update_date)
        last_update_user = self._get_metadata(layer, "lastUpdateUserColumn")
        if last_update_user is not None:
            exclude.append(last_update_user)

        return self._metadata(layer.geo_table, exclude)
Exemplo n.º 33
0
def error_handler(http_exception, request):  # pragma: nocover
    """
    View callable for handling all the exceptions that are not already handled.
    """
    log.warning("%s returned status code %s", request.url,
                http_exception.status_code)
    return caching.set_common_headers(request, "error", caching.NO_CACHE,
                                      http_exception, vary=True, add_cors=True)
Exemplo n.º 34
0
    def get_cgxp_viewer_vars(self):
        role_id = None if self.request.user is None or self.request.user.role is None else \
            self.request.user.role.id

        interface = self.request.interface_name

        themes, errors = self._themes(role_id, interface)
        wfs_types, add_errors = self._internal_wfs_types(role_id)
        errors |= add_errors
        external_wfs_types, add_errors = self._external_wfs_types(role_id)
        errors |= add_errors
        external_themes, add_errors = self._external_themes(interface)
        errors |= add_errors

        version_role_params = {
            "cache_version": get_cache_version()
        }

        d = {
            "lang": self.lang,
            "debug": self.debug,
            "themes": json.dumps(themes),
            "user": self.request.user,
            "WFSTypes": json.dumps(wfs_types),
            "externalWFSTypes": json.dumps(external_wfs_types),
            "external_themes": external_themes,
            "tiles_url": json.dumps(self.settings.get("tiles_url")),
            "functionality": self._functionality(),
            "queryer_attribute_urls": json.dumps(self._get_layers_enum()),
            "serverError": json.dumps(list(errors)),
            "version_role_params": version_role_params
        }

        # handle permalink_themes
        permalink_themes = self.request.params.get("permalink_themes")
        if permalink_themes:
            d["permalink_themes"] = json.dumps(permalink_themes.split(","))

        set_common_headers(
            self.request, "cgxp_viewer", PRIVATE_CACHE,
            vary=True, content_type="application/javascript",
        )

        return d
Exemplo n.º 35
0
    def create(self):
        set_common_headers(self.request, "layers", NO_CACHE)

        if self.request.user is None:
            raise HTTPForbidden()

        self.request.response.cache_control.no_cache = True

        layer = self._get_layer_for_request()

        def check_geometry(r, feature, o):
            geom = feature.geometry
            if geom and not isinstance(geom, geojson.geometry.Default):
                shape = asShape(geom)
                srid = self._get_geom_col_info(layer)[1]
                spatial_elt = from_shape(shape, srid=srid)
                allowed = models.DBSession.query(func.count(
                    RestrictionArea.id))
                allowed = allowed.join(RestrictionArea.roles)
                allowed = allowed.join(RestrictionArea.layers)
                allowed = allowed.filter(RestrictionArea.readwrite.is_(True))
                allowed = allowed.filter(Role.id == self.request.user.role.id)
                allowed = allowed.filter(Layer.id == layer.id)
                allowed = allowed.filter(
                    or_(RestrictionArea.area.is_(None),
                        RestrictionArea.area.ST_Contains(spatial_elt)))
                if allowed.scalar() == 0:
                    raise HTTPForbidden()

                # check if geometry is valid
                if self._get_validation_setting(layer):
                    self._validate_geometry(spatial_elt)

        protocol = self._get_protocol_for_layer(layer,
                                                before_create=check_geometry)
        try:
            features = protocol.create(self.request)
            for feature in features.features:
                self._log_last_update(layer, feature)
            return features
        except TopologicalError as e:
            self.request.response.status_int = 400
            return {"validation_error": str(e)}
Exemplo n.º 36
0
    def raster(self):
        lon = float(self.request.params["lon"])
        lat = float(self.request.params["lat"])
        if "layers" in self.request.params:
            rasters = {}
            layers = self.request.params["layers"].split(",")
            for layer in layers:
                if layer in self.rasters:
                    rasters[layer] = self.rasters[layer]
                else:
                    raise HTTPNotFound("Layer %s not found" % layer)
        else:
            rasters = self.rasters

        result = {}
        for ref in rasters.keys():
            result[ref] = self._get_raster_value(rasters[ref], ref, lon, lat)

        set_common_headers(self.request, "raster", NO_CACHE)
        return result
Exemplo n.º 37
0
    def xapijs(self):
        wms, wms_errors = self._wms_getcap(
            self.mapserver_settings["mapserv_url"])
        queryable_layers = [
            name for name in list(wms.contents)
            if wms[name].queryable == 1]
        cache_version = self.settings.get("cache_version", None)

        set_common_headers(
            self.request, "xapijs", NO_CACHE,
            content_type="application/javascript",
        )

        return {
            "lang": self.lang,
            "debug": self.debug,
            "queryable_layers": json.dumps(queryable_layers),
            "url_params": {"cache_version": cache_version} if cache_version else {},
            "tiles_url": json.dumps(self.settings.get("tiles_url")),
        }
Exemplo n.º 38
0
def error_handler(http_exception, request):  # pragma: no cover
    """
    View callable for handling all the exceptions that are not already handled.
    """
    log.warning("%s returned status code %s", request.url,
                http_exception.status_code)
    return caching.set_common_headers(request,
                                      "error",
                                      caching.NO_CACHE,
                                      http_exception,
                                      vary=True)
Exemplo n.º 39
0
    def raster(self):
        lon = float(self.request.params["lon"])
        lat = float(self.request.params["lat"])
        if "layers" in self.request.params:
            rasters = {}
            layers = self.request.params["layers"].split(",")
            for layer in layers:
                if layer in self.rasters:
                    rasters[layer] = self.rasters[layer]
                else:
                    raise HTTPNotFound("Layer %s not found" % layer)
        else:
            rasters = self.rasters

        result = {}
        for ref in rasters.keys():
            result[ref] = self._get_raster_value(rasters[ref], ref, lon, lat)

        set_common_headers(self.request, "raster", NO_CACHE)
        return result
Exemplo n.º 40
0
    def create(self):
        set_common_headers(self.request, "layers", NO_CACHE)

        if self.request.user is None:
            raise HTTPForbidden()

        self.request.response.cache_control.no_cache = True

        layer = self._get_layer_for_request()

        def check_geometry(r, feature, o):
            geom = feature.geometry
            if geom and not isinstance(geom, geojson.geometry.Default):
                shape = asShape(geom)
                srid = self._get_geom_col_info(layer)[1]
                spatial_elt = from_shape(shape, srid=srid)
                allowed = DBSession.query(func.count(RestrictionArea.id))
                allowed = allowed.join(RestrictionArea.roles)
                allowed = allowed.join(RestrictionArea.layers)
                allowed = allowed.filter(RestrictionArea.readwrite.is_(True))
                allowed = allowed.filter(Role.id == self.request.user.role.id)
                allowed = allowed.filter(Layer.id == layer.id)
                allowed = allowed.filter(or_(
                    RestrictionArea.area.is_(None),
                    RestrictionArea.area.ST_Contains(spatial_elt)
                ))
                if allowed.scalar() == 0:
                    raise HTTPForbidden()

                # check if geometry is valid
                self._validate_geometry(spatial_elt)

        protocol = self._get_protocol_for_layer(layer, before_create=check_geometry)
        try:
            features = protocol.create(self.request)
            for feature in features.features:
                self._log_last_update(layer, feature)
            return features
        except TopologicalError, e:
            self.request.response.status_int = 400
            return {"validation_error": str(e)}
Exemplo n.º 41
0
    def get(self):
        """ Get created PDF. """

        resp, content = self._proxy("%s%s.printout" % (self.config["print_url"], self.request.matchdict.get("file")))

        headers = {}
        if "content-type" in resp:
            headers["content-type"] = resp["content-type"]
        if "content-disposition" in resp:
            headers["content-disposition"] = resp["content-disposition"]

        return set_common_headers(
            self.request, "print", NO_CACHE, response=Response(content, status=resp.status, headers=headers)
        )
Exemplo n.º 42
0
    def mobile(self):
        """
        View callable for the mobile application's index.html file.
        """
        set_common_headers(self.request, "sencha_index", NO_CACHE)

        extra_params = dict(self.request.params)
        came_from = self.request.current_route_url(_query=extra_params)
        cache_version = get_cache_version()
        url_params = {
            "cache_version": cache_version
        }
        extra_params["cache_version"] = cache_version
        if self.request.user is not None:
            extra_params["role"] = self.request.user.role.name

        def enc(vals):
            return (vals[0], vals[1].encode("utf8"))
        return {
            "lang": self.lang,
            "came_from": came_from,
            "url_params": urllib.urlencode(dict(map(enc, url_params.items()))),
            "extra_params": urllib.urlencode(dict(map(enc, extra_params.items()))),
        }
Exemplo n.º 43
0
    def get(self):
        """ Get created PDF. """

        resp, content = self._proxy("{0!s}{1!s}.printout".format(
            self.config["print_url"], self.request.matchdict.get("file")))

        headers = {}
        if "content-type" in resp:
            headers["content-type"] = resp["content-type"]
        if "content-disposition" in resp:
            headers["content-disposition"] = resp["content-disposition"]

        return set_common_headers(
            self.request,
            "print",
            NO_CACHE,
            response=Response(content, status=resp.status, headers=headers),
        )
Exemplo n.º 44
0
    def echo_csv(self):

        name = self.request.params.get("name")
        if name is None:
            return HTTPBadRequest("name parameter is required")

        csv = self.request.params.get("csv")
        if csv is None:
            return HTTPBadRequest("csv parameter is required")

        charset = "utf-8"
        response = self.request.response
        response.body = csv.encode(charset)
        response.charset = charset
        response.content_disposition = ("attachment; filename=%s.csv" %
                                        (name.replace(" ", "_")))
        return set_common_headers(self.request,
                                  "exportcsv",
                                  NO_CACHE,
                                  content_type="application/csv")
Exemplo n.º 45
0
    def _build_response(self,
                        resp,
                        content,
                        cache_control,
                        service_name,
                        headers=None,
                        headers_update=None,
                        content_type=None):
        if headers_update is None:
            headers_update = {}
        headers = dict(resp) if headers is None else headers

        # Hop-by-hop Headers are not supported by WSGI
        # See:
        # https://www.python.org/dev/peps/pep-3333/#other-http-features
        # chapter 13.5.1 at http://www.faqs.org/rfcs/rfc2616.html
        for header in [
                "connection", "keep-alive", "proxy-authenticate",
                "proxy-authorization", "te", "trailers", "transfer-encoding",
                "upgrade"
        ]:  # pragma: no cover
            if header in headers:
                del headers[header]
        # Other problematic headers
        for header in ["content-length",
                       "content-location"]:  # pragma: no cover
            if header in headers:
                del headers[header]

        headers.update(headers_update)

        response = Response(content, status=resp.status, headers=headers)

        return set_common_headers(
            self.request,
            service_name,
            cache_control,
            response=response,
            content_type=content_type,
        )
Exemplo n.º 46
0
def echo(request):
    """
    Echo an uploaded file back to the client as an text/html document so it can
    be handled by Ext.

    The response is JSON-wrapped and base64-encoded to ensure that there are no
    special HTML characters or charset problems and so that braindead ext
    doesn't barf on it.

    See:
    http://docs.sencha.com/ext-js/3-4/#!/api/Ext.form.BasicForm-cfg-fileUpload
    """
    try:
        file = request.POST["file"]
    except KeyError:
        return HTTPBadRequest()
    response = Response()
    response.app_iter = json_base64_encode(file.filename, file.file)
    return set_common_headers(
        request, "echo", NO_CACHE,
        response=response, content_type="text/html"
    )
Exemplo n.º 47
0
 def json(self):
     """answers to /profile.json"""
     _, points = self._compute_points()
     set_common_headers(self.request, "profile", NO_CACHE)
     return {"profile": points}
Exemplo n.º 48
0
    def count(self):
        set_common_headers(self.request, "layers", NO_CACHE)

        protocol = self._get_protocol_for_request()
        return protocol.count(self.request)
Exemplo n.º 49
0
    def create(self):

        if "url" not in self.request.params:
            raise HTTPBadRequest("The parameter url is required")

        url = self.request.params["url"]

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        hostname = uri_parts.hostname
        if "allowed_hosts" in self.settings:
            if hostname not in self.settings[
                    "allowed_hosts"]:  # pragma: no cover
                raise HTTPBadRequest("The requested host is not allowed.")
        else:
            if hostname != self.request.server_name:
                raise HTTPBadRequest("The requested host '%s' should be '%s'" %
                                     (hostname, self.request.server_name))

        shortened = False

        for base in self.short_bases:
            base_parts = urlparse(base)
            if uri_parts.path.startswith(base_parts.path):
                shortened = True
                ref = uri_parts.path.split("/")[-1]

        tries = 0
        while not shortened:
            ref = "".join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get("length", 4)))
            test_url = DBSession.query(Shorturl).filter(
                Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            tries += 1  # pragma: no cover
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to increase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get("email")
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        if "base_url" in self.settings:
            s_url = self.settings["base_url"] + ref
        else:
            s_url = self.request.route_url("shortener_get", ref=ref)

        if \
                email is not None and \
                "email_from" in self.settings and \
                "email_subject" in self.settings and \
                "email_body" in self.settings and \
                "smtp_server" in self.settings:  # pragma: no cover
            text = self.settings["email_body"] % {
                "full_url": url,
                "short_url": s_url,
                "message": self.request.params.get("message", ""),
            }
            send_email(
                self.settings["email_from"],
                [email],
                text.encode("utf-8"),
                self.settings["email_subject"],
                self.settings["smtp_server"],
            )

        set_common_headers(self.request, "shortner", NO_CACHE)
        return {"short_url": s_url}
Exemplo n.º 50
0
def other_error(exception, request):  # pragma: no cover
    set_common_headers(request, "index", NO_CACHE)
    return _do_error(request, 500, exception)
Exemplo n.º 51
0
 def __init__(self, request):
     self.request = request
     set_common_headers(request, "fulltextsearch", NO_CACHE)
     self.settings = request.registry.settings.get("fulltextsearch", {})
     self.languages = self.settings.get("languages", {})
Exemplo n.º 52
0
 def view(request):  # pragma: no cover
     from c2cgeoportal.lib.caching import set_common_headers, NO_CACHE
     return set_common_headers(request, service, NO_CACHE)