use super::super::resolve::*;
use {
::axum::http::HeaderMap,
compris::resolve::*,
kutil::{cli::depict::*, http::*, std::immutable::*},
};
#[derive(Clone, Debug, Default, Depict, Resolve)]
pub struct Protect {
#[resolve(required)]
#[depict(option, as(display), style(string))]
pub regex: Option<ResolveRegex>,
#[resolve]
#[depict(option, style(string))]
pub realm: Option<ByteString>,
#[resolve(required)]
#[depict(style(string))]
pub username: ByteString,
#[resolve(required)]
#[depict(style(string))]
pub password: ByteString,
}
impl Protect {
pub fn protect(&self, uri_path: &str) -> bool {
if let Some(regex) = &self.regex
&& regex.inner.is_match(uri_path)
{
return true;
}
false
}
pub fn authorized(&self, headers: &HeaderMap) -> Option<ByteString> {
if let Some((username, password)) = headers.authorization_basic()
&& (self.username == username)
&& (self.password == password)
{
match &self.realm {
Some(realm) => tracing::debug!("authorized: {}", realm),
None => tracing::debug!("authorized"),
}
return None;
}
let authenticate = match &self.realm {
Some(realm) => {
tracing::debug!("unauthorized: {}", realm);
&format!("Basic realm=\"{}\", charset=\"UTF-8\"", realm)
}
None => {
tracing::debug!("unauthorized");
"Basic charset=\"UTF-8\""
}
};
Some(authenticate.into())
}
}