Exemplo n.º 1
0
def add_user_to_group(user_name):
    groups = iam.list_groups()
    adding_groups = True
    added_groups = []
    group_list = []
    for group in groups.get('Groups'):
        group_names = group.get('GroupName')
        group_list.append(group_names)
    while adding_groups:
        group_cli = Bullet(prompt="\nPlease choose a group: ",
                           choices=group_list,
                           indent=0,
                           align=5,
                           margin=2,
                           shift=0,
                           bullet="",
                           pad_right=5)
        group_result = group_cli.launch()
        added_groups.append(group_result)
        user_group = iam.add_user_to_group(GroupName=group_result,
                                           UserName=user_name)
        group_list.remove(group_result)
        cli = YesNo("Would you like to add the user to another group? ")
        result = cli.launch()
        if not result:
            adding_groups = False

    return added_groups
Exemplo n.º 2
0
def programmatic_access(user_name):
    cli = YesNo("Would you like to allow programmatic access? ")
    result = cli.launch()
    if result:
        access = iam.create_access_key(UserName=user_name)
        access_key_id = access['AccessKey']['AccessKeyId']
        secret_access_key = access['AccessKey']['SecretAccessKey']
    else:
        access_key_id = None
        secret_access_key = None

    return access_key_id, secret_access_key
Exemplo n.º 3
0
def ensure_secrets_basedir(
    secrets_basedir=None,
    allow_create=False,
    allow_prompt=False,
    verbose_level=1,
):
    """
    Ensure that the secrets basedir exists.

    If the path is within the user's home directory, it is OK to
    create the directory automatically if it does not exist. This was
    the original behavior. If the path does exist and contains file,
    but does not have the special marker, that will be considered
    an error the user needs to resolve.

    For paths that lie outside the user's home directory, the user
    must explicitly confirm that it is OK to create the directory
    by responding to prompts (when possible) or by using the
    `--init` option flag or `psec init` command.
    """
    if secrets_basedir is None:
        secrets_basedir = get_default_secrets_basedir()
    homedir = str(Path.home())
    allow_create = (allow_create or str(secrets_basedir).startswith(homedir))
    try:
        is_secrets_basedir(basedir=secrets_basedir, raise_exception=True)
    except BasedirNotFoundError as err:
        if verbose_level > 0:
            logger.info(str(err))
        if not allow_create:
            if allow_prompt:
                client = YesNo(f"create directory '{secrets_basedir}'? ",
                               default='n')
                result = client.launch()
                if not result:
                    sys.exit("[!] cancelled creating '%s'", secrets_basedir)
            else:
                sys.exit("[-] add the '--init' flag or use 'psec init' "
                         "to initialize secrets storage")
        secrets_basedir_create(basedir=secrets_basedir)
        if verbose_level >= 1:
            logger.info("[+] initialized secrets storage in '%s'",
                        secrets_basedir)
    except InvalidBasedirError as err:
        sys.exit(str(err))
    # else:
    #     if verbose_level >= 1:
    #         logger.info(
    #             "[+] secrets storage already initialized in '%s'",
    #             secrets_basedir
    #         )
    return Path(secrets_basedir)
Exemplo n.º 4
0
def setup_experimental_flags(data):
    print_wrapped(
        _("EWS does not require any configuration, you only need to scan "
          "a QR code when you start up EH Forwarder Bot. It’s as simple as "
          "that.\n"
          "\n"
          "We has provided some experimental features that you can use. "
          "They are not required to be enabled for EWS to work. If you do not "
          "want to enable these feature, just press ENTER, and you are good to go."
          ))

    widget = YesNo(prompt=_("Do you want to config experimental features? "),
                   prompt_prefix="[yN] ")
    if not widget.launch(default="n"):
        return

    for key, value in flags_settings.items():
        default, cat, params, desc = value
        if data.data['flags'].get(key) is not None:
            default = data.data['flags'].get(key)
        print()
        print(key)
        print_wrapped(desc)
        if cat == 'bool':
            prompt_prefix = '[Yn] ' if default else '[yN] '
            ans = YesNo(prompt=f"{key}? ",
                        prompt_prefix=prompt_prefix) \
                .launch(default='y' if default else 'n')

            data.data['flags'][key] = ans
        elif cat == 'int':
            ans = Numbers(prompt=f"{key} [{default}]? ") \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'choices':
            ans = Bullet(prompt=f"{key}?", choices=params) \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'multiple':
            ans = Check(prompt=f"{key}?",
                        choices=params).launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'str':
            ans = input(f"{key} [{default}]: ")
            data.data['flags'][key] = ans or default
        else:
            print(_("Skipped."))

    print(_("Saving configurations..."), end="", flush=True)
    data.save()
    print(_("OK"))
