diff options
Diffstat (limited to 'src/auth.rs')
-rw-r--r-- | src/auth.rs | 41 |
1 files changed, 39 insertions, 2 deletions
diff --git a/src/auth.rs b/src/auth.rs index b1ad76d..b7693a0 100644 --- a/src/auth.rs +++ b/src/auth.rs | |||
@@ -1,3 +1,40 @@ | |||
1 | pub fn auth(secret: &str) -> bool { | 1 | use std::error::Error; |
2 | secret == "aaa" | 2 | use axum::headers::HeaderValue; |
3 | use axum::http::StatusCode; | ||
4 | use tracing::error; | ||
5 | use crate::auth::AuthError::{MissingSecret, ServerError, WrongSecret}; | ||
6 | use crate::config::SETTINGS; | ||
7 | |||
8 | pub fn auth(secret: Option<&HeaderValue>) -> Result<bool, AuthError> { | ||
9 | if let Some(value) = secret { | ||
10 | let key = SETTINGS | ||
11 | .get_string("apikey") | ||
12 | .map_err(|err| ServerError(Box::new(err)))?; | ||
13 | if value.to_str().map_err(|err| ServerError(Box::new(err)))? == key.as_str() { | ||
14 | Ok(true) | ||
15 | } else { | ||
16 | Err(WrongSecret) | ||
17 | } | ||
18 | } else { | ||
19 | Err(MissingSecret) | ||
20 | } | ||
3 | } | 21 | } |
22 | |||
23 | pub enum AuthError { | ||
24 | WrongSecret, | ||
25 | MissingSecret, | ||
26 | ServerError(Box<dyn Error>), | ||
27 | } | ||
28 | |||
29 | impl AuthError { | ||
30 | pub fn get(self) -> (StatusCode, &'static str) { | ||
31 | match self { | ||
32 | AuthError::WrongSecret => (StatusCode::UNAUTHORIZED, "Wrong credentials"), | ||
33 | AuthError::MissingSecret => (StatusCode::BAD_REQUEST, "Missing credentials"), | ||
34 | AuthError::ServerError(err) => { | ||
35 | error!("server error: {}", err.to_string()); | ||
36 | (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") | ||
37 | }, | ||
38 | } | ||
39 | } | ||
40 | } \ No newline at end of file | ||