credence_lib/middleware/
facade.rs1use super::{
2 super::{configuration::*, render::*, util::*},
3 constants::*,
4 defer::*,
5};
6
7use {::axum::extract::*, kutil_http::*};
8
9#[derive(Clone, Debug)]
32pub struct FacadeMiddleware {
33 pub configuration: CredenceConfiguration,
35}
36
37impl FacadeMiddleware {
38 pub fn new(configuration: CredenceConfiguration) -> Self {
40 Self { configuration }
41 }
42
43 pub async fn function(State(state_self): State<Self>, mut request: Request) -> Request {
45 let uri_path = match request.uri().decoded_path() {
46 Some(uri_path) => uri_path,
47 None => {
48 return request;
50 }
51 };
52
53 let original_uri_path = uri_path.clone();
54 let mut uri_path = uri_path.as_ref();
55 let mut new_uri_path = None;
56
57 if let Some((uri_path, status_code)) = state_self.configuration.urls.redirect(uri_path) {
60 tracing::info!("redirect to: {} {}", status_code.as_u16(), uri_path);
62 return request.with_deferred_redirect_to(uri_path.into(), status_code);
63 }
64
65 if state_self.configuration.hide(uri_path) {
68 tracing::info!("hide: {}", uri_path);
69 return request.with_deferred_hide();
70 }
71
72 if let Some(protect) = state_self.configuration.urls.protect(uri_path) {
75 if let Some(authenticate) = protect.authorized(request.headers()) {
76 return request.with_deferred_authenticate(authenticate);
77 }
78 }
79
80 let mut asset_path = state_self.configuration.files.asset(uri_path);
83
84 let mut _uri_path = String::default();
86 if asset_path.is_dir() {
87 asset_path = asset_path.join(INDEX);
88 _uri_path = uri_path_join(uri_path, INDEX);
89 uri_path = &_uri_path;
90 }
91
92 let html_file = asset_path.with_extension(HTML_EXTENSION);
93 if html_file.exists() {
94 new_uri_path = Some(String::from(uri_path) + HTML_SUFFIX);
96 } else if let Some(rendered_page_uri_path) = match state_self.configuration.rendered_page_uri_path(uri_path) {
97 Ok(uri_path) => uri_path,
98 Err(_error) => {
99 return request.with_deferred_error("rendered page URI path".into());
100 }
101 } {
102 new_uri_path = Some(rendered_page_uri_path);
104 }
105
106 if let Some(new_uri_path) = new_uri_path {
107 tracing::debug!("rewriting: {} to {}", original_uri_path, new_uri_path);
108 let original_uri_path = original_uri_path.into_owned().into();
109 if let Err(_error) = request.set_uri_path(&new_uri_path) {
110 return request.with_deferred_error("set URI path".into());
111 }
112 return request.with_deferred_rewrite_from(original_uri_path);
113 }
114
115 request
116 }
117}