openstack_sdk/api/identity/v3/user/password/
set.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Changes the password for a user.
19//!
20//! Relationship:
21//! `https://docs.openstack.org/api/openstack-identity/3/rel/user_change_password`
22//!
23use derive_builder::Builder;
24use http::{HeaderMap, HeaderName, HeaderValue};
25
26use crate::api::rest_endpoint_prelude::*;
27
28use crate::api::common::serialize_sensitive_string;
29use secrecy::SecretString;
30use serde::Deserialize;
31use serde::Serialize;
32use std::borrow::Cow;
33
34/// A `user` object
35#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
36#[builder(setter(strip_option))]
37pub struct User {
38    /// The original password for the user.
39    #[serde(serialize_with = "serialize_sensitive_string")]
40    #[builder(setter(into))]
41    pub(crate) original_password: SecretString,
42
43    /// The new password for the user.
44    #[serde(serialize_with = "serialize_sensitive_string")]
45    #[builder(setter(into))]
46    pub(crate) password: SecretString,
47}
48
49#[derive(Builder, Debug, Clone)]
50#[builder(setter(strip_option))]
51pub struct Request<'a> {
52    /// A `user` object
53    #[builder(setter(into))]
54    pub(crate) user: User,
55
56    /// user_id parameter for /v3/users/{user_id}/password API
57    #[builder(default, setter(into))]
58    user_id: Cow<'a, str>,
59
60    #[builder(setter(name = "_headers"), default, private)]
61    _headers: Option<HeaderMap>,
62}
63impl<'a> Request<'a> {
64    /// Create a builder for the endpoint.
65    pub fn builder() -> RequestBuilder<'a> {
66        RequestBuilder::default()
67    }
68}
69
70impl RequestBuilder<'_> {
71    /// Add a single header to the Password.
72    pub fn header(&mut self, header_name: &'static str, header_value: &'static str) -> &mut Self
73where {
74        self._headers
75            .get_or_insert(None)
76            .get_or_insert_with(HeaderMap::new)
77            .insert(header_name, HeaderValue::from_static(header_value));
78        self
79    }
80
81    /// Add multiple headers.
82    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
83    where
84        I: Iterator<Item = T>,
85        T: Into<(Option<HeaderName>, HeaderValue)>,
86    {
87        self._headers
88            .get_or_insert(None)
89            .get_or_insert_with(HeaderMap::new)
90            .extend(iter.map(Into::into));
91        self
92    }
93}
94
95impl RestEndpoint for Request<'_> {
96    fn method(&self) -> http::Method {
97        http::Method::POST
98    }
99
100    fn endpoint(&self) -> Cow<'static, str> {
101        format!("users/{user_id}/password", user_id = self.user_id.as_ref(),).into()
102    }
103
104    fn parameters(&self) -> QueryParams {
105        QueryParams::default()
106    }
107
108    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
109        let mut params = JsonBodyParams::default();
110
111        params.push("user", serde_json::to_value(&self.user)?);
112
113        params.into_body()
114    }
115
116    fn service_type(&self) -> ServiceType {
117        ServiceType::Identity
118    }
119
120    fn response_key(&self) -> Option<Cow<'static, str>> {
121        None
122    }
123
124    /// Returns headers to be set into the request
125    fn request_headers(&self) -> Option<&HeaderMap> {
126        self._headers.as_ref()
127    }
128
129    /// Returns required API version
130    fn api_version(&self) -> Option<ApiVersion> {
131        Some(ApiVersion::new(3, 0))
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    #[cfg(feature = "sync")]
139    use crate::api::Query;
140    use crate::test::client::FakeOpenStackClient;
141    use crate::types::ServiceType;
142    use http::{HeaderName, HeaderValue};
143    use httpmock::MockServer;
144    use serde_json::json;
145
146    #[test]
147    fn test_service_type() {
148        assert_eq!(
149            Request::builder()
150                .user(
151                    UserBuilder::default()
152                        .original_password("foo")
153                        .password("foo")
154                        .build()
155                        .unwrap()
156                )
157                .build()
158                .unwrap()
159                .service_type(),
160            ServiceType::Identity
161        );
162    }
163
164    #[test]
165    fn test_response_key() {
166        assert!(Request::builder()
167            .user(
168                UserBuilder::default()
169                    .original_password("foo")
170                    .password("foo")
171                    .build()
172                    .unwrap()
173            )
174            .build()
175            .unwrap()
176            .response_key()
177            .is_none())
178    }
179
180    #[cfg(feature = "sync")]
181    #[test]
182    fn endpoint() {
183        let server = MockServer::start();
184        let client = FakeOpenStackClient::new(server.base_url());
185        let mock = server.mock(|when, then| {
186            when.method(httpmock::Method::POST)
187                .path(format!("/users/{user_id}/password", user_id = "user_id",));
188
189            then.status(200)
190                .header("content-type", "application/json")
191                .json_body(json!({ "dummy": {} }));
192        });
193
194        let endpoint = Request::builder()
195            .user_id("user_id")
196            .user(
197                UserBuilder::default()
198                    .original_password("foo")
199                    .password("foo")
200                    .build()
201                    .unwrap(),
202            )
203            .build()
204            .unwrap();
205        let _: serde_json::Value = endpoint.query(&client).unwrap();
206        mock.assert();
207    }
208
209    #[cfg(feature = "sync")]
210    #[test]
211    fn endpoint_headers() {
212        let server = MockServer::start();
213        let client = FakeOpenStackClient::new(server.base_url());
214        let mock = server.mock(|when, then| {
215            when.method(httpmock::Method::POST)
216                .path(format!("/users/{user_id}/password", user_id = "user_id",))
217                .header("foo", "bar")
218                .header("not_foo", "not_bar");
219            then.status(200)
220                .header("content-type", "application/json")
221                .json_body(json!({ "dummy": {} }));
222        });
223
224        let endpoint = Request::builder()
225            .user_id("user_id")
226            .user(
227                UserBuilder::default()
228                    .original_password("foo")
229                    .password("foo")
230                    .build()
231                    .unwrap(),
232            )
233            .headers(
234                [(
235                    Some(HeaderName::from_static("foo")),
236                    HeaderValue::from_static("bar"),
237                )]
238                .into_iter(),
239            )
240            .header("not_foo", "not_bar")
241            .build()
242            .unwrap();
243        let _: serde_json::Value = endpoint.query(&client).unwrap();
244        mock.assert();
245    }
246}