Skip to main content

openleadr_wire/
oauth.rs

1use serde::{Deserialize, Serialize};
2use url::Url;
3use validator::{Validate, ValidateLength, ValidationErrors};
4
5#[derive(Debug, serde::Serialize, serde::Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum OAuthErrorType {
8    OAuthNotEnabled,
9    InvalidRequest,
10    InvalidClient,
11    InvalidSubject,
12    InvalidGrant,
13    // UnauthorizedClient,
14    UnsupportedGrantType,
15    // InvalidScope,
16    ServerError,
17    NoAvailableKeys,
18    /// nbf claim set to a later time than 'now'
19    NotYetValid,
20    /// exp claim > now
21    Expired,
22}
23
24#[derive(Debug, serde::Serialize, serde::Deserialize)]
25pub struct OAuthError {
26    pub error: OAuthErrorType,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub error_description: Option<String>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub error_uri: Option<String>,
31}
32
33impl OAuthError {
34    pub fn new(error: OAuthErrorType) -> Self {
35        Self {
36            error,
37            error_description: None,
38            error_uri: None,
39        }
40    }
41
42    pub fn with_description(mut self, description: String) -> Self {
43        self.error_description = Some(description);
44        self
45    }
46
47    pub fn with_uri(mut self, uri: String) -> Self {
48        self.error_uri = Some(uri);
49        self
50    }
51}
52
53#[derive(Debug, Serialize, Deserialize)]
54pub struct AuthServerInfo {
55    #[serde(rename = "tokenURL")]
56    pub token_url: Url,
57}
58
59impl Validate for AuthServerInfo {
60    fn validate(&self) -> Result<(), ValidationErrors> {
61        if self
62            .token_url
63            .as_str()
64            .validate_length(Some(2), Some(8000), None)
65        {
66            return Ok(());
67        }
68
69        let mut err = ::validator::ValidationError::new("length");
70        err.add_param(::std::borrow::Cow::from("min"), &2);
71        err.add_param(::std::borrow::Cow::from("max"), &8000);
72        err.add_param(::std::borrow::Cow::from("value"), &self.token_url);
73
74        let mut errors = ValidationErrors::new();
75        errors.add("token_url", err);
76        Err(errors)
77    }
78}