rusty_box/rest_api/users/
users_api.rs

1/*
2 * Box Platform API
3 *
4 * [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.
5 *
6 * The version of the OpenAPI document: 2.0.0
7 * Contact: devrel@box.com
8 * Generated by: https://openapi-generator.tech
9 */
10//
11
12use std::collections::HashMap;
13
14use serde_json::json;
15
16use super::models::post_users_request::PostUsersRequest;
17use super::models::put_users_id_request::PutUsersIdRequest;
18use super::models::user_full::UserFull;
19use super::models::users::Users;
20
21use crate::client::box_client::BoxClient;
22use crate::client::client_error::BoxAPIError;
23
24pub enum UsersError {
25    DefaultResponse(BoxAPIError),
26    UnknownValue(serde_json::Value),
27}
28
29/// struct for passing parameters to the method [`list`]
30#[derive(Clone, Debug, Default)]
31pub struct ListUsersParams {
32    /// Limits the results to only users who's `name` or `login` start with the search term.  
33    /// 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.
34    pub filter_term: Option<String>,
35    /// 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.
36    pub user_type: Option<String>,
37    /// 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.
38    pub external_app_user_id: Option<String>,
39    /// 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.
40    pub fields: Option<Vec<String>>,
41    /// 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.
42    pub offset: Option<i64>,
43    /// The maximum number of items to return per page.
44    pub limit: Option<i64>,
45    /// 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.
46    pub usemarker: Option<bool>,
47    /// 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`.
48    pub marker: Option<String>,
49}
50
51/// Deletes a user.
52/// By default this will fail if the user still owns any content.
53/// Move their owned content first before proceeding, or use the `force` field to delete the user and their files.
54///
55/// Sample usage:
56/// ```no_run
57/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api};
58///
59/// use dotenv;
60/// use std::env;
61///
62/// #[tokio::main]
63/// async fn main() -> Result<(), BoxAPIError> {
64///
65///     dotenv::from_filename(".dev.env").ok();
66///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
67///
68///     let config = Config::new();
69///     let auth = DevAuth::new(
70///         config,
71///         access_token,
72///     );
73///     let mut client = BoxClient::new(Box::new(auth));
74///
75///     let user_id = "12345";
76///     users_api::delete(&mut client, &user_id, None, None).await?;
77///
78///     Ok(())
79/// }
80/// ```
81pub async fn delete(
82    client: &mut BoxClient<'_>,
83    user_id: &str,
84    notify: Option<bool>,
85    force: Option<bool>,
86) -> Result<(), BoxAPIError> {
87    let uri = client.auth.base_api_url() + "/users" + format!("/{}", user_id).as_str();
88    let headers = client.headers().await?;
89
90    let value = serde_json::json!({
91        "notify": notify,
92        "force": force,
93    });
94
95    client.http.delete(&uri, Some(&headers), &value).await?;
96    let resp = client.http.delete(&uri, Some(&headers), &value).await;
97    match resp {
98        Ok(_) => Ok(()),
99        Err(e) => Err(e),
100    }
101}
102
103/// Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`.  
104/// The application and the authenticated user need to have the permission to look up users in the entire enterprise.
105///
106/// Sample usage:
107/// ```no_run
108/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api};
109///
110/// use dotenv;
111/// use std::env;
112///
113/// #[tokio::main]
114/// async fn main() -> Result<(), BoxAPIError> {
115///
116///     dotenv::from_filename(".dev.env").ok();
117///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
118///
119///     let config = Config::new();
120///     let auth = DevAuth::new(
121///         config,
122///         access_token,
123///     );
124///     let mut client = BoxClient::new(Box::new(auth));
125///
126///     let result = users_api::list(&mut client, None).await?;
127///     println!("Users:");
128///
129///     if let Some(users) = result.entries {
130///         for user in users {
131///             println!(
132///                 "{}\t{}\t{}\t{}",
133///                 user.id.unwrap(),
134///                 user.r#type.to_string(),
135///                 user.name.unwrap(),
136///                 user.login.unwrap(),
137///             );
138///         }
139///     }
140///
141///     Ok(())
142/// }
143/// ```
144pub async fn list(
145    client: &mut BoxClient<'_>,
146    params: Option<ListUsersParams>,
147) -> Result<Users, BoxAPIError> {
148    let uri = client.auth.base_api_url() + "/users";
149    let headers = client.headers().await?;
150
151    let params = params.unwrap_or_default();
152
153    let filter_term = params.filter_term.unwrap_or_default();
154    let user_type = params.user_type.unwrap_or_default();
155    let external_app_user_id = params.external_app_user_id.unwrap_or_default();
156
157    let fields = params
158        .fields
159        .unwrap_or(vec![])
160        .into_iter()
161        .collect::<Vec<String>>()
162        .join(",")
163        .to_string();
164
165    let offset = params.offset.unwrap_or_default().to_string();
166    let limit = params.limit.unwrap_or_default().to_string();
167    let usemarker = params.usemarker.unwrap_or_default().to_string();
168    let marker = params.marker.unwrap_or_default().to_string();
169
170    let mut payload = HashMap::new();
171
172    if filter_term != String::default() {
173        payload.insert("filter_term", filter_term.as_str());
174    }
175    if user_type != String::default() {
176        payload.insert("user_type", user_type.as_str());
177    }
178    if external_app_user_id != String::default() {
179        payload.insert("external_app_user_id", external_app_user_id.as_str());
180    }
181    if fields != String::default() {
182        payload.insert("fields", fields.as_str());
183    }
184    if offset != "0" {
185        payload.insert("offset", offset.as_str());
186    }
187    if limit != "0" {
188        payload.insert("limit", limit.as_str());
189    }
190    if usemarker != String::default() {
191        payload.insert("usemarker", usemarker.as_str());
192    }
193    if marker != String::default() {
194        payload.insert("marker", marker.as_str());
195    }
196
197    let resp = client.http.get(&uri, Some(&headers), &payload).await?;
198
199    let users = serde_json::from_str::<Users>(&resp)?;
200    Ok(users)
201}
202
203/// Retrieves information about a user in the enterprise.  
204/// The application and the authenticated user need to have the permission to look up users in the entire enterprise.  
205/// 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.
206/// In this case, disallowed fields will return null instead.
207///
208/// Sample usage:
209/// ```no_run
210/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api};
211///
212/// use dotenv;
213/// use std::env;
214///
215/// #[tokio::main]
216/// async fn main() -> Result<(), BoxAPIError> {
217///
218///     dotenv::from_filename(".dev.env").ok();
219///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
220///
221///     let config = Config::new();
222///     let auth = DevAuth::new(
223///         config,
224///         access_token,
225///     );
226///     let mut client = BoxClient::new(Box::new(auth));
227///
228///     let user_id = "123";
229///     
230///     let user = users_api::id(&mut client, &user_id, None).await?;
231///     println!("User:{:#?}", user);
232///
233///     Ok(())
234/// }
235/// ```
236pub async fn id(
237    client: &mut BoxClient<'_>,
238    user_id: &str,
239    fields: Option<Vec<String>>,
240) -> Result<UserFull, BoxAPIError> {
241    let uri = client.auth.base_api_url() + "/users" + format!("/{}", user_id).as_str();
242    let headers = client.headers().await?;
243
244    let fields = fields
245        .unwrap_or(vec![])
246        .into_iter()
247        .collect::<Vec<String>>()
248        .join(",")
249        .to_string();
250
251    let mut payload = HashMap::new();
252    payload.insert("fields", fields.as_str());
253
254    let resp = client.http.get(&uri, Some(&headers), &payload).await;
255    match resp {
256        Ok(res) => {
257            let user = serde_json::from_str::<UserFull>(&res)?;
258            Ok(user)
259        }
260        Err(e) => Err(e),
261    }
262}
263
264/// Retrieves information about the user who is currently authenticated.  
265/// In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app.  
266/// In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default.  
267/// Use the `As-User` header to change who this API call is made on behalf of.
268///
269/// Sample usage:
270/// ```no_run
271/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api};
272///
273/// use dotenv;
274/// use std::env;
275///
276///  #[tokio::main]
277/// async fn main() -> Result<(), BoxAPIError> {
278///
279///     dotenv::from_filename(".dev.env").ok();
280///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
281///
282///     let config = Config::new();
283///     let auth = DevAuth::new(
284///         config,
285///         access_token,
286///     );
287///     let mut client = BoxClient::new(Box::new(auth));
288///     
289///     let me = users_api::me(&mut client, None).await?;
290///     println!("Me:{:#?}", me);
291///
292///     Ok(())
293/// }
294/// ```
295pub async fn me(
296    client: &mut BoxClient<'_>,
297    fields: Option<Vec<String>>,
298) -> Result<UserFull, BoxAPIError> {
299    let uri = client.auth.base_api_url() + "/users/me";
300    let headers = client.headers().await?;
301
302    let fields = fields
303        .unwrap_or(vec![])
304        .into_iter()
305        .collect::<Vec<String>>()
306        .join(",")
307        .to_string();
308
309    let mut payload = HashMap::new();
310    payload.insert("fields", fields.as_str());
311
312    let resp = client.http.get(&uri, Some(&headers), &payload).await;
313    match resp {
314        Ok(res) => {
315            let user = serde_json::from_str::<UserFull>(&res)?;
316            Ok(user)
317        }
318        Err(e) => Err(e),
319    }
320}
321
322/// Creates a new managed user in an enterprise.
323/// This endpoint is only available to users and applications with the right admin permissions.
324///
325/// Sample usage:
326/// ```no_run
327/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api, users::models::{PostUsersRequest, Role, Status}};
328///
329/// use dotenv;
330/// use std::env;
331///
332/// #[tokio::main]
333/// async fn main() -> Result<(), BoxAPIError> {
334///
335///     dotenv::from_filename(".dev.env").ok();
336///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
337///
338///     let config = Config::new();
339///     let auth = DevAuth::new(
340///         config,
341///         access_token,
342///     );
343///     let mut client = BoxClient::new(Box::new(auth));
344///     
345///     let new_user_request = PostUsersRequest {
346///         name: "Test User".to_string(),
347///         login: Some("test.user@gmail.local".to_string()),
348///         is_platform_access_only: Some(false),
349///         role: Some(Role::Coadmin),
350///         language: Some("en".to_string()),
351///         is_sync_enabled: Some(true),
352///         job_title: Some("Test Job Title".to_string()),
353///         phone: Some("555-555-5555".to_string()),
354///         address: Some("123 Test St".to_string()),
355///         space_amount: Some(1073741824),
356///         // tracking_codes: Some(vec!["test-tracking-code".to_string()]),
357///         can_see_managed_users: Some(true),
358///         timezone: Some("America/Los_Angeles".to_string()),
359///         is_external_collab_restricted: Some(false),
360///         is_exempt_from_device_limits: Some(false),
361///         is_exempt_from_login_verification: Some(false),
362///         status: Some(Status::Active),
363///         external_app_user_id: Some("test-external-app-user-id".to_string()),
364///         ..Default::default()
365///     };
366///
367///     let new_user = users_api::create(&mut client, None, new_user_request).await?;
368///     println!("New User:{:#?}", new_user);
369///
370///     Ok(())
371/// }
372/// ```
373pub async fn create(
374    client: &mut BoxClient<'_>,
375    fields: Option<Vec<String>>,
376    user: PostUsersRequest,
377) -> Result<UserFull, BoxAPIError> {
378    let uri = client.auth.base_api_url() + "/users";
379    let headers = client.headers().await?;
380
381    let fields = fields
382        .unwrap_or(vec![])
383        .into_iter()
384        .collect::<Vec<String>>()
385        .join(",")
386        .to_string();
387
388    let mut query = HashMap::new();
389    if !fields.is_empty() {
390        query.insert("fields", fields.as_str());
391    }
392
393    // convert the postusersrequest to json
394    let value_json = serde_json::to_string(&user)?;
395    let value = serde_json::from_str(&value_json)?;
396
397    let resp = client
398        .http
399        .post(&uri, Some(&headers), Some(&query), &value)
400        .await;
401    match resp {
402        Ok(res) => {
403            let user = serde_json::from_str::<UserFull>(&res)?;
404            Ok(user)
405        }
406        Err(e) => Err(e),
407    }
408}
409
410/// Validates the roles and permissions of the user,
411/// and creates asynchronous jobs to terminate the user's sessions.
412/// Returns the status for the POST request.
413///
414/// Sample usage:
415///
416/// ```no_run
417/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api};
418///
419/// use dotenv;
420/// use std::env;
421///
422/// #[tokio::main]
423/// async fn main() -> Result<(), BoxAPIError> {
424///
425///     dotenv::from_filename(".dev.env").ok();
426///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
427///
428///     let config = Config::new();
429///     let auth = DevAuth::new(
430///         config,
431///         access_token,
432///     );
433///     let mut client = BoxClient::new(Box::new(auth));
434///     
435///     let by_user_ids = users_api::terminate_sessions_by_user_ids(
436///         &mut client,
437///         vec!["123".to_string(), "456".to_string()],
438///     )
439///     .await?;
440///     assert!(by_user_ids.is_some());
441///
442///     Ok(())
443/// }
444/// ```
445pub async fn terminate_sessions_by_user_ids(
446    client: &mut BoxClient<'_>,
447    user_ids: Vec<String>,
448) -> Result<Option<String>, BoxAPIError> {
449    let uri = client.auth.base_api_url() + "/users/terminate_sessions";
450    let headers = client.headers().await?;
451
452    let mut value = HashMap::new();
453    value.insert("user_ids", user_ids);
454    let value = json!(value);
455
456    let resp = client.http.post(&uri, Some(&headers), None, &value).await;
457    match resp {
458        Ok(res) => Ok(Some(res)),
459        Err(e) => Err(e),
460    }
461}
462
463/// Validates the roles and permissions of the user,
464/// and creates asynchronous jobs to terminate the user's sessions.
465/// Returns the status for the POST request.
466///
467/// Sample usage:
468/// ```no_run
469/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api};
470///
471/// use dotenv;
472/// use std::env;
473///
474/// #[tokio::main]
475/// async fn main() -> Result<(), BoxAPIError> {
476///
477///     dotenv::from_filename(".dev.env").ok();
478///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
479///
480///     let config = Config::new();
481///     let auth = DevAuth::new(
482///         config,
483///         access_token,
484///     );
485///     let mut client = BoxClient::new(Box::new(auth));
486///     
487///
488///     let by_user_logins = users_api::terminate_sessions_by_user_logins(
489///         &mut client,
490///         vec!["abc@gmail.local".to_string(), "def@gmail.local".to_string()],
491///     )
492///     .await?;
493///     assert!(by_user_logins.is_some());
494///
495///     Ok(())
496/// }
497/// ```
498pub async fn terminate_sessions_by_user_logins(
499    client: &mut BoxClient<'_>,
500    user_logins: Vec<String>,
501) -> Result<Option<String>, BoxAPIError> {
502    let uri = client.auth.base_api_url() + "/users/terminate_sessions";
503    let headers = client.headers().await?;
504
505    let mut value = HashMap::new();
506    value.insert("user_logins", user_logins);
507    let value = json!(value);
508
509    let resp = client.http.post(&uri, Some(&headers), None, &value).await;
510    match resp {
511        Ok(res) => Ok(Some(res)),
512        Err(e) => Err(e),
513    }
514}
515
516/// Validates the roles and permissions of the user,
517/// and creates asynchronous jobs to terminate the user's sessions.
518/// Returns the status for the POST request.
519///
520/// Sample usage:
521/// ```no_run
522/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api};
523///
524/// use dotenv;
525/// use std::env;
526///
527/// #[tokio::main]
528/// async fn main() -> Result<(), BoxAPIError> {
529///
530///     dotenv::from_filename(".dev.env").ok();
531///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
532///
533///     let config = Config::new();
534///     let auth = DevAuth::new(
535///         config,
536///         access_token,
537///     );
538///     let mut client = BoxClient::new(Box::new(auth));
539///     
540///     let by_group_ids = users_api::terminate_sessions_by_group_ids(
541///         &mut client,
542///         vec!["123".to_string(), "456".to_string()],
543///     )
544///     .await?;
545///     assert!(by_group_ids.is_some());
546///
547///     Ok(())
548/// }
549/// ```
550pub async fn terminate_sessions_by_group_ids(
551    client: &mut BoxClient<'_>,
552    group_ids: Vec<String>,
553    // fields: Option<Vec<String>>,
554) -> Result<Option<String>, BoxAPIError> {
555    let uri = client.auth.base_api_url() + "/users/terminate_sessions";
556    let headers = client.headers().await?;
557
558    let mut value = HashMap::new();
559    value.insert("user_ids", group_ids);
560    let value = json!(value);
561
562    let resp = client.http.post(&uri, Some(&headers), None, &value).await;
563    match resp {
564        Ok(res) => Ok(Some(res)),
565        Err(e) => Err(e),
566    }
567}
568
569/// Updates a managed or app user in an enterprise.
570/// This endpoint is only available to users and applications with the right admin permissions.
571///
572/// Sample usage:
573/// ```no_run
574/// use rusty_box::{Config, DevAuth, BoxClient,BoxAPIError, users_api, users::models::{PutUsersIdRequest, Role, Status}};
575/// use dotenv;
576/// use std::env;
577///
578/// #[tokio::main]
579/// async fn main() -> Result<(), BoxAPIError> {
580///
581///     dotenv::from_filename(".dev.env").ok();
582///     let access_token = env::var("DEVELOPER_TOKEN").expect("DEVELOPER_TOKEN must be set");
583///
584///     let config = Config::new();
585///     let auth = DevAuth::new(
586///         config,
587///         access_token,
588///     );
589///     let mut client = BoxClient::new(Box::new(auth));
590///
591///     let user_id = "12345";
592///     
593///     let user_updates = PutUsersIdRequest {
594///         name: Some("Test User Updated".to_string()),
595///         address: Some("456 Test St".to_string()),
596///         ..Default::default()
597///     };
598///
599///     let updated_user =
600///         users_api::update(&mut client, &user_id, None, user_updates).await?;
601///     println!("Updated User:{:#?}", updated_user);
602///
603///     Ok(())
604/// }
605/// ```
606pub async fn update(
607    client: &mut BoxClient<'_>,
608    user_id: &str,
609    fields: Option<Vec<String>>,
610    user: PutUsersIdRequest,
611) -> Result<UserFull, BoxAPIError> {
612    let uri = client.auth.base_api_url() + "/users" + format!("/{}", user_id).as_str();
613    let headers = client.headers().await?;
614
615    let fields = fields
616        .unwrap_or(vec![])
617        .into_iter()
618        .collect::<Vec<String>>()
619        .join(",")
620        .to_string();
621
622    let mut query = HashMap::new();
623    if !fields.is_empty() {
624        query.insert("fields", fields.as_str());
625    }
626
627    // convert the postusersrequest to json
628    let value_json = serde_json::to_string(&user)?;
629    let value = serde_json::from_str(&value_json)?;
630
631    let resp = client
632        .http
633        .put(&uri, Some(&headers), Some(&query), &value)
634        .await;
635    match resp {
636        Ok(res) => {
637            let user = serde_json::from_str::<UserFull>(&res)?;
638            Ok(user)
639        }
640        Err(e) => Err(e),
641    }
642}