Esempio n. 1
0
def login(user):
    """Log the user into a deployment of Nexus."""
    config = config_utils.get_cli_config()
    c = config_utils.get_selected_deployment_config(config)
    if c is None:
        utils.error("You must select a deployment using `deployment --select` prior to running this command.")
    active_deployment_cfg = c[1]

    if user is None or user == '':
        user = input("Username:"******"Login successful"))
    if 'expires_in' in token:
        access_token = jwt.decode(token['access_token'], verify=False)
        expiry_utc = datetime.utcfromtimestamp(access_token['exp'])
        print("Token is valid for %s, expiry at %s" % (utils.print_time(token['expires_in']),
                                                       utils.datetime_from_utc_to_local(expiry_utc)))

    active_deployment_cfg['token'] = token
    active_deployment_cfg['userinfo'] = userinfo
    config_utils.save_cli_config(config)
Esempio n. 2
0
def schemas(list, organization, domain, public_only, download):
    """Manage Nexus schemas."""
    if list is not None:
        if organization is None:
            utils.error("You must select an organisation using --organization")
        if domain is None:
            utils.error("You must select an domain using --domain")

        c = config_utils.get_selected_deployment_config()
        if c is None:
            utils.error(
                "You must select a deployment using `deployment --select` prior to running this command."
            )
        active_deployment_cfg = c[1]

        url = active_deployment_cfg[
            'url'] + "/v0/schemas/" + organization + '/' + domain
        if public_only:
            print("Limiting results to publicly accessible records")
            authenticate = False
        else:
            authenticate = True
        data = nexus_utils.get_results_by_uri(url, authenticate=authenticate)
        total = data[1]
        results = data[0]

        columns = ["Schema name", "Version", "URL"]
        table = PrettyTable(columns)
        table.align[columns[0]] = "l"
        table.align[columns[1]] = "l"
        table.align[columns[2]] = "l"
        for item in results:
            schema_url = item['resultId']
            split = schema_url.rsplit("/", 2)
            schema_name = split[1]
            schema_version = split[2]
            table.add_row([schema_name, schema_version, schema_url])
        print(table)
        if len(results) == total:
            print(t.green('Total:' + str(total)))
        else:
            print(t.green('Total: %d of %d' % (str(len(results)), str(total))))
Esempio n. 3
0
def organizations(add, deprecate, list, public_only):
    """Manage Nexus organizations."""
    if list is not None:
        c = config_utils.get_selected_deployment_config()
        if c is None:
            utils.error(
                "You must select a deployment using `deployment --select` prior to running this command."
            )
        active_deployment_cfg = c[1]

        url = active_deployment_cfg['url'] + "/v0/organizations"
        if public_only:
            print("Limiting results to publicly accessible records")
            authenticate = False
        else:
            authenticate = True
        data = nexus_utils.get_results_by_uri(url, authenticate=authenticate)
        total = data[1]
        results = data[0]

        columns = ["Organization name", "URL"]
        table = PrettyTable(columns)
        table.align[columns[0]] = "l"
        table.align[columns[1]] = "l"
        for item in results:
            org_url = item['resultId']
            org_name = org_url.rsplit("/", 1)[1]
            table.add_row([org_name, org_url])
        print(table)
        if len(results) == total:
            print(t.green('Total:' + str(total)))
        else:
            print(t.green('Total: %d of %d' % (str(len(results)), str(total))))

    if add is not None:
        utils.error("--add not implemented yet")

    if deprecate is not None:
        utils.error("--deprecate not implemented yet")
