diff --git a/scp_udg_client_app/helpers.py b/scp_udg_client_app/helpers.py index 9caf8f115603d14816d129e5f4114488479f3a6d..13e40be82f528f04b4778be4db69ed778a9d0e63 100644 --- a/scp_udg_client_app/helpers.py +++ b/scp_udg_client_app/helpers.py @@ -1,3 +1,4 @@ +import json import logging import os import shutil @@ -6,6 +7,7 @@ from os import path from pathlib import Path from typing import Optional +import click import javaproperties from dateutil.parser import parse from scp_udg_client_rest import LoginRequest, Configuration, ApiClient, UrbanDatasetGatewayApi @@ -78,6 +80,7 @@ def move_file(src, dst): return new_dst + def read_properties_file(file_path): with open(file_path, 'r') as file: logger.debug(f'Reading config file {file_path}') @@ -123,14 +126,46 @@ def save_dataset(dataset, resource_id: str, destination_dir: str) -> None: file.write(dataset.to_json()) +def get_token(token, token_file, is_json): + """Determine the token from different sources.""" + if token: + logger.info("Reading token from command line argument") + elif token_file: + try: + logger.info(f"Reading token from file {token_file.name}") + if is_json or token_file.name.lower().endswith('.json'): + token_data = json.load(token_file) + token = token_data.get('token', None) + if not token: + raise click.ClickException("Token field missing in the JSON file.") + else: + token = token_file.read().strip() + except json.JSONDecodeError: + raise click.ClickException("Failed to decode JSON from the token file.") + except Exception as e: + raise click.ClickException(f"Error reading token from file: {str(e)}") + else: + token = None + return token + + def create_api_client_instance(udg_endpoint: str, access_token: Optional[str] = None) -> UrbanDatasetGatewayApi: configuration = Configuration(host=udg_endpoint, access_token=access_token) api_client = ApiClient(configuration) return UrbanDatasetGatewayApi(api_client) -def active_login(api_instance: UrbanDatasetGatewayApi, user_name: str, user_password: str) -> bool: - return is_api_alive(api_instance) or authenticate_user(api_instance, user_name, user_password) +def active_login(api_instance: UrbanDatasetGatewayApi, username: str, password: str) -> bool: + logger.info("Checking if the API is alive.") + api_alive = is_api_alive(api_instance) + if api_alive: + logger.info("API is alive; no need to authenticate user.") + return True + if not username or not password: + logger.warning("Username or password not set; cannot authenticate user.") + return False + logger.info(f"API is not alive; authenticating user '{username}'.") + return authenticate_user(api_instance, username, password) def count_files_recursively(folder_path: str) -> dict: