serenade_security/
firewall.rs1use std::sync::Arc;
4
5use serenade_http::{HttpError, Middleware, Request, RequestHandler, Response};
6
7use crate::{SecurityError, UsernamePasswordToken};
8
9pub const TOKEN_ATTRIBUTE: &str = "_security_token";
11
12pub trait Authenticator: Send + Sync {
14 fn authenticate(
20 &self,
21 credentials: Option<&str>,
22 ) -> Result<UsernamePasswordToken, SecurityError>;
23}
24
25pub struct FirewallMiddleware {
27 header_name: String,
28 authenticator: Arc<dyn Authenticator>,
29 allow_anonymous: bool,
30}
31
32impl FirewallMiddleware {
33 #[must_use]
35 pub fn new(
36 header_name: impl Into<String>,
37 authenticator: impl Authenticator + 'static,
38 ) -> Self {
39 Self {
40 header_name: header_name.into(),
41 authenticator: Arc::new(authenticator),
42 allow_anonymous: false,
43 }
44 }
45
46 #[must_use]
48 pub const fn allow_anonymous(mut self, allow: bool) -> Self {
49 self.allow_anonymous = allow;
50 self
51 }
52}
53
54impl Middleware for FirewallMiddleware {
55 fn process(
56 &self,
57 request: &mut Request,
58 next: &dyn RequestHandler,
59 ) -> Result<Response, HttpError> {
60 let credentials = request.headers().get(&self.header_name);
61 let token = if credentials.is_none() && self.allow_anonymous {
62 UsernamePasswordToken::anonymous()
63 } else {
64 self.authenticator
65 .authenticate(credentials)
66 .map_err(|err| HttpError::status(401, err.to_string()))?
67 };
68 request.attributes_mut().insert(TOKEN_ATTRIBUTE, token);
69 next.handle(request)
70 }
71}
72
73#[must_use]
75pub fn request_token(request: &Request) -> Option<&UsernamePasswordToken> {
76 request
77 .attributes()
78 .get::<UsernamePasswordToken>(TOKEN_ATTRIBUTE)
79}