diff --git a/src/auth.rs b/src/auth.rs index db70723..8a50259 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -3,7 +3,7 @@ use futures::future::BoxFuture; use base64::decode as base64_decode; use tide::{ - http::{response::Builder as ResponseBuilder, StatusCode}, + http::{response::Builder as ResponseBuilder, StatusCode, HeaderValue}, middleware::{Middleware, Next}, Context, Response, }; @@ -49,27 +49,29 @@ impl SimplisticHTTPBasicAuth { impl Middleware for SimplisticHTTPBasicAuth { fn handle<'a>(&'a self, cx: Context, next: Next<'a, State>) -> BoxFuture<'a, Response> { + let credentials = cx.headers().get("Authorization").and_then(|value| { + let (_type, credentials) = parse_authorization(value)?; + if _type.eq_ignore_ascii_case("Basic") { + Some(String::from_utf8(base64_decode(credentials).ok()?).ok()?) + } else { + None + } + }); Box::pin(async move { - let t = cx.headers().get("Authorization").and_then(|value| { - let authorization = value.to_str().ok()?; - let (_type, credentials) = { - // A trailing space is expected to be in `t`. - let (t, c) = authorization.split_at(authorization.find(' ')?); - (t.trim(), c.trim()) - }; - if _type.eq_ignore_ascii_case("Basic") { - Some(String::from_utf8(base64_decode(credentials).ok()?).ok()?) - } else { - None - } - }); - match t { - Some(ref credentials) if self.authenticate(credentials) => { - trace!("An request is authenticated with {} .", credentials); - next.run(cx).await - } - _ => self.unauthorized(), + match credentials { + Some(ref credentials) if self.authenticate(credentials) => { + trace!("An request is authenticated with {} .", credentials); + next.run(cx).await } + _ => self.unauthorized(), + } }) } } + +fn parse_authorization(header_value: &HeaderValue) -> Option<(&str, &str)> { + let value = header_value.to_str().ok()?; + // A trailing space is expected to be in `t`. + let (_type, credentials) = value.split_at(value.find(' ')?); + Some((_type.trim(), credentials.trim())) +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index e016b1e..72fa488 100644 --- a/src/main.rs +++ b/src/main.rs @@ -52,7 +52,9 @@ fn main() { let expiration_task = app_state.expire(); let mut app = App::with_state(app_state); app.middleware(RequestLogger::new()); - app.middleware(HTTPBasicAuth::new()); + if OPT.is_auth_enabled() { + app.middleware(HTTPBasicAuth::new()); + } app.at("/").get(handle_index); app.at("/assets/*path").get(handle_assets); app.at("/upload/start").post(handle_upload_start); diff --git a/src/opt.rs b/src/opt.rs index fdfb0b7..f398f1a 100644 --- a/src/opt.rs +++ b/src/opt.rs @@ -44,6 +44,10 @@ impl Opt { SocketAddr::new(self.ip_addr, self.port) } + pub fn is_auth_enabled(&self) -> bool { + return !self.auth_credentials.is_empty() + } + pub fn credentials_match(&self, credentials: impl AsRef) -> bool { let credentials = credentials.as_ref(); self.auth_credentials.iter().any(|c| c == credentials)