Skip to content

Commit 0c3ca87

Browse files
committed
refactor(api): [#143] remove duplicate code
1 parent 1c72ac0 commit 0c3ca87

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

src/apis/middlewares/auth.rs

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
use std::sync::Arc;
22

33
use axum::extract::{Query, State};
4-
use axum::http::{header, Request, StatusCode};
4+
use axum::http::Request;
55
use axum::middleware::Next;
66
use axum::response::{IntoResponse, Response};
77
use serde::Deserialize;
88

9+
use crate::apis::responses::unhandled_rejection_response;
910
use crate::config::{Configuration, HttpApi};
1011

1112
#[derive(Deserialize, Debug)]
@@ -43,20 +44,23 @@ enum AuthError {
4344

4445
impl IntoResponse for AuthError {
4546
fn into_response(self) -> Response {
46-
let body = match self {
47-
AuthError::Unauthorized => "Unhandled rejection: Err { reason: \"unauthorized\" }",
48-
AuthError::TokenNotValid => "Unhandled rejection: Err { reason: \"token not valid\" }",
49-
};
50-
51-
(
52-
StatusCode::INTERNAL_SERVER_ERROR,
53-
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
54-
body,
55-
)
56-
.into_response()
47+
match self {
48+
AuthError::Unauthorized => unauthorized_response(),
49+
AuthError::TokenNotValid => token_not_valid_response(),
50+
}
5751
}
5852
}
5953

6054
fn authenticate(token: &str, http_api_config: &HttpApi) -> bool {
6155
http_api_config.contains_token(token)
6256
}
57+
58+
#[must_use]
59+
pub fn unauthorized_response() -> Response {
60+
unhandled_rejection_response("unauthorized".to_string())
61+
}
62+
63+
#[must_use]
64+
pub fn token_not_valid_response() -> Response {
65+
unhandled_rejection_response("token not valid".to_string())
66+
}

src/apis/responses.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,10 @@ pub fn failed_to_reload_keys_response() -> Response {
140140
unhandled_rejection_response("failed to reload keys".to_string())
141141
}
142142

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

0 commit comments

Comments
 (0)