예제 #1
0
파일: auth.py 프로젝트: zviri/prefect
def login(token):
    """
    Log in to Prefect Cloud with an api token to use for Cloud communication.

    \b
    Options:
        --token, -t         TEXT    A Prefect Cloud api token  [required]
    """
    check_override_auth_token()

    client = Client(api_token=token)

    # Verify login obtained a valid api token
    try:
        output = client.graphql(
            query={"query": {
                "user": {
                    "default_membership": "tenant_id"
                }
            }})

        # Log into default membership
        success_login = client.login_to_tenant(
            tenant_id=output.data.user[0].default_membership.tenant_id)

        if not success_login:
            raise AuthorizationError

    except AuthorizationError:
        click.secho(
            f"Error attempting to use Prefect API token {token}. "
            "Please check that you are providing a USER scoped Personal Access Token.\n"
            "For more information visit the documentation for USER tokens at "
            "https://docs.prefect.io/orchestration/concepts/tokens.html#user",
            fg="red",
        )
        return
    except ClientError:
        click.secho(
            "Error attempting to communicate with Prefect Cloud. "
            "Please check that you are providing a USER scoped Personal Access Token.\n"
            "For more information visit the documentation for USER tokens at "
            "https://docs.prefect.io/orchestration/concepts/tokens.html#user",
            fg="red",
        )
        return

    # save token
    client.save_api_token()

    click.secho("Login successful!", fg="green")
예제 #2
0
def switch_tenants(id, slug, default):
    """
    Switch active tenant

    \b
    Options:
        --id, -i    TEXT    A Prefect Cloud tenant id
        --slug, -s  TEXT    A Prefect Cloud tenant slug
    """

    # If the config specifies a tenant explicitly, it is used before this mechanism
    if config.cloud.get("tenant_id"):
        raise TerminalError(
            "Your tenant id has been set in the Prefect config instead of with the "
            "CLI. To switch tenants with the CLI, remove the config key "
            " `prefect.cloud.tenant_id`")

    client = Client()

    # Deprecated API token check
    if not client.api_key:
        check_override_auth_token()

        if default:
            raise TerminalError(
                "The default tenant flag can only be used with API keys.")

    else:  # Using an API key
        if default:
            # Clear the set tenant on disk
            client.tenant_id = None
            client.save_auth_to_disk()
            click.secho(
                "Tenant restored to the default tenant for your API key: "
                f"{client.get_default_tenant()}",
                fg="green",
            )
            return

    login_success = client.login_to_tenant(tenant_slug=slug, tenant_id=id)
    if not login_success:
        raise TerminalError("Unable to switch tenant!")

    # `login_to_tenant` will write to disk if using an API token, if using an API key
    # we will write to disk manually here
    if client.api_key:
        client.save_auth_to_disk()

    click.secho(f"Tenant switched to {client.tenant_id}", fg="green")
예제 #3
0
파일: auth.py 프로젝트: zpencerq/prefect
def switch_tenants(id, slug):
    """
    Switch active tenant

    \b
    Options:
        --id, -i    TEXT    A Prefect Cloud tenant id
        --slug, -s  TEXT    A Prefect Cloud tenant slug
    """
    check_override_auth_token()

    client = Client()

    login_success = client.login_to_tenant(tenant_slug=slug, tenant_id=id)
    if not login_success:
        click.secho("Unable to switch tenant", fg="red")
        return

    click.secho("Tenant switched", fg="green")
예제 #4
0
def login(token):
    """
    Log in to Prefect Cloud with an api token to use for Cloud communication.

    \b
    Options:
        --token, -t         TEXT    A Prefect Cloud api token  [required]
    """
    check_override_auth_token()

    client = Client(api_token=token)

    # Verify login obtained a valid api token
    try:
        output = client.graphql(
            query={"query": {
                "user": {
                    "default_membership": "tenant_id"
                }
            }})

        # Log into default membership
        success_login = client.login_to_tenant(
            tenant_id=output.data.user[0].default_membership.tenant_id)

        if not success_login:
            raise AuthorizationError

    except AuthorizationError:
        click.secho(
            "Error attempting to use Prefect API token {}".format(token),
            fg="red")
        return
    except ClientError:
        click.secho("Error attempting to communicate with Prefect Cloud",
                    fg="red")
        return

    # save token
    client.save_api_token()

    click.secho("Login successful!", fg="green")
