1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-08-10 15:23:07 +03:00

Simplify error handling in user-facing routes

This commit is contained in:
Quentin Gliech
2022-05-10 16:51:12 +02:00
parent 2cba5e7ad2
commit ca7b26cf18
17 changed files with 192 additions and 383 deletions

View File

@@ -12,92 +12,32 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{convert::Infallible, error::Error};
use async_trait::async_trait;
use axum::{
body::{HttpBody, StreamBody},
extract::{Extension, FromRequest, RequestParts},
http::StatusCode,
response::{IntoResponse, Response},
Extension,
};
use futures_util::FutureExt;
use headers::{ContentType, HeaderMapExt};
use mas_templates::{ErrorContext, Templates};
use sqlx::PgPool;
struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Postgres>);
#[async_trait]
impl<B> FromRequest<B> for DatabaseConnection
where
B: Send,
{
type Rejection = FancyError;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let Extension(templates) = Extension::<Templates>::from_request(req)
.await
.map_err(internal_error)?;
let Extension(pool) = Extension::<PgPool>::from_request(req)
.await
.map_err(fancy_error(templates))?;
let conn = pool.acquire().await.map_err(internal_error)?;
Ok(Self(conn))
}
}
pub fn fancy_error<E: std::fmt::Display + 'static>(
templates: Templates,
) -> impl Fn(E) -> FancyError {
move |error: E| FancyError {
templates: Some(templates.clone()),
error: Box::new(error),
}
}
pub fn internal_error<E: Error + 'static>(error: E) -> FancyError
where
E: Error,
{
FancyError {
templates: None,
error: Box::new(error),
}
}
use mas_templates::ErrorContext;
pub struct FancyError {
templates: Option<Templates>,
error: Box<dyn std::fmt::Display>,
context: ErrorContext,
}
impl<E: std::fmt::Display> From<E> for FancyError {
fn from(err: E) -> Self {
let context = ErrorContext::new().with_description(err.to_string());
FancyError { context }
}
}
impl IntoResponse for FancyError {
fn into_response(self) -> Response {
let error = format!("{}", self.error);
let context = ErrorContext::new().with_description(error.clone());
let body = match self.templates {
Some(templates) => {
let stream = (async move {
Ok::<_, Infallible>(match templates.render_error(&context).await {
Ok(s) => s,
Err(_e) => "failed to render error template".to_string(),
})
})
.into_stream();
StreamBody::new(stream).boxed_unsync()
}
None => axum::body::Full::from(error)
.map_err(|_e| unreachable!())
.boxed_unsync(),
};
let mut res = Response::new(body);
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
res.headers_mut().typed_insert(ContentType::html());
res
let error = format!("{:?}", self.context);
(
StatusCode::INTERNAL_SERVER_ERROR,
Extension(self.context),
error,
)
.into_response()
}
}

View File

@@ -21,6 +21,6 @@ pub mod user_authorization;
pub use self::{
cookies::CookieExt,
fancy_error::{fancy_error, internal_error, FancyError},
fancy_error::FancyError,
session::{SessionInfo, SessionInfoExt},
};

View File

@@ -32,6 +32,7 @@ use mas_storage::{
};
use serde::{de::DeserializeOwned, Deserialize};
use sqlx::{Acquire, Postgres};
use thiserror::Error;
#[derive(Debug, Deserialize)]
struct AuthorizedForm<F> {
@@ -111,10 +112,18 @@ pub enum UserAuthorizationError {
InternalError(Box<dyn Error>),
}
#[derive(Debug, Error)]
pub enum AuthorizationVerificationError {
#[error("missing token")]
MissingToken,
#[error("invalid token")]
InvalidToken,
#[error("missing form")]
MissingForm,
#[error(transparent)]
InternalError(Box<dyn Error>),
}