Esempio n. 4
0
def tokens(decode):
    """Information about tokens."""
    deployment_name, config = config_utils.get_selected_deployment_config()
    print("Deployment: %s" % t.yellow(deployment_name))
    if 'token' not in config:
        print(t.red("You must first login to view your token."))
    else:
        exp_info = utils.print_time(get_token_remaining_time_valid_in_seconds())
        if is_access_token_valid():
            print(t.green("Token is valid (expiry in %s)" % exp_info))
        else:
            print(t.red("Token expired %s ago" % exp_info))

        tokens = config['token']
        if 'access_token' in tokens:
            print(t.yellow('\nAccess-Token:'))
            print_token(tokens['access_token'], decoded=decode)

        if 'id_token' in tokens:
            print(t.yellow('\nId-Token:'))
            print_token(tokens['id_token'], decoded=decode)

        if 'refresh_token' in tokens:
            print(t.yellow('\nRefresh-Token:'))
            print_token(tokens['refresh_token'], decoded=decode)

        userinfo = config['userinfo']
        print("\nUser:"******"\tId: %s" % userinfo['sub'])
        print("\tFamily name: %s" % userinfo['family_name'])
        print("\tGiven name: %s" % userinfo['given_name'])
        print("\tEmail: %s" % userinfo['email'])
        print("\tPreferred username: %s" % userinfo['preferred_username'])
        groups_ = userinfo['groups']
        print("\tGroups (%d):" % len(groups_))
        for g in groups_:
            print("\t\t"+g)
Esempio n. 5
0
def logout():
    """Logout from currently logged in deployment."""
    # click.echo("logout")
    config = config_utils.get_cli_config()
    deployment_name, selected_deployment_config = config_utils.get_selected_deployment_config(
        config)
    if selected_deployment_config is None:
        utils.error("You haven't selected a nexus deployment.")

    if 'token' not in selected_deployment_config:
        utils.error("You do not appear to have logged into " + deployment_name)

    # invalidate token with auth server
    auth_server = auth_utils.get_auth_server()
    refresh_token = selected_deployment_config['token']['refresh_token']
    auth_server.logout(refresh_token)

    # clear local auth data
    del (selected_deployment_config['token'])
    if 'userinfo' in selected_deployment_config:
        del (selected_deployment_config['userinfo'])
    config_utils.save_cli_config(config)

    print(t.green("Logout successful"))
Esempio n. 6
0
def acls(list_, organization, domain, public_only, show_raw):
    """Manage Nexus ACLs."""
    c = config_utils.get_selected_deployment_config()
    if c is None:
        utils.error(
            "You must select a deployment using `deployment --select` prior to running this command."
        )
    cfg_name = c[0]
    config = c[1]

    if list_ is True:
        column_name = 'Context (' + cfg_name + ')'
        table = PrettyTable([column_name])
        table.align[column_name] = "l"

        if public_only:
            print("Limiting results to publicly accessible records")
            authenticate = False
        else:
            authenticate = True

        data_url = config['url'] + '/v0/acls/kg/*/*?self=false&parents=true'
        data = nexus_utils.get_by_id(data_url, authenticate=authenticate)

        if show_raw:
            utils.print_json(data, colorize=True)

        acl = data['acl']
        acl_by_path = {}
        for e in acl:
            path = e['path']
            if path not in acl_by_path:
                acl_by_path[path] = []
            del (e['path'])

            values = list(filter(None, path.split('/')))
            skip = False
            if organization is not None:
                if len(values) < 2:
                    skip = True
                else:
                    if values[1] != organization:
                        skip = True

            if domain is not None:
                if len(values) < 3:
                    skip = True
                else:
                    if values[2] != domain:
                        skip = True

            if not skip:
                acl_by_path[path].append(e)

        for path in acl_by_path.keys():
            entries = acl_by_path[path]
            if len(entries) == 0:
                continue

            print(t.yellow(path))
            columns = ['Type', 'Realm', 'Identity', 'Permissions']
            table = PrettyTable(columns)
            table.align[columns[0]] = "l"
            table.align[columns[1]] = "l"
            table.align[columns[2]] = "l"
            table.align[columns[3]] = "l"

            for e in entries:
                identity = e['identity']
                permissions = e['permissions']
                permissions.sort()

                id_type = identity['@type']
                realm = ''
                if 'realm' in identity:
                    realm = identity['realm']
                id_name = None
                if id_type == 'UserRef':
                    id_name = identity['sub']
                elif id_type == 'GroupRef':
                    id_name = identity['group']
                elif id_type == 'Anonymous':
                    id_name = ''
                elif id_type == 'Authenticated':
                    id_name = ''
                else:
                    print(t.red(("Unsupported Identity Type: " + id_type)))

                perms = "\n".join(permissions)
                table.add_row([id_type, realm, id_name, perms])

            print(table)
            print()
