Skip to main content

idprova_middleware/
error.rs

1use axum::{
2    http::StatusCode,
3    response::{IntoResponse, Json, Response},
4};
5use serde_json::json;
6
7/// Errors from DAT middleware verification.
8#[derive(Debug)]
9pub enum DatMiddlewareError {
10    /// 401 — missing, empty, or invalid token.
11    Unauthorized(String),
12    /// 403 — valid token but insufficient scope.
13    Forbidden(String),
14}
15
16impl DatMiddlewareError {
17    pub fn unauthorized(msg: impl Into<String>) -> Self {
18        Self::Unauthorized(msg.into())
19    }
20
21    pub fn forbidden(msg: impl Into<String>) -> Self {
22        Self::Forbidden(msg.into())
23    }
24}
25
26impl IntoResponse for DatMiddlewareError {
27    fn into_response(self) -> Response {
28        match self {
29            Self::Unauthorized(msg) => (
30                StatusCode::UNAUTHORIZED,
31                Json(json!({ "error": msg, "code": "unauthorized" })),
32            )
33                .into_response(),
34            Self::Forbidden(msg) => (
35                StatusCode::FORBIDDEN,
36                Json(json!({ "error": msg, "code": "forbidden" })),
37            )
38                .into_response(),
39        }
40    }
41}