nethsm_config/credentials.rs
1use nethsm::{Credentials, Passphrase, UserId, UserRole};
2use serde::{Deserialize, Serialize};
3use zeroize::Zeroize;
4
5/// A set of credentials for a [`NetHsm`][`nethsm::NetHsm`]
6///
7/// Tracks the [`UserRole`], [`UserId`] and optionally the passphrase of the user.
8#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, Zeroize)]
9pub struct ConfigCredentials {
10 #[zeroize(skip)]
11 role: UserRole,
12 #[zeroize(skip)]
13 name: UserId,
14 passphrase: Option<String>,
15}
16
17impl ConfigCredentials {
18 /// Creates a new [`ConfigCredentials`]
19 ///
20 /// # Examples
21 ///
22 /// ```
23 /// use nethsm::UserRole;
24 /// use nethsm_config::{ConfigCredentials, ConfigInteractivity};
25 ///
26 /// # fn main() -> testresult::TestResult {
27 /// // credentials for an Operator user with passphrase
28 /// ConfigCredentials::new(
29 /// UserRole::Operator,
30 /// "user1".parse()?,
31 /// Some("my-passphrase".into()),
32 /// );
33 ///
34 /// // credentials for an Administrator user without passphrase
35 /// ConfigCredentials::new(UserRole::Administrator, "admin1".parse()?, None);
36 /// # Ok(())
37 /// # }
38 /// ```
39 pub fn new(role: UserRole, name: UserId, passphrase: Option<String>) -> Self {
40 Self {
41 role,
42 name,
43 passphrase,
44 }
45 }
46
47 /// Returns the name (a [`UserId`])
48 pub fn get_name(&self) -> UserId {
49 self.name.clone()
50 }
51
52 /// Returns the role (a [`UserRole`])
53 pub fn get_role(&self) -> UserRole {
54 self.role
55 }
56
57 /// Returns the passphrase of the [`ConfigCredentials`]
58 pub fn get_passphrase(&self) -> Option<&str> {
59 self.passphrase.as_deref()
60 }
61
62 /// Sets the passphrase of the [`ConfigCredentials`]
63 pub fn set_passphrase(&mut self, passphrase: String) {
64 self.passphrase = Some(passphrase)
65 }
66
67 /// Returns whether a passphrase is set for the [`ConfigCredentials`]
68 pub fn has_passphrase(&self) -> bool {
69 self.passphrase.is_some()
70 }
71}
72
73impl From<ConfigCredentials> for Credentials {
74 fn from(value: ConfigCredentials) -> Self {
75 Self::new(value.name, value.passphrase.map(Passphrase::new))
76 }
77}