http_auth_basic/
credentials.rs

1use std::str::FromStr;
2
3use base64::{prelude::BASE64_STANDARD, Engine};
4
5use crate::error::AuthBasicError;
6
7/// A `struct` to represent the `user_id` and `password` fields
8/// from an _Authorization Basic_ header value
9#[derive(Debug, PartialEq)]
10pub struct Credentials {
11    pub user_id: String,
12    pub password: String,
13}
14
15impl Credentials {
16    /// Create a new `Credentials` instance
17    /// this is equivalent to writing:
18    ///
19    /// ```
20    /// use http_auth_basic::Credentials;
21    ///
22    /// let credentials = Credentials {
23    ///     user_id: String::from("Foo"),
24    ///     password: String::from("Bar"),
25    /// };
26    ///
27    /// ```
28    ///
29    pub fn new(user_id: &str, password: &str) -> Self {
30        Self {
31            user_id: user_id.to_string(),
32            password: password.to_string(),
33        }
34    }
35
36    /// Creates a `Credentials` instance from a base64 `String`
37    /// which must encode user credentials as `username:password`
38    pub fn decode(auth_header_value: String) -> Result<Self, AuthBasicError> {
39        let decoded = BASE64_STANDARD.decode(auth_header_value)?;
40        let as_utf8 = String::from_utf8(decoded)?;
41
42        // RFC 2617 provides support for passwords with colons
43        if let Some((user_id, password)) = as_utf8.split_once(':') {
44            return Ok(Self::new(user_id, password));
45        }
46
47        Err(AuthBasicError::InvalidAuthorizationHeader)
48    }
49
50    /// Encode a `Credentials` instance into a base64 `String`
51    pub fn encode(&self) -> String {
52        let credentials = format!("{}:{}", self.user_id, self.password);
53
54        BASE64_STANDARD.encode(credentials.as_bytes())
55    }
56
57    /// Creates a `Credentials` instance from an HTTP Authorization header
58    /// which schema is a valid `Basic` HTTP Authorization Schema.
59    pub fn from_header(auth_header: String) -> Result<Credentials, AuthBasicError> {
60        // check if its a valid basic auth header
61        if let Some((auth_type, encoded_credentials)) = auth_header.split_once(' ') {
62            if encoded_credentials.contains(' ') {
63                // Invalid authorization token received
64                return Err(AuthBasicError::InvalidAuthorizationHeader);
65            }
66
67            // Check the provided authorization header
68            // to be a "Basic" authorization header
69            if auth_type.to_lowercase() != "basic" {
70                return Err(AuthBasicError::InvalidScheme(auth_type.to_string()));
71            }
72
73            let credentials = Credentials::decode(encoded_credentials.to_string())?;
74
75            return Ok(credentials);
76        }
77
78        Err(AuthBasicError::InvalidAuthorizationHeader)
79    }
80
81    /// Creates a HTTP Authorization header value for the basic schema
82    /// from the `Credentials` instance
83    pub fn as_http_header(&self) -> String {
84        let as_base64 = self.encode();
85
86        format!("Basic {}", as_base64)
87    }
88}
89
90impl FromStr for Credentials {
91    type Err = AuthBasicError;
92
93    /// Creates a `Credentials` instance from either a base64 `&str`
94    /// which must encode user credentials as `username:password`
95    /// or an HTTP Authorization header which schema is a
96    /// valid `Basic` HTTP Authorization Schema.
97    fn from_str(s: &str) -> Result<Self, Self::Err> {
98        if s.contains(' ') {
99            return Self::from_header(s.into());
100        }
101
102        Self::decode(s.into())
103    }
104}