Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#445 mandatory user id extractor #447

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,9 @@ pub enum ServiceError {
#[display(fmt = "Database error.")]
DatabaseError,

#[display(fmt = "Authentication error, please sign in")]
LoggedInUserNotFound,

// Begin tracker errors
#[display(fmt = "Sorry, we have an error with our tracker connection.")]
TrackerOffline,
Expand Down Expand Up @@ -311,6 +314,7 @@ pub fn http_status_code_for_service_error(error: &ServiceError) -> StatusCode {
ServiceError::TrackerUnknownResponse => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::TorrentNotFoundInTracker => StatusCode::NOT_FOUND,
ServiceError::InvalidTrackerToken => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::LoggedInUserNotFound => StatusCode::UNAUTHORIZED,
}
}

Expand Down
1 change: 1 addition & 0 deletions src/web/api/server/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;
37 changes: 37 additions & 0 deletions src/web/api/server/v1/extractors/user_id.rs
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::TokenNotFound.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(_) => Err(ServiceError::LoggedInUserNotFound.into_response()),
}
}
}
Loading