xo_api_client/
credentials.rs

1use std::{collections::BTreeMap, str::FromStr};
2
3use crate::types::Impossible;
4use jsonrpsee_types::JsonValue;
5
6/// Login token used to authenticate with Xen Orchestra's API
7#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
8#[serde(transparent)]
9pub struct Token(pub String);
10
11impl ToString for Token {
12    fn to_string(&self) -> String {
13        self.0.clone()
14    }
15}
16
17impl From<String> for Token {
18    fn from(s: String) -> Self {
19        Token(s)
20    }
21}
22
23impl FromStr for Token {
24    type Err = Impossible;
25
26    fn from_str(s: &str) -> Result<Self, Self::Err> {
27        Ok(Token(s.to_string()))
28    }
29}
30
31impl From<Token> for Credentials {
32    fn from(val: Token) -> Self {
33        Credentials::Token(val)
34    }
35}
36
37/// Email and password used to authenticate with Xen Orchestra's API.
38///
39/// Note that there is also the type [`Token`]
40#[derive(Debug, Clone)]
41pub struct EmailAndPassword {
42    pub email: String,
43    pub password: String,
44}
45
46impl From<EmailAndPassword> for Credentials {
47    fn from(val: EmailAndPassword) -> Self {
48        Credentials::Password(val)
49    }
50}
51
52/// Some type of credentials used to authenticate with Xen Orchestra's API.
53///
54/// A value of this type may ether contain a [`Token`] or an [`EmailAndPassword`]
55pub enum Credentials {
56    Password(EmailAndPassword),
57    Token(Token),
58}
59
60impl From<Credentials> for BTreeMap<&str, JsonValue> {
61    fn from(credentials: Credentials) -> Self {
62        use std::array::IntoIter;
63
64        match credentials {
65            Credentials::Password(EmailAndPassword { email, password }) => {
66                IntoIter::new([("email", email.into()), ("password", password.into())]).collect()
67            }
68            Credentials::Token(Token(token)) => IntoIter::new([("token", token.into())]).collect(),
69        }
70    }
71}