From c2425bd4a4d24e022eb5c2b7d07d6a9585542889 Mon Sep 17 00:00:00 2001 From: Yusuf Bera Ertan Date: Tue, 9 May 2023 07:35:36 +0300 Subject: [PATCH] refactor: separate verify token into its own function --- src/handler.rs | 31 ++----------------------------- src/main.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 29 deletions(-) diff --git a/src/handler.rs b/src/handler.rs index 58fe879..30f8dec 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -153,22 +153,7 @@ async fn generate_scoped_token( Query(query): Query, Path(music_id): Path, ) -> Result { - let maybe_token = query.token; - - 'ok: { - if let Some(token) = maybe_token { - if app.tokens.verify(token).await? { - tracing::debug!("verified token"); - break 'ok; - } - } - tracing::debug!("invalid token"); - return Ok(( - StatusCode::UNAUTHORIZED, - "Invalid token or token not present", - ) - .into_response()); - } + app.verify_token(query.token).await?; // generate token let token = app.scoped_tokens.generate_for_id(music_id).await; @@ -276,19 +261,7 @@ async fn http( .and_then(|auth| extract_password_from_basic_auth(auth).ok()) }); - 'ok: { - if let Some(token) = maybe_token { - if app.tokens.verify(token).await? { - tracing::debug!("verified token"); - break 'ok; - } - } - tracing::debug!("invalid token"); - return Ok(Response::builder() - .status(StatusCode::UNAUTHORIZED) - .body("Invalid token or token not present".to_string().into()) - .expect("cant fail")); - } + app.verify_token(maybe_token).await?; // proxy only the headers we need let headers = { diff --git a/src/main.rs b/src/main.rs index f4d00a2..3eabd82 100644 --- a/src/main.rs +++ b/src/main.rs @@ -174,6 +174,18 @@ impl AppStateInternal { AppError::from("Invalid token or not authorized").status(http::StatusCode::UNAUTHORIZED) }) } + + async fn verify_token(&self, maybe_token: Option>) -> Result<(), AppError> { + if let Some(token) = maybe_token { + if self.tokens.verify(token).await? { + tracing::debug!("verified token"); + return Ok(()); + } + } + tracing::debug!("invalid token"); + Err(AppError::from("Invalid token or token not present") + .status(http::StatusCode::UNAUTHORIZED)) + } } #[derive(Clone, Deserialize, Serialize)]