1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use data_encoding::BASE64;
use std::fmt;

pub const HEADER_KEY: &str = "X-Collaboflow-Authorization";

/// Generate your own authentication headers to access the Collaboflow REST API.
///
/// ## Usage
///
/// ### API Key
///
/// ```rust
/// # use collaboflow_rs::{Authorization};
///
/// let authorization = Authorization::with_api_key("User id", "Api key");
/// ```
///
/// ### Password
///
/// ```rust
/// # use collaboflow_rs::{Authorization};
///
/// let authorization = Authorization::with_password("User id", "Password");
/// ```
#[derive(Debug, Clone)]
pub struct Authorization {
    authorization_type: AuthorizationType,
    user_id: String,
    value: String,
}

#[derive(Debug, Clone)]
pub enum AuthorizationType {
    ApiKey,
    Password,
}

impl Authorization {
    pub fn with_api_key(user_id: &str, api_key: &str) -> Self {
        Self {
            authorization_type: AuthorizationType::ApiKey,
            user_id: user_id.to_string(),
            value: api_key.to_string(),
        }
    }

    pub fn with_password(user_id: &str, password: &str) -> Self {
        Self {
            authorization_type: AuthorizationType::Password,
            user_id: user_id.to_string(),
            value: password.to_string(),
        }
    }
}

impl fmt::Display for Authorization {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let auth_header = match &self.authorization_type {
            AuthorizationType::ApiKey => format!("{}/apikey:{}", &self.user_id, &self.value),
            AuthorizationType::Password => format!("{}:{}", &self.user_id, &self.value),
        };

        let encoded: String = BASE64.encode(auth_header.as_bytes());
        write!(f, "Basic {}", encoded)
    }
}