Skip to main content

zulip_api/message/fetch_api_key/
response.rs

1use serde::{Deserialize, Serialize};
2use zeroize::Zeroize;
3
4use crate::response::BaseResponse;
5use crate::{field_access, impl_default, impl_display, impl_response};
6
7/// Represents a response from the `Fetch API Key` Zulip endpoint.
8///
9/// Allows third-party applications to use a username-password authentication method.
10#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, Zeroize)]
11pub struct Response {
12    #[serde(flatten)]
13    base: BaseResponse,
14    api_key: Option<String>,
15    email: Option<String>,
16    user_id: Option<i64>,
17}
18
19impl Response {
20    /// Creates a new [Self].
21    pub const fn new() -> Self {
22        Self {
23            base: BaseResponse::new(),
24            api_key: None,
25            email: None,
26            user_id: None,
27        }
28    }
29}
30
31field_access! {
32    Response {
33        /// The API key that can be used to authenticate as the requested user.
34        api_key: option_cow_deref { str, String },
35        /// The email address of the user who owns the API key.
36        email: option_cow_deref { str, String },
37    }
38}
39
40field_access! {
41    Response {
42        /// The unique ID of the user who owns the API key.
43        ///
44        /// **Changes**: New in Zulip 7.0 (feature level 171).
45        user_id: option { i64 },
46    }
47}
48
49impl_default!(Response);
50impl_display!(Response);
51impl_response!(Response, base);
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_response() {
59        let api_key = "someLongApiKey";
60        let api_key_json = serde_json::to_string(&api_key).unwrap();
61
62        let email = "test_user@zulip.server";
63        let email_json = serde_json::to_string(&email).unwrap();
64
65        let user_id = 1;
66        let user_id_json = serde_json::to_string(&user_id).unwrap();
67
68        let req = Response::new()
69            .with_api_key(api_key)
70            .with_email(email)
71            .with_user_id(user_id);
72
73        let req_json = format!(
74            r#"{{"msg":"","result":"success","api_key":{api_key_json},"email":{email_json},"user_id":{user_id_json}}}"#
75        );
76
77        assert_eq!(serde_json::to_string(&req).unwrap(), req_json);
78        assert_eq!(serde_json::from_str::<Response>(&req_json).unwrap(), req);
79
80        assert_eq!(req.api_key(), Some(api_key));
81        assert_eq!(req.email(), Some(email));
82        assert_eq!(req.user_id(), Some(user_id));
83    }
84}