use crate::annotation::Annotation;
use crate::config::GarrisonConfig;
use crate::context::token_extract::extract_token_from_headers;
use crate::error::GarrisonResult;
use crate::router::{DefaultGarrisonInterceptor, GarrisonInterceptor};
use crate::stp::with_current_token;
use std::collections::HashMap;
use std::sync::Arc;
use warp::http::HeaderMap;
use warp::Filter;
impl super::GarrisonRouter {
pub fn new(config: Arc<GarrisonConfig>) -> Self {
Self {
rules: HashMap::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(mut self, path: &str, annotation: Annotation) -> Self {
self.rules.insert(path.to_string(), annotation);
self
}
pub fn into_filter(self) -> impl Filter<Extract = ((),), Error = warp::Rejection> + Clone {
let rules = Arc::new(self.rules);
let interceptor = self.interceptor;
let config = self.config;
warp::any()
.and(warp::path::full())
.and(warp::header::headers_cloned())
.and_then(move |path: warp::path::FullPath, headers: HeaderMap| {
let rules = rules.clone();
let interceptor = interceptor.clone();
let config = config.clone();
async move {
let path_str = path.as_str().to_string();
let annotation = rules.get(&path_str).cloned();
if let Some(annotation) = annotation {
let token = extract_token_from_headers(&headers, &config)
.map_err(|e| warp::reject::custom(super::GarrisonRejection(e)))?;
let auth_check =
async { interceptor.pre_handle(&path_str, &annotation).await };
let result: GarrisonResult<()> = match token {
Some(t) => with_current_token(t, auth_check).await,
None => auth_check.await,
};
result.map_err(|e| warp::reject::custom(super::GarrisonRejection(e)))?;
}
Ok::<(), warp::Rejection>(())
}
})
}
}
impl Default for super::GarrisonRouter {
fn default() -> Self {
Self::new(Arc::new(GarrisonConfig::default_config()))
}
}