summaryrefslogtreecommitdiff
path: root/src/error.rs
blob: 271dc91a3c703c0a19522b700c293f24d37c8612 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use actix_web::http::{header, StatusCode};
use actix_web::{HttpResponse, ResponseError};
use std::fmt::{Display, Formatter};

#[derive(Debug, Copy, Clone)]
pub enum Error {
    MissingToken,
    InvalidToken,
    ConfigurationError,
    IntrospectionServerError,
    AccessDenied,
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Error::AccessDenied => "Access denied",
            Error::MissingToken => "Missing authorization token",
            Error::InvalidToken => "Invalid access token",
            Error::ConfigurationError => "OAuth2 client configuration error",
            Error::IntrospectionServerError => "Introspection endpoint returned an error",
        })
    }
}

impl ResponseError for Error {
    fn status_code(&self) -> StatusCode {
        match self {
            Error::AccessDenied => StatusCode::FORBIDDEN,
            Error::MissingToken => StatusCode::UNAUTHORIZED,
            Error::InvalidToken => StatusCode::UNAUTHORIZED,
            Error::ConfigurationError => StatusCode::INTERNAL_SERVER_ERROR,
            Error::IntrospectionServerError => StatusCode::SERVICE_UNAVAILABLE,
        }
    }

    fn error_response(&self) -> HttpResponse {
        let mut resp = HttpResponse::build(self.status_code());
        match self {
            Error::AccessDenied => {
                resp.insert_header((header::WWW_AUTHENTICATE, "Bearer"));
                resp.body("{\"error\": \"insufficient_scope\"}")
            }
            Error::MissingToken => resp.finish(),
            Error::InvalidToken => {
                resp.insert_header((header::WWW_AUTHENTICATE, "Bearer"));
                resp.body("{\"error\": \"invalid_token\"}")
            }
            Error::ConfigurationError => resp.finish(),
            Error::IntrospectionServerError => resp.finish(),
        }
    }
}