paperless_rs/authorization/
mod.rs

1use base64::engine::general_purpose::STANDARD;
2use base64::Engine;
3
4/// A struct that represents the type of authorization to use.
5pub enum AuthorizationType {
6    Basic(Credentials),
7    Token(String),
8}
9
10/// A struct that represents the credentials to use for basic authorization.
11pub struct Credentials(String);
12
13/// A struct that represents the type of certificate to use.
14pub enum CertificateType {
15    Pem(String),
16    Der(String),
17}
18
19impl AuthorizationType {
20    /// Converts the authorization type to a header.
21    pub fn as_header(&self) -> (String, String) {
22        match self {
23            AuthorizationType::Basic(credentials) => (
24                "Authorization".to_string(),
25                format!("Basic {}", credentials.0),
26            ),
27            AuthorizationType::Token(token) => {
28                ("Authorization".to_string(), format!("Token {}", token))
29            }
30        }
31    }
32}
33
34impl Credentials {
35    /// Creates a new instance of the Credentials struct.
36    ///
37    /// # Arguments
38    ///
39    /// * `username` - The username to use for the credentials.
40    /// * `password` - The password to use for the credentials.
41    pub fn new(username: String, password: String) -> Self {
42        let encoded = STANDARD.encode(format!("{}:{}", username, password));
43
44        Self(encoded)
45    }
46}
47
48impl CertificateType {
49    /// Converts the certificate type to a reqwest certificate.
50    pub async fn as_certificate(&self) -> Result<reqwest::Certificate, Box<dyn std::error::Error>> {
51        match self {
52            CertificateType::Pem(path) => {
53                let certificate = tokio::fs::read(path).await?;
54                Ok(reqwest::Certificate::from_pem(&certificate)?)
55            }
56            CertificateType::Der(path) => {
57                let certificate = tokio::fs::read(path).await?;
58                Ok(reqwest::Certificate::from_der(&certificate)?)
59            }
60        }
61    }
62}