openstack_cli 0.13.5

OpenStack client rewritten in Rust
Documentation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
// WARNING: This file is automatically generated from OpenAPI schema using
// `openstack-codegenerator`.

//! Create User command
//!
//! Wraps invoking of the `v3/users` with `POST` method

use clap::Args;
use eyre::WrapErr;
use tracing::info;

use openstack_sdk::AsyncOpenStack;

use crate::Cli;
use crate::OpenStackCliError;
use crate::output::OutputProcessor;

use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::identity::v3::user::create;
use openstack_types::identity::v3::user::response::create::UserResponse;
use serde_json::Value;

/// Creates a user.
///
/// Relationship:
/// `https://docs.openstack.org/api/openstack-identity/3/rel/users`
#[derive(Args)]
#[command(about = "Create user")]
pub struct UserCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

    /// Path parameters
    #[command(flatten)]
    path: PathParameters,

    /// A `user` object
    #[command(flatten)]
    user: User,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {}

/// Path parameters
#[derive(Args)]
struct PathParameters {}
/// Options Body data
#[derive(Args, Clone)]
#[group(required = false, multiple = true)]
struct Options {
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    ignore_change_password_upon_first_use: Option<bool>,

    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    ignore_lockout_failure_attempts: Option<bool>,

    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    ignore_password_expiry: Option<bool>,

    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    ignore_user_inactivity: Option<bool>,

    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    lock_password: Option<bool>,

    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    multi_factor_auth_enabled: Option<bool>,

    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="[String] as JSON", value_parser=crate::common::parse_json)]
    multi_factor_auth_rules: Option<Vec<Vec<String>>>,
}

/// User Body data
#[derive(Args, Clone)]
struct User {
    /// The ID of the default project for the user. A user’s default project
    /// must not be a domain. Setting this attribute does not grant any actual
    /// authorization on the project, and is merely provided for convenience.
    /// Therefore, the referenced project does not need to exist within the
    /// user domain. (Since v3.1) If the user does not have authorization to
    /// their default project, the default project is ignored at token
    /// creation. (Since v3.1) Additionally, if your default project is not
    /// valid, a token is issued without an explicit scope of authorization.
    #[arg(help_heading = "Body parameters", long)]
    default_project_id: Option<String>,

    /// Set explicit NULL for the default_project_id
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "default_project_id")]
    no_default_project_id: bool,

    /// The description of the user resource.
    #[arg(help_heading = "Body parameters", long)]
    description: Option<String>,

    /// Set explicit NULL for the description
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "description")]
    no_description: bool,

    /// The ID of the domain of the user. If the domain ID is not provided in
    /// the request, the Identity service will attempt to pull the domain ID
    /// from the token used in the request. Note that this requires the use of
    /// a domain-scoped token.
    #[arg(help_heading = "Body parameters", long)]
    domain_id: Option<String>,

    /// If the user is enabled, this value is `true`. If the user is disabled,
    /// this value is `false`.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    enabled: Option<bool>,

    /// List of federated objects associated with a user. Each object in the
    /// list contains the `idp_id` and `protocols`. `protocols` is a list of
    /// objects, each of which contains `protocol_id` and `unique_id` of the
    /// protocol and user respectively. For example:
    ///
    /// ```text
    /// "federated": [
    ///   {
    ///     "idp_id": "efbab5a6acad4d108fec6c63d9609d83",
    ///     "protocols": [
    ///       {"protocol_id": mapped, "unique_id": "test@example.com"}
    ///     ]
    ///   }
    /// ]
    /// ```
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    federated: Option<Vec<Value>>,

    /// The user name. Must be unique within the owning domain.
    #[arg(help_heading = "Body parameters", long)]
    name: String,

    /// The resource options for the user. Available resource options are
    /// `ignore_change_password_upon_first_use`, `ignore_password_expiry`,
    /// `ignore_lockout_failure_attempts`, `lock_password`,
    /// `multi_factor_auth_enabled`, and `multi_factor_auth_rules`
    /// `ignore_user_inactivity`.
    #[command(flatten)]
    options: Option<Options>,

    /// The password for the user.
    #[arg(help_heading = "Body parameters", long)]
    password: Option<String>,

    /// Set explicit NULL for the password
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "password")]
    no_password: bool,
}

impl UserCommand {
    /// Perform command action
    pub async fn take_action(
        &self,
        parsed_args: &Cli,
        client: &mut AsyncOpenStack,
    ) -> Result<(), OpenStackCliError> {
        info!("Create User");

        let op = OutputProcessor::from_args(parsed_args, Some("identity.user"), Some("create"));
        op.validate_args(parsed_args)?;

        let mut ep_builder = create::Request::builder();

        // Set body parameters
        // Set Request.user data
        let args = &self.user;
        let mut user_builder = create::UserBuilder::default();
        if let Some(val) = &args.default_project_id {
            user_builder.default_project_id(Some(val.into()));
        } else if args.no_default_project_id {
            user_builder.default_project_id(None);
        }

        if let Some(val) = &args.description {
            user_builder.description(Some(val.into()));
        } else if args.no_description {
            user_builder.description(None);
        }

        if let Some(val) = &args.domain_id {
            user_builder.domain_id(val);
        }

        if let Some(val) = &args.enabled {
            user_builder.enabled(*val);
        }

        if let Some(val) = &args.federated {
            let federated_builder: Vec<create::Federated> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<create::Federated>(v.to_owned()))
                .collect::<Vec<create::Federated>>();
            user_builder.federated(federated_builder);
        }

        user_builder.name(&args.name);

        if let Some(val) = &args.options {
            let mut options_builder = create::OptionsBuilder::default();
            if let Some(val) = &val.ignore_change_password_upon_first_use {
                options_builder.ignore_change_password_upon_first_use(*val);
            }
            if let Some(val) = &val.ignore_lockout_failure_attempts {
                options_builder.ignore_lockout_failure_attempts(*val);
            }
            if let Some(val) = &val.ignore_password_expiry {
                options_builder.ignore_password_expiry(*val);
            }
            if let Some(val) = &val.ignore_user_inactivity {
                options_builder.ignore_user_inactivity(*val);
            }
            if let Some(val) = &val.lock_password {
                options_builder.lock_password(*val);
            }
            if let Some(val) = &val.multi_factor_auth_enabled {
                options_builder.multi_factor_auth_enabled(*val);
            }
            if let Some(val) = &val.multi_factor_auth_rules {
                options_builder.multi_factor_auth_rules(val.iter());
            }
            user_builder.options(
                options_builder
                    .build()
                    .wrap_err("error preparing the request data")?,
            );
        }

        if let Some(val) = &args.password {
            user_builder.password(Some(val.into()));
        } else if args.no_password {
            user_builder.password(None);
        }

        ep_builder.user(
            user_builder
                .build()
                .wrap_err("error preparing the request data")?,
        );

        let ep = ep_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;

        let data = ep.query_async(client).await?;
        op.output_single::<UserResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}