typedb_driver/user/
user_manager.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19use std::collections::HashMap;
20
21use crate::{
22    common::{address::Address, Result},
23    connection::server_connection::ServerConnection,
24    error::ConnectionError,
25    User,
26};
27
28/// Provides access to all user management methods.
29#[derive(Debug)]
30pub struct UserManager {
31    server_connections: HashMap<Address, ServerConnection>,
32}
33
34impl UserManager {
35    pub fn new(server_connections: HashMap<Address, ServerConnection>) -> Self {
36        Self { server_connections }
37    }
38
39    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
40    pub async fn get_current_user(&self) -> Result<Option<User>> {
41        let (_, connection) = self
42            .server_connections
43            .iter()
44            .next()
45            .expect("Unexpected condition: the server connection collection is empty");
46        self.get(connection.username()).await
47    }
48
49    /// Checks if a user with the given name exists.
50    ///
51    /// # Arguments
52    ///
53    /// * `username` — The user name to be checked
54    ///
55    /// # Examples
56    ///
57    /// ```rust
58    /// driver.users.contains(username).await;
59    /// ```
60    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
61    pub async fn contains(&self, username: impl Into<String>) -> Result<bool> {
62        let username = username.into();
63        let mut error_buffer = Vec::with_capacity(self.server_connections.len());
64        for (server_id, server_connection) in self.server_connections.iter() {
65            match server_connection.contains_user(username.clone()).await {
66                Ok(res) => return Ok(res),
67                Err(err) => error_buffer.push(format!("- {}: {}", server_id, err)),
68            }
69        }
70        Err(ConnectionError::ServerConnectionFailedWithError { error: error_buffer.join("\n") })?
71    }
72
73    /// Retrieve a user with the given name.
74    ///
75    /// # Arguments
76    ///
77    /// * `username` — The name of the user to retrieve
78    ///
79    /// # Examples
80    ///
81    /// ```rust
82    /// driver.users.get(username).await;
83    /// ```
84    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
85    pub async fn get(&self, username: impl Into<String>) -> Result<Option<User>> {
86        let uname = username.into();
87        let mut error_buffer = Vec::with_capacity(self.server_connections.len());
88        for (server_id, server_connection) in self.server_connections.iter() {
89            match server_connection.get_user(uname.clone()).await {
90                Ok(res) => {
91                    return Ok(res.map(|u_info| User {
92                        name: u_info.name,
93                        password: u_info.password,
94                        server_connections: self.server_connections.clone(),
95                    }))
96                }
97                Err(err) => error_buffer.push(format!("- {}: {}", server_id, err)),
98            }
99        }
100        Err(ConnectionError::ServerConnectionFailedWithError { error: error_buffer.join("\n") })?
101    }
102
103    /// Retrieves all users which exist on the TypeDB server.
104    ///
105    /// # Examples
106    ///
107    /// ```rust
108    /// driver.users.all().await;
109    /// ```
110    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
111    pub async fn all(&self) -> Result<Vec<User>> {
112        let mut error_buffer = Vec::with_capacity(self.server_connections.len());
113        for (server_id, server_connection) in self.server_connections.iter() {
114            match server_connection.all_users().await {
115                Ok(res) => {
116                    return Ok(res
117                        .iter()
118                        .map(|u_info| User {
119                            name: u_info.name.clone(),
120                            password: u_info.password.clone(),
121                            server_connections: self.server_connections.clone(),
122                        })
123                        .collect())
124                }
125                Err(err) => error_buffer.push(format!("- {}: {}", server_id, err)),
126            }
127        }
128        Err(ConnectionError::ServerConnectionFailedWithError { error: error_buffer.join("\n") })?
129    }
130
131    /// Create a user with the given name &amp; password.
132    ///
133    /// # Arguments
134    ///
135    /// * `username` — The name of the user to be created
136    /// * `password` — The password of the user to be created
137    ///
138    /// # Examples
139    ///
140    /// ```rust
141    /// driver.users.create(username, password).await;
142    /// ```
143    #[cfg_attr(feature = "sync", maybe_async::must_be_sync)]
144    pub async fn create(&self, username: impl Into<String>, password: impl Into<String>) -> Result {
145        let uname = username.into();
146        let passwd = password.into();
147        let mut error_buffer = Vec::with_capacity(self.server_connections.len());
148        for (server_id, server_connection) in self.server_connections.iter() {
149            match server_connection.create_user(uname.clone(), passwd.clone()).await {
150                Ok(res) => return Ok(res),
151                Err(err) => error_buffer.push(format!("- {}: {}", server_id, err)),
152            }
153        }
154        Err(ConnectionError::ServerConnectionFailedWithError { error: error_buffer.join("\n") })?
155    }
156}