diff --git a/src/web/api/v1/auth.rs b/src/web/api/v1/auth.rs index 545e3054..e93f642c 100644 --- a/src/web/api/v1/auth.rs +++ b/src/web/api/v1/auth.rs @@ -78,9 +78,15 @@ //! "data": "new category" //! } //! ``` +use std::sync::Arc; use hyper::http::HeaderValue; +use crate::common::AppData; +use crate::errors::ServiceError; +use crate::models::user::UserId; +use crate::web::api::v1::extractors::bearer_token::BearerToken; + /// Parses the token from the `Authorization` header. pub fn parse_token(authorization: &HeaderValue) -> String { let split: Vec<&str> = authorization @@ -91,3 +97,21 @@ pub fn parse_token(authorization: &HeaderValue) -> String { let token = split[1].trim(); token.to_string() } + +/// If the user is logged in, returns the user's ID. Otherwise, returns `None`. +/// +/// # Errors +/// +/// It returns an error if we cannot get the user from the bearer token. +pub async fn get_optional_logged_in_user( + maybe_bearer_token: Option, + app_data: Arc, +) -> Result, ServiceError> { + match maybe_bearer_token { + Some(bearer_token) => match app_data.auth.get_user_id_from_bearer_token(&Some(bearer_token)).await { + Ok(user_id) => Ok(Some(user_id)), + Err(error) => Err(error), + }, + None => Ok(None), + } +} diff --git a/src/web/api/v1/contexts/torrent/handlers.rs b/src/web/api/v1/contexts/torrent/handlers.rs index 6133f9bf..df518170 100644 --- a/src/web/api/v1/contexts/torrent/handlers.rs +++ b/src/web/api/v1/contexts/torrent/handlers.rs @@ -16,11 +16,11 @@ use crate::errors::ServiceError; use crate::models::info_hash::InfoHash; use crate::models::torrent::TorrentRequest; use crate::models::torrent_tag::TagId; -use crate::models::user::UserId; use crate::routes::torrent::Create; use crate::services::torrent::ListingRequest; use crate::utils::parse_torrent; -use crate::web::api::v1::extractors::bearer_token::{BearerToken, Extract}; +use crate::web::api::v1::auth::get_optional_logged_in_user; +use crate::web::api::v1::extractors::bearer_token::Extract; use crate::web::api::v1::responses::OkResponseData; /// Upload a new torrent file to the Index @@ -198,24 +198,6 @@ pub async fn delete_torrent_handler( } } -/// If the user is logged in, returns the user's ID. Otherwise, returns `None`. -/// -/// # Errors -/// -/// It returns an error if we cannot get the user from the bearer token. -async fn get_optional_logged_in_user( - maybe_bearer_token: Option, - app_data: Arc, -) -> Result, ServiceError> { - match maybe_bearer_token { - Some(bearer_token) => match app_data.auth.get_user_id_from_bearer_token(&Some(bearer_token)).await { - Ok(user_id) => Ok(Some(user_id)), - Err(error) => Err(error), - }, - None => Ok(None), - } -} - /// Extracts the [`TorrentRequest`] from the multipart form payload. /// /// # Errors