def setup_experimental_flags(data):
    print()
    print_wrapped(
        _("EFMS has also provided some experimental features that you can use. "
          "They are not required to be enabled for EFMS to work."))

    widget = YesNo(prompt=_("Do you want to config experimental features? "),
                   prompt_prefix="[yN] ",
                   default="n")
    if not widget.launch():
        return

    for key, value in flags_settings.items():
        default, cat, params, desc = value
        if data.data['flags'].get(key) is not None:
            default = data.data['flags'].get(key)
        if cat == 'bool':
            prompt_prefix = '[Yn] ' if default else '[yN] '
            print()
            print(key)
            print_wrapped(desc)

            ans = YesNo(prompt=f"{key}? ",
                        prompt_prefix=prompt_prefix,
                        default='y' if default else 'n') \
                .launch()

            data.data['flags'][key] = ans
        elif cat == 'int':
            print()
            print(key)
            print_wrapped(desc)
            ans = Numbers(prompt=f"{key} [{default}]? ", type=int) \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'choices':
            print()
            print(key)
            print_wrapped(desc)
            ans = Bullet(prompt=f"{key}?", choices=params) \
                .launch(default=default)
            data.data['flags'][key] = ans

    print(_("Saving configurations..."), end="", flush=True)
    data.save()
    print(_("OK"))
def delete_application_versions(target_apps):
    num_apps = len(target_apps)
    keys = ['ApplicationName', 'VersionLabel']
    cli = YesNo(
        f"{num_apps} application versions will be deleted, would you like to proceed? "
    )
    result = cli.launch()
    if result:
        print("deleting apps...")
        for r in target_apps:
            p = [r.get(key) for key in keys]
            delete_app = eb.delete_application_version(ApplicationName=p[0],
                                                       VersionLabel=p[1],
                                                       DeleteSourceBundle=True)
            print(delete_app)
        print("Finished request")
    else:
        quit()
    return None
Exemplo n.º 7
0
def setup_experimental_flags(data):
    print()
    widget = YesNo(prompt=_("Do you want to config experimental features? "),
                   prompt_prefix="[yN] ", default="n")
    if not widget.launch():
        return

    for key, value in flags_settings.items():
        default, cat, params, desc = value
        if data.data['flags'].get(key) is not None:
            default = data.data['flags'].get(key)
        if cat == 'bool':
            prompt_prefix = '[Yn] ' if default else '[yN] '
            print()
            print(key)
            print_wrapped(desc)

            ans = YesNo(prompt=f"{key}? ",
                        default='y' if default else 'n',
                        prompt_prefix=prompt_prefix) \
                .launch()

            data.data['flags'][key] = ans
        elif cat == 'int':
            print()
            print(key)
            print_wrapped(desc)
            ans = Numbers(prompt=f"{key} [{default}]? ", type=int) \
                .launch(default=default)
            data.data['flags'][key] = ans
        elif cat == 'choices':
            try:
                assert isinstance(params, list)
                default = params.index(default)
            except ValueError:
                default = 0
            print()
            print(key)
            print_wrapped(desc)
            ans = Bullet(prompt=f"{key}?", choices=params) \
                .launch(default=default)
            data.data['flags'][key] = ans
Exemplo n.º 8
0
def gif_path_option(image_filepath):
    path = Path(image_filepath)
    default_choice = YesNo(
        # Prompt for the user to see
        prompt="Do you want to use the default folder {0} ? ".format(
            path.parent), )
    default = default_choice.launch()

    if default:
        return str(path.parent)
    else:
        while True:
            folder_choices = Input(
                # Prompt for the user to see
                prompt="What is the folder you want to use for the ASCII gif? ",
                strip=True)

            menu = folder_choices.launch()
            if os.path.exists(menu):
                return menu
            else:
                msg = f'Error: The folder \'{menu}\' doesnt seem to exists'
                print(color.error(msg))
Exemplo n.º 9
0
from bullet import YesNo

client = YesNo("Are you a good student? ", default='y')

