use super::{Credential, HttpBasicAuth};
use crate::error::{GarrisonError, GarrisonResult};
use base64::{engine::general_purpose::STANDARD, Engine};
impl HttpBasicAuth {
pub fn encode(user: &str, pass: &str) -> String {
let credentials = format!("{}:{}", user, pass);
STANDARD.encode(credentials.as_bytes())
}
pub fn decode(header_value: &str) -> GarrisonResult<Credential> {
let decoded = STANDARD
.decode(header_value)
.map_err(|e| GarrisonError::Internal(format!("secure-base64-decode::{}", e)))?;
let decoded_str = String::from_utf8(decoded)
.map_err(|e| GarrisonError::Internal(format!("secure-utf8-decode::{}", e)))?;
let (user, pass) = decoded_str
.split_once(':')
.ok_or_else(|| GarrisonError::Internal("secure-cred-missing-colon::".to_string()))?;
Ok(Credential {
user: user.to_string(),
pass: pass.to_string(),
})
}
pub fn parse_authorization_header(header: &str) -> GarrisonResult<Credential> {
let header = header.trim();
let (scheme, credentials) = header
.split_once(char::is_whitespace)
.ok_or_else(|| GarrisonError::Internal("secure-auth-header-no-cred::".to_string()))?;
if !scheme.eq_ignore_ascii_case("basic") {
return Err(GarrisonError::Internal(format!(
"secure-httpbasic-unsupported-scheme::{}",
scheme
)));
}
let credentials = credentials.trim();
if credentials.is_empty() {
return Err(GarrisonError::Internal(
"secure-auth-header-no-cred::".to_string(),
));
}
Self::decode(credentials)
}
}