Esempio n. 7
0
def contexts(list, public_only, no_format, search):
    """Manage Nexus contexts."""
    c = config_utils.get_selected_deployment_config()
    if c is None:
        utils.error(
            "You must select a deployment using `deployment --select` prior to running this command."
        )
    cfg_name = c[0]
    config = c[1]

    if list is True:
        column_name = 'Context (' + cfg_name + ')'
        table = PrettyTable(
            [column_name])  # TODO add "Revision", "Published", "Deprecated"
        table.align[column_name] = "l"

        if public_only:
            print("Limiting results to publicly accessible records")
            authenticate = False
        else:
            authenticate = True

        data_url = config['url'] + '/v0/contexts'
        data = nexus_utils.get_results_by_uri(data_url,
                                              authenticate=authenticate)
        total = data[1]
        results = data[0]

        for item in results:
            s = item['resultId']
            if no_format:
                print(s)
            else:
                table.add_row([s])

        if not no_format:
            print(table)
            print(t.green('Total:' + str(total)))

    if search is not None:
        if public_only:
            print("Limiting results to publicly accessible records")
            authenticate = False
        else:
            authenticate = True

        data_url = config['url'] + '/v0/contexts'
        data = nexus_utils.get_results_by_uri(data_url,
                                              authenticate=authenticate)
        results = data[0]

        for item in results:
            context_id = item['resultId']
            print("Getting " + context_id + " ...")
            context_json = nexus_utils.get_by_id(context_id,
                                                 authenticate=authenticate)
            if '@context' in context_json:
                for key in context_json['@context']:
                    if type(key) is str:
                        if search in key:
                            print(t.green(key))
                    elif type(key) is dict:
                        for k in key.keys():
                            if search in k:
                                print(t.green(k + ": " + str(key[k])))
            else:
                print("no @context found")
def search(query,
           fetch_entities=True,
           max_results=None,
           authenticate=True,
           verbose=False):
    """
    Execute provided search query and return resulting entities.

    :param query: a dict
    :param fetch_entities: bool
    :param max_results:
    :param authenticate:
    :param verbose:
    :return:
    """

    results = []

    headers = {}
    if authenticate:
        add_authorization_to_headers(headers)
    headers["Content-Type"] = "application/json"

    search_url = config_utils.get_selected_deployment_config(
    )[1]['url'] + "/v0/queries"

    r = None
    try:
        if verbose:
            print("Issuing POST: " + search_url)
            print("Query:")
            utils.print_json(query, colorize=True)
        r = requests.post(search_url,
                          data=json.dumps(query),
                          headers=headers,
                          allow_redirects=False)
    except Exception as e:
        utils.error("Failed: {0}".format(e))

    # expecting a redirect
    if 300 <= r.status_code < 400:
        location = r.headers['Location']
        if verbose:
            print("HTTP " + str(r.status_code) + " (" + r.reason + ")")
            print("Following redirect: " + location)

        # now get the results
        entities, total = get_results_by_uri(location, max_results=max_results)
        if verbose:
            print("Total: " + format(total, ',d'))
            print("Collected: " + format(len(entities), ',d'))

        if fetch_entities:
            for e in entities:
                payload = get_by_id(e['resultId'], verbose=verbose)
                results.append(payload)
        else:
            for e in entities:
                results.append(e['resultId'])

    return results