예제 #1
0
 def __call__(self, request):
     """Perform the actual authentication"""
     if self.where == "qs":
         parts = urlparse(request.url)
         qs = parse_qs(parts.query)
         qs[self.key] = self.token
         request.url = urlunparse((
             parts.scheme,
             parts.netloc,
             parts.path,
             parts.params,
             urlencode(qs),
             parts.fragment,
         ))
     elif self.where == "header":
         request.headers["Authorization"] = "Bearer {}".format(self.token)
     return request
예제 #2
0
 def exchange_code_for_token(self, authorized_url, state):
     """Get exchange code for token"""
     qs = parse_qs(urlparse(authorized_url).query)
     if qs["state"][0] != state:
         raise AuthenticationError(
             "The state received in the authorized url does not match initially computed state"
         )
     code = qs["code"][0]
     token_exchange_data = {
         "redirect_uri": self.config.redirect_uri,
         "client_id": self.config.client_id,
         "code": code,
         "state": state,
     }
     # If necessary, change the keys of the form data that will be passed to the token exchange POST request
     custom_token_exchange_params = getattr(self.config,
                                            "token_exchange_params", {})
     if custom_token_exchange_params:
         token_exchange_data[custom_token_exchange_params[
             "redirect_uri"]] = token_exchange_data.pop("redirect_uri")
         token_exchange_data[custom_token_exchange_params[
             "client_id"]] = token_exchange_data.pop("client_id")
     # If the client_secret is known, the token exchange request must be authenticated with a BASIC Auth, using the
     # client_id and client_secret as username and password respectively
     if getattr(self.config, "client_secret", None):
         token_exchange_data.update({
             "auth": (self.config.client_id, self.config.client_secret),
             "grant_type":
             "authorization_code",
             "client_secret":
             self.config.client_secret,
         })
     post_request_kwargs = {
         self.config.token_exchange_post_data_method: token_exchange_data
     }
     r = self.session.post(self.config.token_uri, **post_request_kwargs)
     return r.json()[self.config.token_key]
예제 #3
0
def search_crunch(ctx, **kwargs):
    """Search product types and optionnaly apply crunchers to search results"""
    # Process inputs for search
    product_type = kwargs.pop("producttype")
    instrument = kwargs.pop("instrument")
    platform = kwargs.pop("platform")
    platform_identifier = kwargs.pop("platformserialidentifier")
    processing_level = kwargs.pop("processinglevel")
    sensor_type = kwargs.pop("sensortype")
    id_ = kwargs.pop("id")
    custom = kwargs.pop("query")
    if not any([
            product_type,
            instrument,
            platform,
            platform_identifier,
            processing_level,
            sensor_type,
            id_,
    ]):
        with click.Context(search_crunch) as ctx:
            print("Give me some work to do. See below for how to do that:",
                  end="\n\n")
            click.echo(search_crunch.get_help(ctx))
        sys.exit(-1)

    kwargs["verbose"] = ctx.obj["verbosity"]
    setup_logging(**kwargs)

    if kwargs["box"] != (None, ) * 4:
        rect = kwargs.pop("box")
        footprint = {
            "lonmin": rect[0],
            "latmin": rect[1],
            "lonmax": rect[2],
            "latmax": rect[3],
        }
    else:
        footprint = kwargs.pop("geom")

    start_date = kwargs.pop("start")
    stop_date = kwargs.pop("end")
    criteria = {
        "geometry": footprint,
        "startTimeFromAscendingNode": None,
        "completionTimeFromAscendingNode": None,
        "cloudCover": kwargs.pop("cloudcover"),
        "productType": product_type,
        "instrument": instrument,
        "platform": platform,
        "platformSerialIdentifier": platform_identifier,
        "processingLevel": processing_level,
        "sensorType": sensor_type,
        "id": id_,
    }
    if custom:
        custom_dict = parse_qs(custom)
        for k, v in custom_dict.items():
            if isinstance(v, list) and len(v) == 1:
                criteria[k] = v[0]
            else:
                criteria[k] = v
    if start_date:
        criteria["startTimeFromAscendingNode"] = start_date.isoformat()
    if stop_date:
        criteria["completionTimeFromAscendingNode"] = stop_date.isoformat()
    conf_file = kwargs.pop("conf")
    if conf_file:
        conf_file = click.format_filename(conf_file)
    locs_file = kwargs.pop("locs")
    if locs_file:
        locs_file = click.format_filename(locs_file)

    # Process inputs for crunch
    cruncher_names = set(kwargs.pop("cruncher") or [])
    cruncher_args = kwargs.pop("cruncher_args")
    cruncher_args_dict = {}
    if cruncher_args:
        for cruncher, argname, argval in cruncher_args:
            cruncher_args_dict.setdefault(cruncher,
                                          {}).setdefault(argname, argval)

    items_per_page = kwargs.pop("items")
    page = kwargs.pop("page") or 1

    gateway = EODataAccessGateway(user_conf_file_path=conf_file,
                                  locations_conf_path=locs_file)

    # Search
    results, total = gateway.search(page=page,
                                    items_per_page=items_per_page,
                                    **criteria)
    click.echo("Found a total number of {} products".format(total))
    click.echo("Returned {} products".format(len(results)))

    # Crunch !
    crunch_args = {
        cruncher_name: cruncher_args_dict.get(cruncher_name, {})
        for cruncher_name in cruncher_names
    }
    if crunch_args:
        results = gateway.crunch(results,
                                 search_criteria=criteria,
                                 **crunch_args)

    storage_filepath = kwargs.pop("storage")
    if not storage_filepath.endswith(".geojson"):
        storage_filepath += ".geojson"
    result_storage = gateway.serialize(results, filename=storage_filepath)
    click.echo("Results stored at '{}'".format(result_storage))