/*
* Box Platform API
*
* [Box Platform](https://box.dev) provides functionality to provide access to content stored within [Box](https://box.com). It provides endpoints for basic manipulation of files and folders, management of users within an enterprise, as well as more complex topics such as legal holds and retention policies.
*
* The version of the OpenAPI document: 2.0.0
* Contact: devrel@box.com
* Generated by: https://openapi-generator.tech
*/
//
use std::collections::HashMap;
use serde_json::json;
use super::models::post_users_request::PostUsersRequest;
use super::models::put_users_id_request::PutUsersIdRequest;
use super::models::user_full::UserFull;
use super::models::users::Users;
use crate::auth::AuthError;
use crate::box_client::BoxClient;
use crate::http_client::BaseHttpClient;
/// struct for passing parameters to the method [`list`]
#[derive(Clone, Debug, Default)]
pub struct ListUsersParams {
/// Limits the results to only users who's `name` or `login` start with the search term.
/// For externally managed users, the search term needs to completely match the in order to find the user, and it will only return one user at a time.
pub filter_term: Option<String>,
/// Limits the results to the kind of user specified. * `all` returns every kind of user for whom the `login` or `name` partially matches the `filter_term`. It will only return an external user if the login matches the `filter_term` completely, and in that case it will only return that user. * `managed` returns all managed and app users for whom the `login` or `name` partially matches the `filter_term`. * `external` returns all external users for whom the `login` matches the `filter_term` exactly.
pub user_type: Option<String>,
/// Limits the results to app users with the given `external_app_user_id` value. When creating an app user, an `external_app_user_id` value can be set. This value can then be used in this endpoint to find any users that match that `external_app_user_id` value.
pub external_app_user_id: Option<String>,
/// A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.
pub fields: Option<Vec<String>>,
/// The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response.
pub offset: Option<i64>,
/// The maximum number of items to return per page.
pub limit: Option<i64>,
/// Specifies whether to use marker-based pagination instead of offset-based pagination. Only one pagination method can be used at a time. By setting this value to true, the API will return a `marker` field that can be passed as a parameter to this endpoint to get the next page of the response.
pub usemarker: Option<bool>,
/// Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`.
pub marker: Option<String>,
}
/// Deletes a user.
/// By default this will fail if the user still owns any content.
/// Move their owned content first before proceeding, or use the `force` field to delete the user and their files.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let user_id = "12345";
/// users_api::delete(&mut client, &user_id, None, None).await?;
///
/// Ok(())
/// }
/// ```
pub async fn delete(
client: &mut BoxClient<'_>,
user_id: &str,
notify: Option<bool>,
force: Option<bool>,
) -> Result<(), AuthError> {
let uri = client.auth.base_api_url() + "/users" + format!("/{}", user_id).as_str();
let headers = client.headers().await?;
//TODO: these need to go in the query string
let value = serde_json::json!({
"notify": notify,
"force": force,
});
let resp = client.http.delete(&uri, Some(&headers), &value).await;
match resp {
Ok(_) => Ok(()),
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`.
/// The application and the authenticated user need to have the permission to look up users in the entire enterprise.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let result = users_api::list(&mut client, None).await?;
/// println!("Users:");
///
/// if let Some(users) = result.entries {
/// for user in users {
/// println!(
/// "{}\t{}\t{}\t{}",
/// user.id.unwrap(),
/// user.r#type.to_string(),
/// user.name.unwrap(),
/// user.login.unwrap(),
/// );
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub async fn list(
client: &mut BoxClient<'_>,
params: Option<ListUsersParams>,
) -> Result<Users, AuthError> {
let uri = client.auth.base_api_url() + "/users";
let headers = client.headers().await?;
let params = params.unwrap_or_default();
let filter_term = params.filter_term.unwrap_or_default();
let user_type = params.user_type.unwrap_or_default();
let external_app_user_id = params.external_app_user_id.unwrap_or_default();
let fields = params
.fields
.unwrap_or(vec![])
.into_iter()
.collect::<Vec<String>>()
.join(",")
.to_string();
let offset = params.offset.unwrap_or_default().to_string();
let limit = params.limit.unwrap_or_default().to_string();
let usemarker = params.usemarker.unwrap_or_default().to_string();
let marker = params.marker.unwrap_or_default().to_string();
let mut payload = HashMap::new();
if filter_term != String::default() {
payload.insert("filter_term", filter_term.as_str());
}
if user_type != String::default() {
payload.insert("user_type", user_type.as_str());
}
if external_app_user_id != String::default() {
payload.insert("external_app_user_id", external_app_user_id.as_str());
}
if fields != String::default() {
payload.insert("fields", fields.as_str());
}
if offset != "0" {
payload.insert("offset", offset.as_str());
}
if limit != "0" {
payload.insert("limit", limit.as_str());
}
if usemarker != String::default() {
payload.insert("usemarker", usemarker.as_str());
}
if marker != String::default() {
payload.insert("marker", marker.as_str());
}
let resp = client.http.get(&uri, Some(&headers), &payload).await;
match resp {
Ok(res) => {
let users = serde_json::from_str::<Users>(&res)?;
Ok(users)
}
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Retrieves information about a user in the enterprise.
/// The application and the authenticated user need to have the permission to look up users in the entire enterprise.
/// This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes.
/// In this case, disallowed fields will return null instead.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let user_id = "123";
///
/// let user = users_api::id(&mut client, &user_id, None).await?;
/// println!("User:{:#?}", user);
///
/// Ok(())
/// }
/// ```
pub async fn id(
client: &mut BoxClient<'_>,
user_id: &str,
fields: Option<Vec<String>>,
) -> Result<UserFull, AuthError> {
let uri = client.auth.base_api_url() + "/users" + format!("/{}", user_id).as_str();
let headers = client.headers().await?;
let fields = fields
.unwrap_or(vec![])
.into_iter()
.collect::<Vec<String>>()
.join(",")
.to_string();
let mut payload = HashMap::new();
payload.insert("fields", fields.as_str());
let resp = client.http.get(&uri, Some(&headers), &payload).await;
match resp {
Ok(res) => {
let user = serde_json::from_str::<UserFull>(&res)?;
Ok(user)
}
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Retrieves information about the user who is currently authenticated.
/// In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app.
/// In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default.
/// Use the `As-User` header to change who this API call is made on behalf of.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let me = users_api::me(&mut client, None).await?;
/// println!("Me:{:#?}", me);
///
/// Ok(())
/// }
/// ```
pub async fn me(
client: &mut BoxClient<'_>,
fields: Option<Vec<String>>,
) -> Result<UserFull, AuthError> {
let uri = client.auth.base_api_url() + "/users/me";
let headers = client.headers().await?;
let fields = fields
.unwrap_or(vec![])
.into_iter()
.collect::<Vec<String>>()
.join(",")
.to_string();
let mut payload = HashMap::new();
payload.insert("fields", fields.as_str());
let resp = client.http.get(&uri, Some(&headers), &payload).await;
match resp {
Ok(res) => {
let user = serde_json::from_str::<UserFull>(&res)?;
Ok(user)
}
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Creates a new managed user in an enterprise.
/// This endpoint is only available to users and applications with the right admin permissions.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// rest_api::users::models::post_users_request
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let new_user_request = post_users_request::PostUsersRequest {
/// name: "Test User".to_string(),
/// login: Some("test.user@gmail.local".to_string()),
/// is_platform_access_only: Some(false),
/// role: Some(post_users_request::Role::Coadmin),
/// language: Some("en".to_string()),
/// is_sync_enabled: Some(true),
/// job_title: Some("Test Job Title".to_string()),
/// phone: Some("555-555-5555".to_string()),
/// address: Some("123 Test St".to_string()),
/// space_amount: Some(1073741824),
/// // tracking_codes: Some(vec!["test-tracking-code".to_string()]),
/// can_see_managed_users: Some(true),
/// timezone: Some("America/Los_Angeles".to_string()),
/// is_external_collab_restricted: Some(false),
/// is_exempt_from_device_limits: Some(false),
/// is_exempt_from_login_verification: Some(false),
/// status: Some(post_users_request::Status::Active),
/// external_app_user_id: Some("test-external-app-user-id".to_string()),
/// ..Default::default()
/// };
///
/// let new_user = users_api::create(&mut client, None, new_user_request).await?;
/// println!("New User:{:#?}", new_user);
///
/// Ok(())
/// }
/// ```
pub async fn create(
client: &mut BoxClient<'_>,
fields: Option<Vec<String>>,
user: PostUsersRequest,
) -> Result<UserFull, AuthError> {
let uri = client.auth.base_api_url() + "/users";
let headers = client.headers().await?;
let fields = fields
.unwrap_or(vec![])
.into_iter()
.collect::<Vec<String>>()
.join(",")
.to_string();
let mut query = HashMap::new();
if !fields.is_empty() {
query.insert("fields", fields.as_str());
}
// convert the postusersrequest to json
let value_json = serde_json::to_string(&user)?;
let value = serde_json::from_str(&value_json)?;
let resp = client
.http
.post(&uri, Some(&headers), Some(&query), &value)
.await;
match resp {
Ok(res) => {
let user = serde_json::from_str::<UserFull>(&res)?;
Ok(user)
}
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Validates the roles and permissions of the user,
/// and creates asynchronous jobs to terminate the user's sessions.
/// Returns the status for the POST request.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let by_user_ids = users_api::terminate_sessions_by_user_ids(
/// &mut client,
/// vec!["123".to_string(), "456".to_string()],
/// )
/// .await?;
/// assert!(by_user_ids.is_some());
///
/// Ok(())
/// }
/// ```
pub async fn terminate_sessions_by_user_ids(
client: &mut BoxClient<'_>,
user_ids: Vec<String>,
) -> Result<Option<String>, AuthError> {
let uri = client.auth.base_api_url() + "/users/terminate_sessions";
let headers = client.headers().await?;
let mut value = HashMap::new();
value.insert("user_ids", user_ids);
let value = json!(value);
let resp = client.http.post(&uri, Some(&headers), None, &value).await;
match resp {
Ok(res) => Ok(Some(res)),
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Validates the roles and permissions of the user,
/// and creates asynchronous jobs to terminate the user's sessions.
/// Returns the status for the POST request.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
///
/// let by_user_logins = users_api::terminate_sessions_by_user_logins(
/// &mut client,
/// vec!["abc@gmail.local".to_string(), "def@gmail.local".to_string()],
/// )
/// .await?;
/// assert!(by_user_logins.is_some());
///
/// Ok(())
/// }
/// ```
pub async fn terminate_sessions_by_user_logins(
client: &mut BoxClient<'_>,
user_logins: Vec<String>,
) -> Result<Option<String>, AuthError> {
let uri = client.auth.base_api_url() + "/users/terminate_sessions";
let headers = client.headers().await?;
let mut value = HashMap::new();
value.insert("user_logins", user_logins);
let value = json!(value);
let resp = client.http.post(&uri, Some(&headers), None, &value).await;
match resp {
Ok(res) => Ok(Some(res)),
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Validates the roles and permissions of the user,
/// and creates asynchronous jobs to terminate the user's sessions.
/// Returns the status for the POST request.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let by_group_ids = users_api::terminate_sessions_by_group_ids(
/// &mut client,
/// vec!["123".to_string(), "456".to_string()],
/// )
/// .await?;
/// assert!(by_group_ids.is_some());
///
/// Ok(())
/// }
/// ```
pub async fn terminate_sessions_by_group_ids(
client: &mut BoxClient<'_>,
group_ids: Vec<String>,
// fields: Option<Vec<String>>,
) -> Result<Option<String>, AuthError> {
let uri = client.auth.base_api_url() + "/users/terminate_sessions";
let headers = client.headers().await?;
let mut value = HashMap::new();
value.insert("user_ids", group_ids);
let value = json!(value);
let resp = client.http.post(&uri, Some(&headers), None, &value).await;
match resp {
Ok(res) => Ok(Some(res)),
Err(e) => Err(AuthError::RequestError(e)),
}
}
/// Updates a managed or app user in an enterprise.
/// This endpoint is only available to users and applications with the right admin permissions.
///
/// Sample usage:
/// ```no_run
/// use rusty_box::{
/// auth::{
/// auth_developer::DevAuth,
/// AuthError,
/// },
/// box_client::BoxClient,
/// config::Config,
/// rest_api::users::users_api,
/// rest_api::users::models::put_users_id_request::PutUsersIdRequest
/// };
/// use dotenv;
/// use std::env;
/// #[tokio::main]
/// async fn main() -> Result<(), AuthError> {
///
/// dotenv::from_filename(".dev.env").ok();
/// let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
///
/// let config = Config::new();
/// let auth = DevAuth::new(
/// config,
/// access_token,
/// );
/// let mut client = BoxClient::new(Box::new(auth));
///
/// let user_id = "12345";
///
/// let user_updates = PutUsersIdRequest {
/// name: Some("Test User Updated".to_string()),
/// address: Some("456 Test St".to_string()),
/// ..Default::default()
/// };
///
/// let updated_user =
/// users_api::update(&mut client, &user_id, None, user_updates).await?;
/// println!("Updated User:{:#?}", updated_user);
///
/// Ok(())
/// }
/// ```
pub async fn update(
client: &mut BoxClient<'_>,
user_id: &str,
fields: Option<Vec<String>>,
user: PutUsersIdRequest,
) -> Result<UserFull, AuthError> {
let uri = client.auth.base_api_url() + "/users" + format!("/{}", user_id).as_str();
let headers = client.headers().await?;
let fields = fields
.unwrap_or(vec![])
.into_iter()
.collect::<Vec<String>>()
.join(",")
.to_string();
let mut query = HashMap::new();
if !fields.is_empty() {
query.insert("fields", fields.as_str());
}
// convert the postusersrequest to json
let value_json = serde_json::to_string(&user)?;
let value = serde_json::from_str(&value_json)?;
let resp = client
.http
.put(&uri, Some(&headers), Some(&query), &value)
.await;
match resp {
Ok(res) => {
let user = serde_json::from_str::<UserFull>(&res)?;
Ok(user)
}
Err(e) => Err(AuthError::RequestError(e)),
}
}