use super::{
super::{configuration::*, render::*, util::*},
constants::*,
defer::*,
};
use {::axum::extract::*, kutil::http::*};
#[derive(Clone, Debug)]
pub struct FacadeMiddleware {
pub configuration: CredenceConfiguration,
}
impl FacadeMiddleware {
pub fn new(configuration: CredenceConfiguration) -> Self {
Self { configuration }
}
pub async fn function(State(state_self): State<Self>, mut request: Request) -> Request {
let uri_path = match request.uri().decoded_path() {
Some(uri_path) => uri_path,
None => {
return request;
}
};
let original_uri_path = uri_path.clone();
let mut uri_path = uri_path.as_ref();
let mut new_uri_path = None;
if let Some((uri_path, status_code)) = state_self.configuration.urls.redirect(uri_path) {
tracing::info!("redirect to: {} {}", status_code.as_u16(), uri_path);
return request.with_deferred_redirect_to(uri_path.into(), status_code);
}
if state_self.configuration.hide(uri_path) {
tracing::info!("hide: {}", uri_path);
return request.with_deferred_hide();
}
if let Some(protect) = state_self.configuration.urls.protect(uri_path)
&& let Some(authenticate) = protect.authorized(request.headers())
{
return request.with_deferred_authenticate(authenticate);
}
let mut asset_path = state_self.configuration.files.asset(uri_path);
if asset_path.is_dir() {
asset_path = asset_path.join(INDEX);
new_uri_path = Some(uri_path_join(uri_path, INDEX));
uri_path = new_uri_path.as_ref().unwrap();
}
let mut html_asset_path = asset_path.clone();
html_asset_path.as_mut_os_string().push(HTML_SUFFIX);
if html_asset_path.exists() {
new_uri_path = Some(String::from(uri_path) + HTML_SUFFIX);
} else if let Some(rendered_page_uri_path) = match state_self.configuration.rendered_page_uri_path(uri_path) {
Ok(uri_path) => uri_path,
Err(_error) => {
return request.with_deferred_error("rendered page URI path".into());
}
} {
new_uri_path = Some(rendered_page_uri_path);
}
if let Some(new_uri_path) = new_uri_path {
tracing::debug!("rewriting: {} to {}", original_uri_path, new_uri_path);
let original_uri_path = original_uri_path.into_owned().into();
if let Err(_error) = request.set_uri_path(&new_uri_path) {
return request.with_deferred_error("set URI path".into());
}
return request.with_deferred_rewrite_from(original_uri_path);
}
request
}
}