1
use std::fmt;
2

            
3
use axum::{
4
    http::StatusCode,
5
    response::{IntoResponse, Response},
6
};
7
use serde::{Deserialize, Serialize};
8
use serde_json;
9

            
10
use sylvia_iot_corelib::http::Json;
11

            
12
#[derive(Debug, Deserialize, Serialize)]
13
pub struct OAuth2Error {
14
    error: String,
15
    #[serde(skip_serializing_if = "Option::is_none")]
16
    error_description: Option<String>,
17
}
18

            
19
const INVALID_REQUEST: &'static str = "invalid_request";
20

            
21
impl OAuth2Error {
22
46
    pub fn new(error: &str, description: Option<String>) -> Self {
23
46
        OAuth2Error {
24
46
            error: error.to_string(),
25
46
            error_description: description,
26
46
        }
27
46
    }
28

            
29
14
    pub fn new_request(description: Option<String>) -> Self {
30
14
        OAuth2Error {
31
14
            error: INVALID_REQUEST.to_string(),
32
14
            error_description: description,
33
14
        }
34
14
    }
35
}
36

            
37
impl fmt::Display for OAuth2Error {
38
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39
        write!(f, "{}", serde_json::to_string(self).unwrap())
40
    }
41
}
42

            
43
impl IntoResponse for OAuth2Error {
44
14
    fn into_response(self) -> Response {
45
14
        (StatusCode::BAD_REQUEST, Json(self)).into_response()
46
14
    }
47
}