예제 #5
0
def login(key, token):
    """
    Login to Prefect Cloud

    Create an API key in the UI then login with it here:

        $ prefect auth login -k YOUR-KEY

    You will be switched to the default tenant associated with the key. After login,
    your available tenants can be seen with `prefect auth list-tenants` and you can
    change the default tenant on this machine using `prefect auth switch-tenants`.

    The given key will be stored on disk for later access. Prefect will default to using
    this key for all interaction with the API but frequently overrides can be passed to
    individual commands or functions. To remove your key from disk, see
    `prefect auth logout`.

    This command has backwards compatibility support for API tokens, which are a
    deprecated form of authentication with Prefect Cloud
    """
    if not key and not token:
        raise TerminalError("You must supply an API key or token!")

    if key and token:
        raise TerminalError("You cannot supply both an API key and token")

    abort_on_config_api_key(
        "To log in with the CLI, remove the config key `prefect.cloud.api_key`"
    )

    # Attempt to treat the input like an API key even if it is passed as a token
    client = Client(api_key=key or token)

    try:
        default_tenant = client.get_default_tenant()
    except AuthorizationError:
        if key:  # We'll catch an error again later if using a token
            raise TerminalError("Unauthorized. Invalid Prefect Cloud API key.")
    except ClientError:
        raise TerminalError(
            "Error attempting to communicate with Prefect Cloud.")
    else:
        if not default_tenant and key:
            raise TerminalError(
                "Failed to find a tenant associated with the given API key!")

        elif default_tenant:  # Successful login
            if token:
                click.secho(
                    "WARNING: You logged in with an API key using the `--token` flag "
                    "which is deprecated. Please use `--key` instead.",
                    fg="yellow",
                )
            client.save_auth_to_disk()
            click.secho("Login successful!", fg="green")
            return

        # If there's not a tenant id, we've been given an actual token, fallthrough to
        # the backwards compatibility token auth

    # Backwards compatibility for tokens
    if token:
        check_override_auth_token()
        client = Client(api_token=token)

        # Verify they're not also using an API key
        if client.api_key:
            raise TerminalError(
                "You have already logged in with an API key and cannot use a token."
            )

        click.secho(
            "WARNING: API tokens are deprecated. Please create an API key and use "
            "`prefect auth login --key <KEY>` to login instead.",
            fg="yellow",
        )

        # Verify login obtained a valid api token
        try:
            output = client.graphql(
                query={"query": {
                    "user": {
                        "default_membership": "tenant_id"
                    }
                }})

            # Log into default membership
            success_login = client.login_to_tenant(
                tenant_id=output.data.user[0].default_membership.tenant_id)

            if not success_login:
                raise AuthorizationError

        except AuthorizationError:
            click.secho(
                "Error attempting to use the given API token. "
                "Please check that you are providing a USER scoped Personal Access Token.\n"
                "For more information visit the documentation for USER tokens at "
                "https://docs.prefect.io/orchestration/concepts/tokens.html#user",
                fg="red",
            )
            return
        except ClientError:
            click.secho(
                "Error attempting to communicate with Prefect Cloud. "
                "Please check that you are providing a USER scoped Personal Access Token.\n"
                "For more information visit the documentation for USER tokens at "
                "https://docs.prefect.io/orchestration/concepts/tokens.html#user",
                fg="red",
            )
            return

        # save token
        client.save_api_token()

        click.secho("Login successful!", fg="green")
예제 #6
0
def start_client():
    client = Client()
    client.login_to_tenant(tenant_slug="default")
def change_prev_flow_state(number, secret):
    logger = prefect.context.get("logger")
    prev_random_number = prefect.context.get("prev_random_number")
    prev_flow_run_id = prefect.context.get("prev_flow_run_id")

    logger.info(f"The number retrieved from Context was: {prev_random_number}")
    logger.info(f"The number submitted to this Task was: {number}")

    client = Client(api_token=secret)
    client.login_to_tenant(tenant_slug="kmw-cloud")

    if number is None:
        logger.info("Outcome: Your number was None")
        pass
    elif number < 50:
        logger.info(f"Outcome: Your number was {number}, which is < 50")
        pass
    elif number < 70:
        set_flow_run_state = client.graphql(query="""
                mutation SetFlowRunStates($flowRunId: UUID!, $state: JSON!) {
                    set_flow_run_states(
                        input: {
                        states: [{ flow_run_id: $flowRunId, state: $state }]
                        }
                    ) {
                        states {
                        id
                        status
                        message
                        }
                    }
                }
            """,
                                            variables={
                                                "flowRunId": prev_flow_run_id,
                                                "state": {
                                                    "type": "Cancelled"
                                                }
                                            })
    elif number < 90:
        set_flow_run_state = client.graphql(query="""
                mutation SetFlowRunStates($flowRunId: UUID!, $state: JSON!) {
                    set_flow_run_states(
                        input: {
                        states: [{ flow_run_id: $flowRunId, state: $state }]
                        }
                    ) {
                        states {
                        id
                        status
                        message
                        }
                    }
                }
            """,
                                            variables={
                                                "flowRunId": prev_flow_run_id,
                                                "state": {
                                                    "type": "Finished"
                                                }
                                            })
    else:
        set_flow_run_state = client.graphql(query="""
                mutation SetFlowRunStates($flowRunId: UUID!, $state: JSON!) {
                    set_flow_run_states(
                        input: {
                        states: [{ flow_run_id: $flowRunId, state: $state }]
                        }
                    ) {
                        states {
                        id
                        status
                        message
                        }
                    }
                }
            """,
                                            variables={
                                                "flowRunId": prev_flow_run_id,
                                                "state": {
                                                    "type": "Skipped"
                                                }
                                            })