actix_middleware_rfc7662/
error.rs

1use actix_web::http::{header, StatusCode};
2use actix_web::{HttpResponse, ResponseError};
3use std::fmt::{Display, Formatter};
4
5#[derive(Debug, Copy, Clone)]
6pub enum Error {
7    MissingToken,
8    InvalidToken,
9    ConfigurationError,
10    IntrospectionServerError,
11    AccessDenied,
12}
13
14impl Display for Error {
15    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
16        f.write_str(match self {
17            Error::AccessDenied => "Access denied",
18            Error::MissingToken => "Missing authorization token",
19            Error::InvalidToken => "Invalid access token",
20            Error::ConfigurationError => "OAuth2 client configuration error",
21            Error::IntrospectionServerError => "Introspection endpoint returned an error",
22        })
23    }
24}
25
26impl ResponseError for Error {
27    fn status_code(&self) -> StatusCode {
28        match self {
29            Error::AccessDenied => StatusCode::FORBIDDEN,
30            Error::MissingToken => StatusCode::UNAUTHORIZED,
31            Error::InvalidToken => StatusCode::UNAUTHORIZED,
32            Error::ConfigurationError => StatusCode::INTERNAL_SERVER_ERROR,
33            Error::IntrospectionServerError => StatusCode::SERVICE_UNAVAILABLE,
34        }
35    }
36
37    fn error_response(&self) -> HttpResponse {
38        let mut resp = HttpResponse::build(self.status_code());
39        match self {
40            Error::AccessDenied => {
41                resp.insert_header((header::WWW_AUTHENTICATE, "Bearer"));
42                resp.body("{\"error\": \"insufficient_scope\"}")
43            }
44            Error::MissingToken => resp.finish(),
45            Error::InvalidToken => {
46                resp.insert_header((header::WWW_AUTHENTICATE, "Bearer"));
47                resp.body("{\"error\": \"invalid_token\"}")
48            }
49            Error::ConfigurationError => resp.finish(),
50            Error::IntrospectionServerError => resp.finish(),
51        }
52    }
53}