use std::sync::Arc;
use serenade_http::{HttpError, Middleware, Request, RequestHandler, Response};
use crate::{SecurityError, UsernamePasswordToken};
pub const TOKEN_ATTRIBUTE: &str = "_security_token";
pub trait Authenticator: Send + Sync {
fn authenticate(
&self,
credentials: Option<&str>,
) -> Result<UsernamePasswordToken, SecurityError>;
}
pub struct FirewallMiddleware {
header_name: String,
authenticator: Arc<dyn Authenticator>,
allow_anonymous: bool,
}
impl FirewallMiddleware {
#[must_use]
pub fn new(
header_name: impl Into<String>,
authenticator: impl Authenticator + 'static,
) -> Self {
Self {
header_name: header_name.into(),
authenticator: Arc::new(authenticator),
allow_anonymous: false,
}
}
#[must_use]
pub const fn allow_anonymous(mut self, allow: bool) -> Self {
self.allow_anonymous = allow;
self
}
}
impl Middleware for FirewallMiddleware {
fn process(
&self,
request: &mut Request,
next: &dyn RequestHandler,
) -> Result<Response, HttpError> {
let credentials = request.headers().get(&self.header_name);
let token = if credentials.is_none() && self.allow_anonymous {
UsernamePasswordToken::anonymous()
} else {
self.authenticator
.authenticate(credentials)
.map_err(|err| HttpError::status(401, err.to_string()))?
};
request.attributes_mut().insert(TOKEN_ATTRIBUTE, token);
next.handle(request)
}
}
#[must_use]
pub fn request_token(request: &Request) -> Option<&UsernamePasswordToken> {
request
.attributes()
.get::<UsernamePasswordToken>(TOKEN_ATTRIBUTE)
}