WWW-Authenticate header

This commit is contained in:
Igor Katson 2024-11-20 17:29:21 +00:00
parent 3e8a39314b
commit 6213481732
No known key found for this signature in database
GPG key ID: B4EC22B66D61A3F5
2 changed files with 15 additions and 2 deletions

View file

@ -56,7 +56,11 @@ impl ApiError {
}
pub const fn unathorized() -> Self {
Self::new_from_text(StatusCode::UNAUTHORIZED, "unauthorized")
Self {
status: Some(StatusCode::UNAUTHORIZED),
kind: ApiErrorKind::Unauthorized,
plaintext: true,
}
}
pub fn status(&self) -> StatusCode {
@ -84,6 +88,7 @@ impl ApiError {
enum ApiErrorKind {
TorrentNotFound(TorrentIdOrHash),
DhtDisabled,
Unauthorized,
Text(&'static str),
Other(anyhow::Error),
}
@ -106,6 +111,7 @@ impl Serialize for ApiError {
error_kind: match self.kind {
ApiErrorKind::TorrentNotFound(_) => "torrent_not_found",
ApiErrorKind::DhtDisabled => "dht_disabled",
ApiErrorKind::Unauthorized => "unathorized",
ApiErrorKind::Other(_) => "internal_error",
ApiErrorKind::Text(_) => "internal_error",
},
@ -146,6 +152,7 @@ impl std::fmt::Display for ApiError {
match &self.kind {
ApiErrorKind::TorrentNotFound(idx) => write!(f, "torrent {idx} not found"),
ApiErrorKind::Other(err) => write!(f, "{err:?}"),
ApiErrorKind::Unauthorized => write!(f, "unathorized"),
ApiErrorKind::DhtDisabled => write!(f, "DHT is disabled"),
ApiErrorKind::Text(t) => write!(f, "{t}"),
}

View file

@ -67,7 +67,13 @@ async fn simple_basic_auth(
.and_then(|v| String::from_utf8(v).ok());
let user_pass = match user_pass {
Some(user_pass) => user_pass,
None => return Err(ApiError::unathorized()),
None => {
return Ok((
StatusCode::UNAUTHORIZED,
[("WWW-Authenticate", "Basic realm=\"API\"")],
)
.into_response())
}
};
// TODO: constant time compare
match user_pass.split_once(':') {