def _load_api_conf_directories(self):
        for key in self.folders:
            if not os.path.exists(self.folders[key]):
                raise GraviteeioError("Missing folder {}".format(self.folders[key]))

        root_template_file = None
        value_file = None
        
        if os.path.exists(self.files["value_file"]):
            value_file = self.files["value_file"]

        root_template_path_file = self.files["root_template_path_file"]
        for (data_format, extention) in ((data_format, extention) for data_format in Data_Template_Format for extention in data_format.extentions):
            if not root_template_file and os.path.exists(root_template_path_file.format(extention)):
                self.template_format = data_format
                root_template_file = environments.APIM_API_TEMPLATE_FILE.format(extention)

            file = self.files["value_file"].format(extention)
            if not value_file and os.path.exists(file):
                value_file_format = data_format
                value_file = file

            if root_template_file and value_file:
                break

        self.template = self._get_template(root_template_file, self.folders["templates_folder"])

        try:
            with open(value_file, 'r') as f:
                api_value_string = f.read()
        except OSError:
            raise GraviteeioError("Cannot open file {}".format(value_file))

        self.api_vars = {}
        self.api_vars["Values"] = value_file_format.load(api_value_string)

        settings_folder = self.folders["settings_folder"]
        # config_files = []

        for file in os.listdir(settings_folder):
            if not file.startswith(('_', ".")):
                try:
                    with open("/".join([settings_folder, file]), 'r') as f:
                        config_string = f.read()
                except OSError:
                    raise GraviteeioError("Cannot open {}".format(file))

                filename, file_extension = os.path.splitext(file)
                file_format = Data_Template_Format.find(file_extension)

                if file_format:
                    self.api_vars[filename] = file_format.load(config_string)

        self.loaded_schema = True
Example #2
0
def token(ctx, token, name):
    """
    Sign in with personal access token

    if token start with `env:` the token will retrieve from environment variable. i.e: `env:TOKEN`.
    """
    config: GraviteeioConfig_apim = ctx.obj['config'].getGraviteeioConfig(
        ctx.obj['module'])
    auth_client = ctx.obj['auth_client']

    if not click.get_text_stream('stdin').isatty():
        token = click.get_text_stream('stdin').read().strip()

    if not name:
        name = "-"
    # print(token)
    try:
        if config.is_logged_in():
            ctx.invoke(logout)
    except Exception:
        logger.exception("invoke logout")

    config.save_active_auth(name, Auth_Type.PERSONAL_ACCESS_TOKEN, token)

    try:
        auth_client.tokens()
        click.echo(
            "You are now logged with your personal token [{}].".format(name))
        click.echo("Your current profile is [{}]".format(
            ctx.obj['config'].profile))
    except Exception:
        config.remove_active_auth()
        raise GraviteeioError("No valid token.")
Example #3
0
    def get_api_data(self, debug, set_values):

        try:
            template = self.j2_env.get_template(
                environments.APIM_API_TEMPLATE_FILE)
        except TemplateNotFound:
            raise GraviteeioError("Template {} not found".format(
                environments.APIM_API_TEMPLATE_FILE))

        for set_value in set_values:
            self.api_value_data = utils.update_dic_with_set(
                set_value, self.api_value_data)

        api_data_yaml = template.render(api=self.api_value_data, config={})

        if debug:
            print("YAML:")
            print(api_data_yaml)

        api_data_dic = yaml.load(api_data_yaml, Loader=yaml.SafeLoader)

        if 'version' in api_data_dic:
            api_data_dic['version'] = str(api_data_dic['version'])

        return api_data_dic
    def _get_template(self, root_template_file, templates_folder):
        j2_env = Environment(loader=FileSystemLoader(templates_folder), trim_blocks=False, autoescape=False)
        filter_loader(j2_env)

        try:
            template = j2_env.get_template(root_template_file)
        except TemplateNotFound:
            raise GraviteeioError("Template not found, try to load {}".format(root_template_file))

        return template
Example #5
0
    def __init__(self, folder_path, value_file):
        self.j2_env = Environment(loader=FileSystemLoader(folder_path),
                                  trim_blocks=False)
        try:
            with open(value_file, 'r') as f:
                api_value_string = f.read()
        except FileNotFoundError:
            raise GraviteeioError("No such file {}".format(value_file))

        self.api_value_data = yaml.load(api_value_string,
                                        Loader=yaml.SafeLoader)
Example #6
0
def create(obj, user, auth_type):
    """Create a new authentication user"""
    config: GraviteeioConfig_apim = obj['config'].getGraviteeioConfig(
        GioModule.APIM)
    auth_list = config.get_auth_list()

    for auth in auth_list:
        if auth["username"] == user and auth_type.upper(
        ) == auth["type"].upper():
            raise GraviteeioError(
                "Username [{}] already exit for authentication type {}.".
                format(user, auth_type))

    auth_list.append({"username": user, "type": auth_type, "is_active": False})

    config.save(auth=auth_list)

    click.echo("User [{}] saved.".format(user))
Example #7
0
def diff(obj, api_id, file, set, config_path):
    """
    This commande compare the api definition configuration developed on local machine with the configuration on the remote server.
    """
    api_client: ApiClient = obj['api_client']

    if not config_path:
        config_path = "./"

    if not os.path.exists(config_path):
        raise GraviteeioError(
            "No resources folder {} found.".format(config_path))

    api_resolver = ApiConfigResolver(config_path, file)
    api_data = api_resolver.get_api_data(set_values=set)

    api_server = api_client.get_export(api_id, filter_api_values)

    diff_result = jsondiff(api_server, api_data)
    display_dict_differ(diff_result)
Example #8
0
def apply(obj, api_id, file, set, debug, config_path):
    """
    Allow to create/update an API from spec API like Swagger or OpenApiSpec (OAS)
    """
    api_client: ApiClient = obj['api_client']

    try:
        with open(file, 'r') as f:
            api_spec = f.read()
    except FileNotFoundError:
        raise GraviteeioError("Missing values file {}".format(file))

    if api_id:
        resp = api_client.update_oas(api_id, api_spec)
        click.echo("API {} is updated".format(api_id))
    else:
        click.echo("Start Create")
        resp = api_client.create_oas(api_spec)
        click.echo("API has been created with id {}".format(resp["id"]))

    pass
Example #9
0
def login(ctx, username, password):
    """
    Sign in with username/password
    """
    config: GraviteeioConfig_apim = ctx.obj['config'].getGraviteeioConfig(
        ctx.obj['module'])
    auth_client = ctx.obj['auth_client']

    if not click.get_text_stream('stdin').isatty():
        stdin_stream = click.get_text_stream('stdin').read().strip()

        if not username and not password:
            username_pwd = stdin_stream.split(":")
            if len(username_pwd) < 2:
                raise GraviteeioError(
                    "No username or password found. username and password have to split with ':' character"
                )
            else:
                username = username_pwd[0]
                password = username_pwd[1]
        else:
            password = stdin_stream

    bearer = auth_client.login(username, password)

    try:
        if config.is_logged_in():
            ctx.invoke(logout)
    except Exception:
        logger.exception("invoke logout")

    config.save_active_auth(username, Auth_Type.CREDENTIAL, bearer)

    click.echo("You are now logged in as [{}].".format(username))
    click.echo("Your current profile is [{}]".format(
        ctx.obj['config'].profile))