forked from torrust/torrust-index
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: [torrust#445] new user id extractor
- Loading branch information
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
pub mod bearer_token; | ||
pub mod user_id; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
use std::sync::Arc; | ||
|
||
use async_trait::async_trait; | ||
use axum::extract::{FromRef, FromRequestParts}; | ||
use axum::http::request::Parts; | ||
use axum::response::{IntoResponse, Response}; | ||
|
||
use super::bearer_token; | ||
use crate::common::AppData; | ||
use crate::errors::ServiceError; | ||
use crate::models::user::UserId; | ||
|
||
pub struct ExtractLoggedInUser(pub UserId); | ||
|
||
#[async_trait] | ||
impl<S> FromRequestParts<S> for ExtractLoggedInUser | ||
where | ||
Arc<AppData>: FromRef<S>, | ||
S: Send + Sync, | ||
{ | ||
type Rejection = Response; | ||
|
||
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | ||
let maybe_bearer_token = match bearer_token::Extract::from_request_parts(parts, state).await { | ||
Ok(maybe_bearer_token) => maybe_bearer_token.0, | ||
Err(_) => return Err(ServiceError::Unauthorized.into_response()), | ||
}; | ||
|
||
//Extracts the app state | ||
let app_data = Arc::from_ref(state); | ||
|
||
match app_data.auth.get_user_id_from_bearer_token(&maybe_bearer_token).await { | ||
Ok(user_id) => Ok(ExtractLoggedInUser(user_id)), | ||
Err(error) => Err(error.into_response()), | ||
} | ||
} | ||
} |