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