spacegate_kernel/utils/
auth.rs

1pub mod basic;
2pub mod bearer;
3use hyper::{header::AUTHORIZATION, http::HeaderValue};
4
5use crate::{extractor::OptionalExtract, injector::Inject, BoxError, BoxResult, SgRequest};
6#[derive(Debug, Clone)]
7pub struct Authorization<A>(pub A);
8
9impl<A> Authorization<A> {
10    pub fn new(auth: A) -> Self {
11        Self(auth)
12    }
13}
14
15impl<A> OptionalExtract for Authorization<A>
16where
17    A: TryFrom<HeaderValue> + Send + Sync + 'static,
18    A::Error: Into<BoxError>,
19{
20    fn extract(req: &SgRequest) -> Option<Self> {
21        let auth = req.headers().get(AUTHORIZATION)?.clone();
22        let auth = A::try_from(auth).ok()?;
23        Some(Self(auth))
24    }
25}
26
27impl<A> Inject for Authorization<A>
28where
29    for<'a> &'a A: TryInto<HeaderValue> + Send + Sync,
30    for<'a> <&'a A as TryInto<HeaderValue>>::Error: Into<BoxError>,
31{
32    fn inject(&self, req: &mut SgRequest) -> BoxResult<()> {
33        req.headers_mut().insert(AUTHORIZATION, (&self.0).try_into().map_err(Into::into)?);
34        Ok(())
35    }
36}