at_jet/middleware/
auth.rs1use {axum::{http::Request,
4 middleware::Next,
5 response::Response},
6 std::{future::Future,
7 pin::Pin,
8 task::{Context,
9 Poll}},
10 tower::{Layer,
11 Service}};
12
13#[derive(Clone)]
18pub struct AuthLayer;
19
20impl<S> Layer<S> for AuthLayer {
21 type Service = AuthMiddleware<S>;
22
23 fn layer(&self, inner: S) -> Self::Service {
24 AuthMiddleware { inner }
25 }
26}
27
28#[derive(Clone)]
30pub struct AuthMiddleware<S> {
31 inner: S,
32}
33
34impl<S, ReqBody> Service<Request<ReqBody>> for AuthMiddleware<S>
35where
36 S: Service<Request<ReqBody>, Response = Response> + Clone + Send + 'static,
37 S::Future: Send,
38 ReqBody: Send + 'static,
39{
40 type Error = S::Error;
41 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
42 type Response = S::Response;
43
44 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
45 self.inner.poll_ready(cx)
46 }
47
48 fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
49 let mut inner = self.inner.clone();
50
51 Box::pin(async move {
52 inner.call(req).await
63 })
64 }
65}
66
67pub async fn validate_bearer_token(
69 req: Request<axum::body::Body>,
70 next: Next,
71) -> Result<Response, axum::http::StatusCode> {
72 let auth_header = req.headers().get("Authorization").and_then(|h| h.to_str().ok());
73
74 match auth_header {
75 | Some(header) if header.starts_with("Bearer ") => {
76 let _token = &header[7 ..];
77 Ok(next.run(req).await)
79 }
80 | _ => Err(axum::http::StatusCode::UNAUTHORIZED),
81 }
82}