Skip to content

Commit

Permalink
refactor(api): [#143] remove duplicate code
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Jan 13, 2023
1 parent 1c72ac0 commit 0c3ca87
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
28 changes: 16 additions & 12 deletions src/apis/middlewares/auth.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::sync::Arc;

use axum::extract::{Query, State};
use axum::http::{header, Request, StatusCode};
use axum::http::Request;
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use serde::Deserialize;

use crate::apis::responses::unhandled_rejection_response;
use crate::config::{Configuration, HttpApi};

#[derive(Deserialize, Debug)]
Expand Down Expand Up @@ -43,20 +44,23 @@ enum AuthError {

impl IntoResponse for AuthError {
fn into_response(self) -> Response {
let body = match self {
AuthError::Unauthorized => "Unhandled rejection: Err { reason: \"unauthorized\" }",
AuthError::TokenNotValid => "Unhandled rejection: Err { reason: \"token not valid\" }",
};

(
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
body,
)
.into_response()
match self {
AuthError::Unauthorized => unauthorized_response(),
AuthError::TokenNotValid => token_not_valid_response(),
}
}
}

fn authenticate(token: &str, http_api_config: &HttpApi) -> bool {
http_api_config.contains_token(token)
}

#[must_use]
pub fn unauthorized_response() -> Response {
unhandled_rejection_response("unauthorized".to_string())
}

#[must_use]
pub fn token_not_valid_response() -> Response {
unhandled_rejection_response("token not valid".to_string())
}
5 changes: 4 additions & 1 deletion src/apis/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,10 @@ pub fn failed_to_reload_keys_response() -> Response {
unhandled_rejection_response("failed to reload keys".to_string())
}

fn unhandled_rejection_response(reason: String) -> Response {
/// This error response is to keep backward compatibility with the old Warp API.
/// It should be a plain text or json.
#[must_use]
pub fn unhandled_rejection_response(reason: String) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
Expand Down

0 comments on commit 0c3ca87

Please sign in to comment.