use super::{DefaultGarrisonInterceptor, GarrisonInterceptor};
use crate::annotation::Annotation;
use crate::config::GarrisonConfig;
use crate::context::axum_adapter::AxumRequest;
#[cfg(feature = "tenant-isolation")]
use crate::context::tenant::TenantResolver;
use crate::context::GarrisonRequest;
use crate::error::GarrisonError;
use crate::stp::context::{clear_renewed_token, get_renewed_token, with_renewed_token_scope};
use crate::stp::with_current_token;
use axum::body::Body;
use axum::extract::State;
use axum::handler::Handler;
use axum::http::header::SET_COOKIE;
#[cfg(feature = "tenant-isolation")]
use axum::http::StatusCode;
use axum::http::{HeaderName, HeaderValue, Request};
use axum::middleware::{from_fn_with_state, Next};
use axum::response::{IntoResponse, Response};
use axum::Router;
use std::sync::Arc;
#[derive(Clone)]
struct RouteRule {
path: String,
annotation: Annotation,
}
#[derive(Clone)]
struct MiddlewareState {
rules: Arc<Vec<RouteRule>>,
interceptor: Arc<dyn GarrisonInterceptor>,
config: Arc<GarrisonConfig>,
}
pub struct GarrisonRouter {
inner: Router,
rules: Vec<RouteRule>,
interceptor: Arc<dyn GarrisonInterceptor>,
config: Arc<GarrisonConfig>,
}
impl GarrisonRouter {
pub fn new(config: Arc<GarrisonConfig>) -> Self {
Self {
inner: Router::new(),
rules: Vec::new(),
interceptor: Arc::new(DefaultGarrisonInterceptor),
config,
}
}
pub fn with_interceptor<I: GarrisonInterceptor + 'static>(mut self, interceptor: I) -> Self {
self.interceptor = Arc::new(interceptor);
self
}
pub fn route_protected<H, T>(mut self, path: &str, handler: H, annotation: Annotation) -> Self
where
H: Handler<T, ()> + Clone + Send + Sync + 'static,
T: 'static,
{
self.inner = self.inner.route(path, axum::routing::get(handler));
self.rules.push(RouteRule {
path: path.to_string(),
annotation,
});
self
}
pub fn group<F>(self, prefix: &str, annotation: Annotation, f: F) -> Self
where
F: FnOnce(GarrisonRouter) -> GarrisonRouter,
{
assert!(!prefix.is_empty(), "prefix must not be empty");
let trimmed = prefix.trim_end_matches('/');
let child = GarrisonRouter {
inner: Router::new(),
rules: Vec::new(),
interceptor: self.interceptor.clone(),
config: self.config.clone(),
};
let child = f(child);
let mut parent = self;
for rule in child.rules {
let merged_path = format!("{}{}", trimmed, rule.path);
let merged_annotation = if annotation == Annotation::Ignore {
Annotation::Ignore
} else {
rule.annotation
};
parent.rules.push(RouteRule {
path: merged_path,
annotation: merged_annotation,
});
}
if trimmed.is_empty() {
parent.inner = parent.inner.merge(child.inner);
} else {
parent.inner = parent.inner.nest(trimmed, child.inner);
}
parent
}
pub fn build(self) -> Router {
let state = MiddlewareState {
rules: Arc::new(self.rules),
interceptor: self.interceptor,
config: self.config,
};
self.inner
.layer(from_fn_with_state(state, garrison_middleware))
}
}
impl Default for GarrisonRouter {
fn default() -> Self {
Self::new(Arc::new(GarrisonConfig::default_config()))
}
}
async fn garrison_middleware(
State(state): State<MiddlewareState>,
req: Request<Body>,
next: Next,
) -> Response {
let path = req.uri().path().to_string();
let rule = state.rules.iter().find(|r| r.path == path).cloned();
let token = AxumRequest::new(&req)
.get_token(&state.config)
.ok()
.flatten();
let handle = async {
if let Some(rule) = &rule {
state
.interceptor
.pre_handle(&path, &rule.annotation)
.await?;
}
Ok::<_, GarrisonError>(next.run(req).await)
};
let config = state.config.clone();
with_renewed_token_scope(async {
let result = match token {
Some(t) => with_current_token(t, handle).await,
None => handle.await,
};
let mut resp = match result {
Ok(resp) => resp,
Err(e) => e.into_response(),
};
if let Some(renewed_token) = get_renewed_token() {
if config.is_write_header {
if let Ok(name) = HeaderName::from_bytes(config.token_name.as_bytes()) {
if let Ok(value) = HeaderValue::from_str(&renewed_token) {
resp.headers_mut().insert(name, value);
}
}
}
if config.is_write_cookie {
let secure_flag = if config.cookie_secure { "; Secure" } else { "" };
let cookie = format!(
"{}={}; HttpOnly; Path=/; SameSite={}{}",
config.token_name, renewed_token, config.cookie_same_site, secure_flag
);
if let Ok(value) = HeaderValue::from_str(&cookie) {
resp.headers_mut().append(SET_COOKIE, value);
}
}
clear_renewed_token();
}
resp
})
.await
}
#[cfg(feature = "tenant-isolation")]
pub async fn tenant_resolution_middleware(
State(resolver): State<Arc<dyn TenantResolver>>,
req: Request<Body>,
next: Next,
) -> Result<Response, StatusCode> {
use crate::context::tenant::TENANT;
let ctx = resolver
.resolve(req.headers())
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
Ok(TENANT.scope(ctx, next.run(req)).await)
}