res = client.launch()
print(res)
Exemplo n.º 10
0
 details, plp = playlist_prompt(channels[channel])
 clear()
 title = plp.launch()
 while title in ["[Next Page]", "[Previous Page]"]:
     page = details.next_page if title == "[Next Page]" else details.prev_page
     details, plp = playlist_prompt(channels[channel], page)
     clear()
     title = plp.launch()
 playlist = [pl for pl in details.items if pl.title == title][0]
 fp = Input(f"Enter a folder name ({playlist.title}): ",
            default=playlist.title)
 f_folder = fp.launch()
 addp = YesNo(prompt="Add this playlist to be monitored? (y/N)",
              default="N",
              prompt_prefix="")
 should_monitor = addp.launch()
 if should_monitor:
     regp = Input(
         prompt="What should the regex be for the videos in this playlist?\n"
     )
     reg = regp.launch()
     cfg_path = os.path.join(yt_utils.BASE_SHARE, "channels.json")
     with open(cfg_path, "r") as inf:
         current_cfg = json.load(fp=inf)
     for i in range(len(current_cfg)):
         if current_cfg[i]["name"] != channel:
             continue
         current_cfg[i]["series_to_check"].append({
             "folder": f_folder,
             "title_format": reg
         })
Exemplo n.º 11
0
 def take_action(self, parsed_args):
     self.LOG.debug('[*] creating secrets')
     # Does an environment already exist?
     if not stdin.isatty():
         raise RuntimeError(
             '[-] this command only works when a TTY is available')
     se = self.app.secrets
     env = se.environment
     if not se.environment_exists():
         if parsed_args.update:
             raise RuntimeError(f"[!] environment '{env}' does not exist'")
         client = YesNo(f"create environment '{env}'? ", default='n')
         res = client.launch()
         if not res:
             self.LOG.info('[!] cancelled creating environment')
             return 1
         se.environment_create()
         self.LOG.info(f"[+] environment '{env}' "
                       f"({se.environment_path()}) created")
     if parsed_args.update and len(parsed_args.arg) > 1:
         # TODO(dittrich): Refactor to loop over parsed_arg.arg
         # from here (not farther down).
         raise RuntimeError(
             "[!] only one variable can be updated at a time")
     se.read_secrets_and_descriptions()
     groups = se.get_groups()
     group = parsed_args.group
     if group is None:
         if not parsed_args.update:
             # Default group to same name as environment identifier
             group = env
         else:
             group = se.get_group(parsed_args.arg[0])
     if group not in groups:
         if parsed_args.update:
             raise RuntimeError(f"[!] group '{group}' does not exist'")
         client = YesNo(f"create new group '{group}'? ", default='n')
         res = client.launch()
         if not res:
             self.LOG.info('[!] cancelled creating group')
             return 1
         descriptions = list()
         variables = list()
     else:
         descriptions = se.read_descriptions(group=group)
         variables = [item['Variable'] for item in descriptions]
     args = parsed_args.arg
     changed = False
     for arg in args:
         arg_row = find(descriptions, 'Variable', arg)
         if parsed_args.update:
             if arg not in variables:
                 self.LOG.info(
                     f"[-] can't update nonexistent variable '{arg}'")
                 continue
             self.LOG.info(
                 f"[+] updating variable '{arg}' in group '{group}'")
             new_description = get_description(
                 name=arg, defaults=descriptions[arg_row])
         else:
             if arg in variables:
                 self.LOG.info(f"[-] variable '{arg}' already exists")
                 continue
             self.LOG.info(
                 f"[+] creating variable '{arg}' in group '{group}'")
             new_description = get_description(name=arg,
                                               defaults={
                                                   'Variable': arg,
                                                   'Prompt':
                                                   f"Value for '{arg}'",
                                                   'Options': "*",
                                                   'Export': " ",
                                               })
         if len(new_description):
             table = PrettyTable()
             table.field_names = ('Key', 'Value')
             table.align = 'l'
             for k, v in new_description.items():
                 table.add_row((k, v))
             print(table)
             client = YesNo("commit this description? ", default='n')
             res = client.launch()
             if not res:
                 continue
             if arg_row is not None:
                 descriptions[arg_row] = new_description
             else:
                 descriptions.append(new_description)
                 se.set_secret(arg)
             changed = True
     if changed:
         se.write_descriptions(
             data=descriptions,
             group=group,
             mirror_to=os.getcwd() if parsed_args.mirror_locally else None)