firebase_auth/
axum_feature.rs1use std::sync::Arc;
2
3use axum::{
4 extract::{FromRef, FromRequestParts},
5 http::{self, request::Parts, StatusCode},
6 response::{IntoResponse, Response},
7};
8use tracing::debug;
9
10use crate::{FirebaseAuth, FirebaseUser};
11
12#[derive(Clone)]
13pub struct FirebaseAuthState {
14 pub firebase_auth: Arc<FirebaseAuth>,
15}
16
17impl FirebaseAuthState {
18 pub fn new(firebase_auth: FirebaseAuth) -> Self {
19 Self {
20 firebase_auth: Arc::new(firebase_auth),
21 }
22 }
23}
24
25fn get_bearer_token(header: &str) -> Option<String> {
26 let prefix_len = "Bearer ".len();
27
28 match header.len() {
29 l if l < prefix_len => None,
30 _ => Some(header[prefix_len..].to_string()),
31 }
32}
33
34impl<S> FromRequestParts<S> for FirebaseUser
35where
36 FirebaseAuthState: FromRef<S>,
37 S: Send + Sync,
38{
39 type Rejection = UnauthorizedResponse;
40
41 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
42 let store = FirebaseAuthState::from_ref(state);
43
44 let auth_header = parts
45 .headers
46 .get(http::header::AUTHORIZATION)
47 .and_then(|value| value.to_str().ok())
48 .unwrap_or("");
49
50 let bearer = get_bearer_token(auth_header).map_or(
51 Err(UnauthorizedResponse {
52 msg: "Missing Bearer Token".to_string(),
53 }),
54 Ok,
55 )?;
56
57 debug!("Got bearer token {}", bearer);
58
59 match store.firebase_auth.verify(&bearer) {
60 Err(e) => Err(UnauthorizedResponse {
61 msg: format!("Failed to verify Token: {}", e),
62 }),
63 Ok(current_user) => Ok(current_user),
64 }
65 }
66}
67
68pub struct UnauthorizedResponse {
69 msg: String,
70}
71
72impl IntoResponse for UnauthorizedResponse {
73 fn into_response(self) -> Response {
74 (StatusCode::UNAUTHORIZED, self.msg).into_response()
75 }
76}