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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//! https://datatracker.ietf.org/doc/html/rfc8628#section-3.2

use std::time::Duration;

use mime::Mime;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use url::Url;

pub const CONTENT_TYPE: Mime = mime::APPLICATION_JSON;
pub const INTERVAL_DEFAULT: usize = 5;
pub type DeviceCode = String;
pub type UserCode = String;
pub type VerificationUri = Url;
pub type VerificationUriComplete = Url;

//
//
//
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SuccessfulBody {
    pub device_code: DeviceCode,
    pub user_code: UserCode,
    // e.g. google
    #[serde(alias = "verification_url")]
    pub verification_uri: VerificationUri,
    #[serde(
        alias = "verification_url_complete",
        skip_serializing_if = "Option::is_none"
    )]
    pub verification_uri_complete: Option<VerificationUriComplete>,
    pub expires_in: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<usize>,

    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    _extra: Option<Map<String, Value>>,
}

impl SuccessfulBody {
    pub fn new(
        device_code: DeviceCode,
        user_code: UserCode,
        verification_uri: VerificationUri,
        verification_uri_complete: Option<VerificationUriComplete>,
        expires_in: usize,
        interval: Option<usize>,
    ) -> Self {
        Self {
            device_code,
            user_code,
            verification_uri,
            verification_uri_complete,
            expires_in,
            interval,
            _extra: None,
        }
    }

    pub fn interval(&self) -> Duration {
        Duration::from_secs(self.interval.unwrap_or(INTERVAL_DEFAULT) as u64)
    }

    pub fn set_extra(&mut self, extra: Map<String, Value>) {
        self._extra = Some(extra);
    }
    pub fn extra(&self) -> Option<&Map<String, Value>> {
        self._extra.as_ref()
    }
}

//
//
//
pub type ErrorBody = crate::access_token_response::ErrorBody;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn de() {
        let body_str = r#"
        {
            "device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS",
            "user_code": "WDJB-MJHT",
            "verification_uri": "https://example.com/device",
            "verification_uri_complete":
                "https://example.com/device?user_code=WDJB-MJHT",
            "expires_in": 1800,
            "interval": 5
        }
        "#;
        match serde_json::from_str::<SuccessfulBody>(body_str) {
            Ok(_) => {}
            Err(err) => panic!("{}", err),
        }
    }
}