From 578c4e237f15aa18ecbf9eeba26a6755263171e9 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Sat, 10 Feb 2024 12:23:20 +0000 Subject: [PATCH] Allow converting AuthenticationError to ApiError --- src/server.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/server.rs b/src/server.rs index bbb9e3c..9d3fe9f 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,11 +1,14 @@ use axum::{ extract::Query, + http::StatusCode, + response::IntoResponse, routing::{get, post}, Form, Json, Router, }; use serde::{Deserialize, Serialize}; use tracing::{event, instrument, Level}; +use crate::auth::AuthenticationError; use crate::secrets::Password; #[instrument] @@ -21,11 +24,29 @@ pub async fn run() -> color_eyre::Result<()> { #[derive(Debug, Clone, PartialEq, Eq, Serialize)] struct ApiError { + #[serde(skip_serializing)] + status: StatusCode, error: String, message: String, } -type ApiResult = Result>; +impl From for ApiError { + fn from(err: AuthenticationError) -> Self { + Self { + status: StatusCode::UNAUTHORIZED, + error: "authentication-failed".to_owned(), + message: err.to_string(), + } + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> axum::response::Response { + (self.status, Json(self)).into_response() + } +} + +type ApiResult = Result; #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] struct ApiVersion {