Skip to content

Commit

Permalink
feat: [39] new extractor for getting the user_id
Browse files Browse the repository at this point in the history
  • Loading branch information
mario-nt committed Nov 30, 2023
1 parent 644d33a commit da8e2ea
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/web/api/v1/extractors/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod bearer_token;
pub mod user_id;
51 changes: 51 additions & 0 deletions src/web/api/v1/extractors/user_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use std::sync::Arc;

use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};
use serde::Deserialize;
use tokio::sync::RwLock;

use super::bearer_token;
use crate::services;
use crate::web::api::v1::auth::{self, Authentication};

pub struct ExtractLoggedInUser(pub Option<UserId>);

#[derive(Deserialize, Debug)]
pub struct UserId(i64);

impl UserId {
#[must_use]
pub fn value(&self) -> i64 {
self.0
}
}

#[async_trait]
impl<S> FromRequestParts<S> for ExtractLoggedInUser
where
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(_) => None,
};

let bearer_token = services::authentication::JsonWebToken::new(Arc::new(crate::config::Configuration {
settings: RwLock::default(),
config_path: Option::default(),
}));

let auth: Authentication = auth::Authentication::new(Arc::new(bearer_token));

match auth.get_user_id_from_bearer_token(&maybe_bearer_token).await {
Ok(user_id) => Ok(ExtractLoggedInUser(Some(UserId(user_id)))),
Err(error) => return Err(error.into_response()),
}
}
}

0 comments on commit da8e2ea

Please sign in to comment.