rocket_authorization/
basic.rs

1use super::{AuthError, Authorization, Request};
2use base64::engine::general_purpose::STANDARD as BASE64;
3use base64::Engine as _;
4
5#[derive(Debug, Clone, PartialEq)]
6pub struct Basic {
7    pub username: String,
8    pub password: String,
9}
10
11#[rocket::async_trait]
12impl Authorization for Basic {
13    const KIND: &'static str = "Basic";
14
15    async fn parse(_: &str, credential: &str, _: &Request) -> Result<Self, AuthError> {
16        let decoded_payload = BASE64
17            .decode(credential)
18            .map_err(|error| AuthError::Unprocessable(format!("Base64 Decode Error: {error}")))?;
19
20        let decoded_text = String::from_utf8(decoded_payload)
21            .map_err(|error| AuthError::Unprocessable(format!("UTF8 Parse Error: {error}")))?;
22
23        let components: Vec<_> = decoded_text.split(':').collect();
24        if components.len() != 2 {
25            return Err(AuthError::Unprocessable("Non-Colon Pair Given".into()));
26        }
27
28        let (username, password) = (components[0].trim(), components[1].trim());
29        if username.is_empty() || password.is_empty() {
30            return Err(AuthError::Unprocessable("No Credentials Given".into()));
31        }
32
33        Ok(Basic {
34            username: username.into(),
35            password: password.into(),
36        })
37    }
38}