use sa_token_adapter::storage::SaStorage;
use sa_token_core::router::PathAuthConfig;
use std::sync::Arc;
use summer::app::AppBuilder;
use summer::plugin::MutableComponentRegistry;
pub trait SaTokenConfigurator: Send + Sync + 'static {
#[deprecated(note = "use `configure_path_auth` instead")]
fn configure(&self, auth: PathAuthBuilder) -> PathAuthBuilder {
auth
}
fn configure_path_auth(&self, auth: PathAuthBuilder) -> PathAuthBuilder {
#[allow(deprecated)]
self.configure(auth)
}
fn configure_storage(&self, _app: &AppBuilder) -> Option<Arc<dyn SaStorage>> {
None
}
}
#[derive(Debug, Clone, Default)]
pub struct PathAuthBuilder {
pub include: Vec<String>,
pub exclude: Vec<String>,
}
impl PathAuthBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn include(mut self, pattern: impl Into<String>) -> Self {
self.include.push(pattern.into());
self
}
pub fn include_all(mut self, patterns: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.include.extend(patterns.into_iter().map(|p| p.into()));
self
}
pub fn exclude(mut self, pattern: impl Into<String>) -> Self {
self.exclude.push(pattern.into());
self
}
pub fn exclude_all(mut self, patterns: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.exclude.extend(patterns.into_iter().map(|p| p.into()));
self
}
pub fn permit_all(self, pattern: impl Into<String>) -> Self {
self.exclude(pattern)
}
pub fn authenticated(self, pattern: impl Into<String>) -> Self {
self.include(pattern)
}
pub fn is_configured(&self) -> bool {
!self.include.is_empty()
}
pub fn build(self) -> PathAuthConfig {
PathAuthConfig::new()
.include(self.include)
.exclude(self.exclude)
}
pub fn merge(mut self, other: PathAuthBuilder) -> Self {
self.include.extend(other.include);
self.exclude.extend(other.exclude);
self
}
}
pub trait SaTokenAuthConfigurator {
#[deprecated(note = "use `sa_token_configure` instead")]
fn sa_token_auth<C>(&mut self, configurator: C) -> &mut Self
where
C: SaTokenConfigurator;
fn sa_token_configure<C>(&mut self, configurator: C) -> &mut Self
where
C: SaTokenConfigurator;
}
impl SaTokenAuthConfigurator for AppBuilder {
#[allow(deprecated)]
fn sa_token_auth<C>(&mut self, configurator: C) -> &mut Self
where
C: SaTokenConfigurator,
{
self.sa_token_configure(configurator)
}
fn sa_token_configure<C>(&mut self, configurator: C) -> &mut Self
where
C: SaTokenConfigurator,
{
if let Some(storage) = configurator.configure_storage(self) {
self.add_component(crate::custom_storage::SaTokenStorage::new(storage));
}
let builder = configurator.configure_path_auth(PathAuthBuilder::new());
if builder.is_configured() {
let config = builder.build();
self.add_component(config)
} else {
self
}
}
}
impl SaTokenConfigurator for PathAuthBuilder {
fn configure_path_auth(&self, auth: PathAuthBuilder) -> PathAuthBuilder {
auth.merge(self.clone())
}
}