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
92
    pub fn new(error: &str, description: Option<String>) -> Self {
23
92
        OAuth2Error {
24
92
            error: error.to_string(),
25
92
            error_description: description,
26
92
        }
27
92
    }
28

            
29
28
    pub fn new_request(description: Option<String>) -> Self {
30
28
        OAuth2Error {
31
28
            error: INVALID_REQUEST.to_string(),
32
28
            error_description: description,
33
28
        }
34
28
    }
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
28
    fn into_response(self) -> Response {
45
28
        (StatusCode::BAD_REQUEST, Json(self)).into_response()
46
28
    }
47
}