spacegate_kernel/utils/auth/
bearer.rs

1use crate::{BoxError, BoxResult};
2
3use hyper::http::HeaderValue;
4
5use super::Authorization;
6
7#[derive(Debug)]
8pub struct Bearer {
9    pub token: String,
10}
11
12impl Bearer {
13    pub fn new(token: impl Into<String>) -> Self {
14        Self { token: token.into() }
15    }
16    ///
17    /// # Errors
18    ///
19    /// If the token is not a valid header value.
20    pub fn to_header(&self) -> BoxResult<hyper::http::HeaderValue> {
21        Ok(hyper::http::HeaderValue::from_str(&format!("Bearer {}", self.token))?)
22    }
23}
24
25impl From<Bearer> for Authorization<Bearer> {
26    fn from(val: Bearer) -> Self {
27        Authorization(val)
28    }
29}
30
31impl From<Authorization<Bearer>> for Bearer {
32    fn from(val: Authorization<Self>) -> Self {
33        val.0
34    }
35}
36
37impl TryFrom<HeaderValue> for Bearer {
38    type Error = BoxError;
39    fn try_from(header: HeaderValue) -> Result<Self, Self::Error> {
40        if let Ok(header) = header.to_str() {
41            if let Some(token) = header.strip_prefix("Bearer ") {
42                Ok(Bearer::new(token))
43            } else {
44                Err("auth header value is not a bearer auth value".into())
45            }
46        } else {
47            Err("auth header value is not a valid string".into())
48        }
49    }
50}
51
52impl TryInto<HeaderValue> for &Bearer {
53    type Error = BoxError;
54    fn try_into(self) -> Result<HeaderValue, Self::Error> {
55        self.to_header()
56    }
57}
58
59impl std::fmt::Display for Bearer {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        write!(f, "Bearer {}", self.token)
62    }
63}