matroskin 0.1.0

whatsminer api client lib
Documentation
//! Implement `set.user.permission` command
//!
//! Sets the command permissions for a user account.
//! This command can only be executed by an account with super privileges.
//!
//! - Command: [SetUserPermission]
//! - ApiDoc: <https://apidoc.whatsminer.com/#api-User-user_set_permission>
use serde::Serialize;

use crate::{
    account::Users,
    command::{Command, CommandLevel},
    error::Result,
    permission::PermissionLevel,
};

/// This command represents the `set.user.permission` operation.
///
/// Sets the command permissions for a user account.
/// Only executable by an account with super privileges.
///
/// - ApiDoc: <https://apidoc.whatsminer.com/#api-User-user_set_permission>
///
/// # Example
/// ```rust,no_run
/// use matroskin::actor::Actor;
/// use matroskin::account::Account;
/// use matroskin::password::Password;
/// use matroskin::command::set_user_permission::SetUserPermission;
/// use matroskin::account::Users;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let addr = "10.10.10.10:4433";
///     let username = Account::Super;
///     let password = Password::Super;
///
///     let actor = Actor::new(addr, username, password);
///     actor.connect()?;
///
///     let cmd = SetUserPermission::new(Users::User1, "set.system.led,set.miner.pools");
///     let response = actor.send(cmd).await?;
///     println!("Response: {:#?}", response);
///
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct SetUserPermission {
    /// Target user account. Valid values: `user1`, `user2`, `user3`.
    pub user: Users,
    /// Comma-separated API command names granted to the target user.
    pub permission: String,
}

impl SetUserPermission {
    /// Set the command-list string specified by the device API.
    pub fn new(user: Users, permission: impl Into<String>) -> Self {
        Self {
            user,
            permission: permission.into(),
        }
    }
}

impl Command for SetUserPermission {
    type Response = String;
    const CMD_NAME: &'static str = "set.user.permission";
    const LEVEL: CommandLevel = CommandLevel::Secured;
    const MINIMAL_PERMISSIONS: PermissionLevel = PermissionLevel::All;

    fn params(&self) -> Result<Option<impl serde::Serialize>> {
        Ok(Some(self))
    }
}

#[cfg(test)]
mod tests {
    use crate::account::Account;
    use crate::auth_data::AuthData;

    use super::*;

    const RESPONSE_JSON: &str =
        r#"{"code":0,"when":1692685512,"msg":"ok","desc":"set.user.permission"}"#;

    #[test]
    fn request_has_correct_structure() {
        let cmd = SetUserPermission::new(Users::User1, "set.system.led,set.miner.pools");
        assert!(cmd.is_secured());
        assert!(!cmd.is_encrypted());

        let auth = AuthData::new::<SetUserPermission>(Account::Super, "pass", "salt").unwrap();
        let encoded = cmd.encode(Some(auth)).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();

        assert_eq!(json["cmd"], "set.user.permission");
        assert_eq!(json["account"], "super");
        assert!(json["ts"].as_u64().unwrap() > 0);
        assert_eq!(json["token"].as_str().unwrap().len(), 8);
        assert_eq!(json["param"]["user"], "user1");
        assert_eq!(
            json["param"]["permission"],
            "set.system.led,set.miner.pools"
        );
    }

    #[test]
    fn deserialize_response_fixture() {
        let response = SetUserPermission::parse_response(RESPONSE_JSON.as_bytes()).unwrap();
        assert!(response.code.is_success());
        assert_eq!(response.desc, "set.user.permission");
        assert_eq!(response.when, 1692685512);
        assert_eq!(response.msg, "ok");
    }
}