|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use async_trait::async_trait; |
| 4 | +use axum::extract::{FromRef, FromRequestParts}; |
| 5 | +use axum::http::request::Parts; |
| 6 | +use axum::response::{ Response}; |
| 7 | + |
| 8 | +use crate::common::AppData; |
| 9 | +use crate::models::user::UserId; |
| 10 | +use crate::web::api::server::v1::extractors::bearer_token; |
| 11 | + |
| 12 | +pub struct ExtractOptionalLoggedInUser(pub Option<UserId>); |
| 13 | + |
| 14 | +#[async_trait] |
| 15 | +impl<S> FromRequestParts<S> for ExtractOptionalLoggedInUser |
| 16 | + where |
| 17 | + Arc<AppData>: FromRef<S>, |
| 18 | + S: Send + Sync, |
| 19 | +{ |
| 20 | + type Rejection = Response; |
| 21 | + |
| 22 | + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { |
| 23 | + /* let maybe_bearer_token = match bearer_token::Extract::from_request_parts(parts, state).await { |
| 24 | + Ok(maybe_bearer_token) => maybe_bearer_token.0, |
| 25 | + Err(_) => return Err(ServiceError::TokenNotFound.into_response()), |
| 26 | + }; */ |
| 27 | + |
| 28 | + let bearer_token = match bearer_token::Extract::from_request_parts(parts, state).await { |
| 29 | + Ok(bearer_token) => bearer_token.0, |
| 30 | + Err(_) => None |
| 31 | + }; |
| 32 | + |
| 33 | + //Extracts the app state |
| 34 | + let app_data = Arc::from_ref(state); |
| 35 | + |
| 36 | + match app_data.auth.get_user_id_from_bearer_token(&bearer_token).await { |
| 37 | + Ok(user_id) => Ok(ExtractOptionalLoggedInUser(Some(user_id))), |
| 38 | + Err(_) => Ok(ExtractOptionalLoggedInUser(None)), |
| 39 | + } |
| 40 | + } |
| 41 | +} |
0 commit comments