1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use axum::{
    async_trait,
    extract::{FromRef, FromRequestParts},
    http::{self, request::Parts, StatusCode},
    response::{IntoResponse, Response},
};

use crate::{FirebaseAuth, FirebaseUser};

#[derive(Clone)]
pub struct FirebaseAuthState {
    pub firebase_auth: FirebaseAuth,
}

impl FromRef<FirebaseAuthState> for FirebaseAuth {
    fn from_ref(state: &FirebaseAuthState) -> Self {
        state.firebase_auth.clone()
    }
}

fn get_bearer_token(header: &str) -> Option<String> {
    let prefix_len = "Bearer ".len();

    match header.len() {
        l if l < prefix_len => None,
        _ => Some(header[prefix_len..].to_string()),
    }
}

#[async_trait]
impl<S> FromRequestParts<S> for FirebaseUser
where
    FirebaseAuthState: FromRef<S>,
    S: Send + Sync,
{
    type Rejection = UnauthorizedResponse;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let store = FirebaseAuthState::from_ref(state);

        let auth_header = parts
            .headers
            .get(http::header::AUTHORIZATION)
            .and_then(|value| value.to_str().ok())
            .unwrap_or("");

        let bearer = get_bearer_token(auth_header);
        let bearer = if let Some(bearer) = bearer {
            bearer
        } else {
            return Err(UnauthorizedResponse {
                msg: "Missing Bearer Token".to_string(),
            });
        };

        match store.firebase_auth.verify(&bearer) {
            None => Err(UnauthorizedResponse {
                msg: "Failed to verify Token".to_string(),
            }),
            Some(current_user) => Ok(current_user),
        }
    }
}

pub struct UnauthorizedResponse {
    msg: String,
}

impl IntoResponse for UnauthorizedResponse {
    fn into_response(self) -> Response {
        (StatusCode::UNAUTHORIZED, self.msg).into_response()
    }
}