use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
pub mod api;
pub mod api_keys;
pub mod auth;
pub mod orgs;
pub mod passkeys;
pub mod posts;
pub mod projects;
pub mod security;
pub mod social;
pub mod well_known;
pub fn email<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
Ok(<String as serde::Deserialize>::deserialize(d)?.trim().to_lowercase())
}
#[derive(Debug)]
pub enum AppError {
Internal(String),
Forbidden(ryuk::gate::Forbidden),
}
impl<E: std::error::Error + 'static> From<E> for AppError {
fn from(e: E) -> Self {
match ryuk::gate::Forbidden::from_error(&e) {
Some(f) => AppError::Forbidden(f),
None => AppError::Internal(e.to_string()),
}
}
}
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AppError::Forbidden(x) => write!(f, "{x}"),
AppError::Internal(detail) => f.write_str(detail),
}
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
match self {
AppError::Forbidden(f) => f.into_response(),
AppError::Internal(detail) => {
tracing::error!(error = %detail, "request failed");
(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
}
}
}
}
#[cfg(test)]
mod tests {
use super::AppError;
use axum::{http::StatusCode, response::IntoResponse};
use ryuk::gate::Forbidden;
fn status<E: std::error::Error + 'static>(e: E) -> StatusCode {
AppError::from(e).into_response().status()
}
#[test]
fn a_denied_gate_keeps_its_403_or_404_through_question_mark() {
assert_eq!(status(Forbidden::new()), StatusCode::FORBIDDEN);
assert_eq!(status(Forbidden::new().deny_as_not_found()), StatusCode::NOT_FOUND);
}
#[test]
fn any_other_error_is_a_500_with_a_fixed_body() {
let e = AppError::from(std::fmt::Error);
assert!(matches!(e, AppError::Internal(_)));
let r = e.into_response();
assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
}