google_verifiedaccess1/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// Verify your enterprise credentials
17 Full,
18}
19
20impl AsRef<str> for Scope {
21 fn as_ref(&self) -> &str {
22 match *self {
23 Scope::Full => "https://www.googleapis.com/auth/verifiedaccess",
24 }
25 }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30 fn default() -> Scope {
31 Scope::Full
32 }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all Verifiedaccess related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_verifiedaccess1 as verifiedaccess1;
49/// use verifiedaccess1::api::VerifyChallengeResponseRequest;
50/// use verifiedaccess1::{Result, Error};
51/// # async fn dox() {
52/// use verifiedaccess1::{Verifiedaccess, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
53///
54/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
55/// // `client_secret`, among other things.
56/// let secret: yup_oauth2::ApplicationSecret = Default::default();
57/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
58/// // unless you replace `None` with the desired Flow.
59/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
60/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
61/// // retrieve them from storage.
62/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
63/// .with_native_roots()
64/// .unwrap()
65/// .https_only()
66/// .enable_http2()
67/// .build();
68///
69/// let executor = hyper_util::rt::TokioExecutor::new();
70/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
71/// secret,
72/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
73/// yup_oauth2::client::CustomHyperClientBuilder::from(
74/// hyper_util::client::legacy::Client::builder(executor).build(connector),
75/// ),
76/// ).build().await.unwrap();
77///
78/// let client = hyper_util::client::legacy::Client::builder(
79/// hyper_util::rt::TokioExecutor::new()
80/// )
81/// .build(
82/// hyper_rustls::HttpsConnectorBuilder::new()
83/// .with_native_roots()
84/// .unwrap()
85/// .https_or_http()
86/// .enable_http2()
87/// .build()
88/// );
89/// let mut hub = Verifiedaccess::new(client, auth);
90/// // As the method needs a request, you would usually fill it with the desired information
91/// // into the respective structure. Some of the parts shown here might not be applicable !
92/// // Values shown here are possibly random and not representative !
93/// let mut req = VerifyChallengeResponseRequest::default();
94///
95/// // You can configure optional parameters by calling the respective setters at will, and
96/// // execute the final call using `doit()`.
97/// // Values shown here are possibly random and not representative !
98/// let result = hub.challenge().verify(req)
99/// .doit().await;
100///
101/// match result {
102/// Err(e) => match e {
103/// // The Error enum provides details about what exactly happened.
104/// // You can also just use its `Debug`, `Display` or `Error` traits
105/// Error::HttpError(_)
106/// |Error::Io(_)
107/// |Error::MissingAPIKey
108/// |Error::MissingToken(_)
109/// |Error::Cancelled
110/// |Error::UploadSizeLimitExceeded(_, _)
111/// |Error::Failure(_)
112/// |Error::BadRequest(_)
113/// |Error::FieldClash(_)
114/// |Error::JsonDecodeError(_, _) => println!("{}", e),
115/// },
116/// Ok(res) => println!("Success: {:?}", res),
117/// }
118/// # }
119/// ```
120#[derive(Clone)]
121pub struct Verifiedaccess<C> {
122 pub client: common::Client<C>,
123 pub auth: Box<dyn common::GetToken>,
124 _user_agent: String,
125 _base_url: String,
126 _root_url: String,
127}
128
129impl<C> common::Hub for Verifiedaccess<C> {}
130
131impl<'a, C> Verifiedaccess<C> {
132 pub fn new<A: 'static + common::GetToken>(
133 client: common::Client<C>,
134 auth: A,
135 ) -> Verifiedaccess<C> {
136 Verifiedaccess {
137 client,
138 auth: Box::new(auth),
139 _user_agent: "google-api-rust-client/7.0.0".to_string(),
140 _base_url: "https://verifiedaccess.googleapis.com/".to_string(),
141 _root_url: "https://verifiedaccess.googleapis.com/".to_string(),
142 }
143 }
144
145 pub fn challenge(&'a self) -> ChallengeMethods<'a, C> {
146 ChallengeMethods { hub: self }
147 }
148
149 /// Set the user-agent header field to use in all requests to the server.
150 /// It defaults to `google-api-rust-client/7.0.0`.
151 ///
152 /// Returns the previously set user-agent.
153 pub fn user_agent(&mut self, agent_name: String) -> String {
154 std::mem::replace(&mut self._user_agent, agent_name)
155 }
156
157 /// Set the base url to use in all requests to the server.
158 /// It defaults to `https://verifiedaccess.googleapis.com/`.
159 ///
160 /// Returns the previously set base url.
161 pub fn base_url(&mut self, new_base_url: String) -> String {
162 std::mem::replace(&mut self._base_url, new_base_url)
163 }
164
165 /// Set the root url to use in all requests to the server.
166 /// It defaults to `https://verifiedaccess.googleapis.com/`.
167 ///
168 /// Returns the previously set root url.
169 pub fn root_url(&mut self, new_root_url: String) -> String {
170 std::mem::replace(&mut self._root_url, new_root_url)
171 }
172}
173
174// ############
175// SCHEMAS ###
176// ##########
177/// Result message for VerifiedAccess.CreateChallenge.
178///
179/// # Activities
180///
181/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
182/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
183///
184/// * [create challenge](ChallengeCreateCall) (response)
185#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
186#[serde_with::serde_as]
187#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
188pub struct Challenge {
189 /// Challenge generated with the old signing key (this will only be present during key rotation)
190 #[serde(rename = "alternativeChallenge")]
191 pub alternative_challenge: Option<SignedData>,
192 /// Generated challenge
193 pub challenge: Option<SignedData>,
194}
195
196impl common::ResponseResult for Challenge {}
197
198/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
199///
200/// # Activities
201///
202/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
203/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
204///
205/// * [create challenge](ChallengeCreateCall) (request)
206#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
207#[serde_with::serde_as]
208#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
209pub struct Empty {
210 _never_set: Option<bool>,
211}
212
213impl common::RequestValue for Empty {}
214
215/// The wrapper message of any data and its signature.
216///
217/// This type is not used in any activity, and only used as *part* of another schema.
218///
219#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
220#[serde_with::serde_as]
221#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
222pub struct SignedData {
223 /// The data to be signed.
224 #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
225 pub data: Option<Vec<u8>>,
226 /// The signature of the data field.
227 #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
228 pub signature: Option<Vec<u8>>,
229}
230
231impl common::Part for SignedData {}
232
233/// signed ChallengeResponse
234///
235/// # Activities
236///
237/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
238/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
239///
240/// * [verify challenge](ChallengeVerifyCall) (request)
241#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
242#[serde_with::serde_as]
243#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
244pub struct VerifyChallengeResponseRequest {
245 /// The generated response to the challenge
246 #[serde(rename = "challengeResponse")]
247 pub challenge_response: Option<SignedData>,
248 /// Service can optionally provide identity information about the device or user associated with the key. For an EMK, this value is the enrolled domain. For an EUK, this value is the user's email address. If present, this value will be checked against contents of the response, and verification will fail if there is no match.
249 #[serde(rename = "expectedIdentity")]
250 pub expected_identity: Option<String>,
251}
252
253impl common::RequestValue for VerifyChallengeResponseRequest {}
254
255/// Result message for VerifiedAccess.VerifyChallengeResponse.
256///
257/// # Activities
258///
259/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
260/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
261///
262/// * [verify challenge](ChallengeVerifyCall) (response)
263#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
264#[serde_with::serde_as]
265#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
266pub struct VerifyChallengeResponseResult {
267 /// Attested device id (ADID) of the device, read from the verified data.
268 #[serde(rename = "attestedDeviceId")]
269 pub attested_device_id: Option<String>,
270 /// Device enrollment id is returned in this field (for the machine response only).
271 #[serde(rename = "deviceEnrollmentId")]
272 pub device_enrollment_id: Option<String>,
273 /// Device permanent id is returned in this field (for the machine response only).
274 #[serde(rename = "devicePermanentId")]
275 pub device_permanent_id: Option<String>,
276 /// Certificate Signing Request (in the SPKAC format, base64 encoded) is returned in this field. This field will be set only if device has included CSR in its challenge response. (the option to include CSR is now available for both user and machine responses)
277 #[serde(rename = "signedPublicKeyAndChallenge")]
278 pub signed_public_key_and_challenge: Option<String>,
279 /// For EMCert check, device permanent id is returned here. For EUCert check, signed_public_key_and_challenge [base64 encoded] is returned if present, otherwise empty string is returned. This field is deprecated, please use device_permanent_id or signed_public_key_and_challenge fields.
280 #[serde(rename = "verificationOutput")]
281 pub verification_output: Option<String>,
282}
283
284impl common::ResponseResult for VerifyChallengeResponseResult {}
285
286// ###################
287// MethodBuilders ###
288// #################
289
290/// A builder providing access to all methods supported on *challenge* resources.
291/// It is not used directly, but through the [`Verifiedaccess`] hub.
292///
293/// # Example
294///
295/// Instantiate a resource builder
296///
297/// ```test_harness,no_run
298/// extern crate hyper;
299/// extern crate hyper_rustls;
300/// extern crate google_verifiedaccess1 as verifiedaccess1;
301///
302/// # async fn dox() {
303/// use verifiedaccess1::{Verifiedaccess, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
304///
305/// let secret: yup_oauth2::ApplicationSecret = Default::default();
306/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
307/// .with_native_roots()
308/// .unwrap()
309/// .https_only()
310/// .enable_http2()
311/// .build();
312///
313/// let executor = hyper_util::rt::TokioExecutor::new();
314/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
315/// secret,
316/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
317/// yup_oauth2::client::CustomHyperClientBuilder::from(
318/// hyper_util::client::legacy::Client::builder(executor).build(connector),
319/// ),
320/// ).build().await.unwrap();
321///
322/// let client = hyper_util::client::legacy::Client::builder(
323/// hyper_util::rt::TokioExecutor::new()
324/// )
325/// .build(
326/// hyper_rustls::HttpsConnectorBuilder::new()
327/// .with_native_roots()
328/// .unwrap()
329/// .https_or_http()
330/// .enable_http2()
331/// .build()
332/// );
333/// let mut hub = Verifiedaccess::new(client, auth);
334/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
335/// // like `create(...)` and `verify(...)`
336/// // to build up your call.
337/// let rb = hub.challenge();
338/// # }
339/// ```
340pub struct ChallengeMethods<'a, C>
341where
342 C: 'a,
343{
344 hub: &'a Verifiedaccess<C>,
345}
346
347impl<'a, C> common::MethodsBuilder for ChallengeMethods<'a, C> {}
348
349impl<'a, C> ChallengeMethods<'a, C> {
350 /// Create a builder to help you perform the following task:
351 ///
352 /// CreateChallenge API
353 ///
354 /// # Arguments
355 ///
356 /// * `request` - No description provided.
357 pub fn create(&self, request: Empty) -> ChallengeCreateCall<'a, C> {
358 ChallengeCreateCall {
359 hub: self.hub,
360 _request: request,
361 _delegate: Default::default(),
362 _additional_params: Default::default(),
363 _scopes: Default::default(),
364 }
365 }
366
367 /// Create a builder to help you perform the following task:
368 ///
369 /// VerifyChallengeResponse API
370 ///
371 /// # Arguments
372 ///
373 /// * `request` - No description provided.
374 pub fn verify(&self, request: VerifyChallengeResponseRequest) -> ChallengeVerifyCall<'a, C> {
375 ChallengeVerifyCall {
376 hub: self.hub,
377 _request: request,
378 _delegate: Default::default(),
379 _additional_params: Default::default(),
380 _scopes: Default::default(),
381 }
382 }
383}
384
385// ###################
386// CallBuilders ###
387// #################
388
389/// CreateChallenge API
390///
391/// A builder for the *create* method supported by a *challenge* resource.
392/// It is not used directly, but through a [`ChallengeMethods`] instance.
393///
394/// # Example
395///
396/// Instantiate a resource method builder
397///
398/// ```test_harness,no_run
399/// # extern crate hyper;
400/// # extern crate hyper_rustls;
401/// # extern crate google_verifiedaccess1 as verifiedaccess1;
402/// use verifiedaccess1::api::Empty;
403/// # async fn dox() {
404/// # use verifiedaccess1::{Verifiedaccess, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
405///
406/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
407/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
408/// # .with_native_roots()
409/// # .unwrap()
410/// # .https_only()
411/// # .enable_http2()
412/// # .build();
413///
414/// # let executor = hyper_util::rt::TokioExecutor::new();
415/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
416/// # secret,
417/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
418/// # yup_oauth2::client::CustomHyperClientBuilder::from(
419/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
420/// # ),
421/// # ).build().await.unwrap();
422///
423/// # let client = hyper_util::client::legacy::Client::builder(
424/// # hyper_util::rt::TokioExecutor::new()
425/// # )
426/// # .build(
427/// # hyper_rustls::HttpsConnectorBuilder::new()
428/// # .with_native_roots()
429/// # .unwrap()
430/// # .https_or_http()
431/// # .enable_http2()
432/// # .build()
433/// # );
434/// # let mut hub = Verifiedaccess::new(client, auth);
435/// // As the method needs a request, you would usually fill it with the desired information
436/// // into the respective structure. Some of the parts shown here might not be applicable !
437/// // Values shown here are possibly random and not representative !
438/// let mut req = Empty::default();
439///
440/// // You can configure optional parameters by calling the respective setters at will, and
441/// // execute the final call using `doit()`.
442/// // Values shown here are possibly random and not representative !
443/// let result = hub.challenge().create(req)
444/// .doit().await;
445/// # }
446/// ```
447pub struct ChallengeCreateCall<'a, C>
448where
449 C: 'a,
450{
451 hub: &'a Verifiedaccess<C>,
452 _request: Empty,
453 _delegate: Option<&'a mut dyn common::Delegate>,
454 _additional_params: HashMap<String, String>,
455 _scopes: BTreeSet<String>,
456}
457
458impl<'a, C> common::CallBuilder for ChallengeCreateCall<'a, C> {}
459
460impl<'a, C> ChallengeCreateCall<'a, C>
461where
462 C: common::Connector,
463{
464 /// Perform the operation you have build so far.
465 pub async fn doit(mut self) -> common::Result<(common::Response, Challenge)> {
466 use std::borrow::Cow;
467 use std::io::{Read, Seek};
468
469 use common::{url::Params, ToParts};
470 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
471
472 let mut dd = common::DefaultDelegate;
473 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
474 dlg.begin(common::MethodInfo {
475 id: "verifiedaccess.challenge.create",
476 http_method: hyper::Method::POST,
477 });
478
479 for &field in ["alt"].iter() {
480 if self._additional_params.contains_key(field) {
481 dlg.finished(false);
482 return Err(common::Error::FieldClash(field));
483 }
484 }
485
486 let mut params = Params::with_capacity(3 + self._additional_params.len());
487
488 params.extend(self._additional_params.iter());
489
490 params.push("alt", "json");
491 let mut url = self.hub._base_url.clone() + "v1/challenge";
492 if self._scopes.is_empty() {
493 self._scopes.insert(Scope::Full.as_ref().to_string());
494 }
495
496 let url = params.parse_with_url(&url);
497
498 let mut json_mime_type = mime::APPLICATION_JSON;
499 let mut request_value_reader = {
500 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
501 common::remove_json_null_values(&mut value);
502 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
503 serde_json::to_writer(&mut dst, &value).unwrap();
504 dst
505 };
506 let request_size = request_value_reader
507 .seek(std::io::SeekFrom::End(0))
508 .unwrap();
509 request_value_reader
510 .seek(std::io::SeekFrom::Start(0))
511 .unwrap();
512
513 loop {
514 let token = match self
515 .hub
516 .auth
517 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
518 .await
519 {
520 Ok(token) => token,
521 Err(e) => match dlg.token(e) {
522 Ok(token) => token,
523 Err(e) => {
524 dlg.finished(false);
525 return Err(common::Error::MissingToken(e));
526 }
527 },
528 };
529 request_value_reader
530 .seek(std::io::SeekFrom::Start(0))
531 .unwrap();
532 let mut req_result = {
533 let client = &self.hub.client;
534 dlg.pre_request();
535 let mut req_builder = hyper::Request::builder()
536 .method(hyper::Method::POST)
537 .uri(url.as_str())
538 .header(USER_AGENT, self.hub._user_agent.clone());
539
540 if let Some(token) = token.as_ref() {
541 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
542 }
543
544 let request = req_builder
545 .header(CONTENT_TYPE, json_mime_type.to_string())
546 .header(CONTENT_LENGTH, request_size as u64)
547 .body(common::to_body(
548 request_value_reader.get_ref().clone().into(),
549 ));
550
551 client.request(request.unwrap()).await
552 };
553
554 match req_result {
555 Err(err) => {
556 if let common::Retry::After(d) = dlg.http_error(&err) {
557 sleep(d).await;
558 continue;
559 }
560 dlg.finished(false);
561 return Err(common::Error::HttpError(err));
562 }
563 Ok(res) => {
564 let (mut parts, body) = res.into_parts();
565 let mut body = common::Body::new(body);
566 if !parts.status.is_success() {
567 let bytes = common::to_bytes(body).await.unwrap_or_default();
568 let error = serde_json::from_str(&common::to_string(&bytes));
569 let response = common::to_response(parts, bytes.into());
570
571 if let common::Retry::After(d) =
572 dlg.http_failure(&response, error.as_ref().ok())
573 {
574 sleep(d).await;
575 continue;
576 }
577
578 dlg.finished(false);
579
580 return Err(match error {
581 Ok(value) => common::Error::BadRequest(value),
582 _ => common::Error::Failure(response),
583 });
584 }
585 let response = {
586 let bytes = common::to_bytes(body).await.unwrap_or_default();
587 let encoded = common::to_string(&bytes);
588 match serde_json::from_str(&encoded) {
589 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
590 Err(error) => {
591 dlg.response_json_decode_error(&encoded, &error);
592 return Err(common::Error::JsonDecodeError(
593 encoded.to_string(),
594 error,
595 ));
596 }
597 }
598 };
599
600 dlg.finished(true);
601 return Ok(response);
602 }
603 }
604 }
605 }
606
607 ///
608 /// Sets the *request* property to the given value.
609 ///
610 /// Even though the property as already been set when instantiating this call,
611 /// we provide this method for API completeness.
612 pub fn request(mut self, new_value: Empty) -> ChallengeCreateCall<'a, C> {
613 self._request = new_value;
614 self
615 }
616 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
617 /// while executing the actual API request.
618 ///
619 /// ````text
620 /// It should be used to handle progress information, and to implement a certain level of resilience.
621 /// ````
622 ///
623 /// Sets the *delegate* property to the given value.
624 pub fn delegate(
625 mut self,
626 new_value: &'a mut dyn common::Delegate,
627 ) -> ChallengeCreateCall<'a, C> {
628 self._delegate = Some(new_value);
629 self
630 }
631
632 /// Set any additional parameter of the query string used in the request.
633 /// It should be used to set parameters which are not yet available through their own
634 /// setters.
635 ///
636 /// Please note that this method must not be used to set any of the known parameters
637 /// which have their own setter method. If done anyway, the request will fail.
638 ///
639 /// # Additional Parameters
640 ///
641 /// * *$.xgafv* (query-string) - V1 error format.
642 /// * *access_token* (query-string) - OAuth access token.
643 /// * *alt* (query-string) - Data format for response.
644 /// * *callback* (query-string) - JSONP
645 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
646 /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
647 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
648 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
649 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
650 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
651 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
652 pub fn param<T>(mut self, name: T, value: T) -> ChallengeCreateCall<'a, C>
653 where
654 T: AsRef<str>,
655 {
656 self._additional_params
657 .insert(name.as_ref().to_string(), value.as_ref().to_string());
658 self
659 }
660
661 /// Identifies the authorization scope for the method you are building.
662 ///
663 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
664 /// [`Scope::Full`].
665 ///
666 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
667 /// tokens for more than one scope.
668 ///
669 /// Usually there is more than one suitable scope to authorize an operation, some of which may
670 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
671 /// sufficient, a read-write scope will do as well.
672 pub fn add_scope<St>(mut self, scope: St) -> ChallengeCreateCall<'a, C>
673 where
674 St: AsRef<str>,
675 {
676 self._scopes.insert(String::from(scope.as_ref()));
677 self
678 }
679 /// Identifies the authorization scope(s) for the method you are building.
680 ///
681 /// See [`Self::add_scope()`] for details.
682 pub fn add_scopes<I, St>(mut self, scopes: I) -> ChallengeCreateCall<'a, C>
683 where
684 I: IntoIterator<Item = St>,
685 St: AsRef<str>,
686 {
687 self._scopes
688 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
689 self
690 }
691
692 /// Removes all scopes, and no default scope will be used either.
693 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
694 /// for details).
695 pub fn clear_scopes(mut self) -> ChallengeCreateCall<'a, C> {
696 self._scopes.clear();
697 self
698 }
699}
700
701/// VerifyChallengeResponse API
702///
703/// A builder for the *verify* method supported by a *challenge* resource.
704/// It is not used directly, but through a [`ChallengeMethods`] instance.
705///
706/// # Example
707///
708/// Instantiate a resource method builder
709///
710/// ```test_harness,no_run
711/// # extern crate hyper;
712/// # extern crate hyper_rustls;
713/// # extern crate google_verifiedaccess1 as verifiedaccess1;
714/// use verifiedaccess1::api::VerifyChallengeResponseRequest;
715/// # async fn dox() {
716/// # use verifiedaccess1::{Verifiedaccess, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
717///
718/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
719/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
720/// # .with_native_roots()
721/// # .unwrap()
722/// # .https_only()
723/// # .enable_http2()
724/// # .build();
725///
726/// # let executor = hyper_util::rt::TokioExecutor::new();
727/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
728/// # secret,
729/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
730/// # yup_oauth2::client::CustomHyperClientBuilder::from(
731/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
732/// # ),
733/// # ).build().await.unwrap();
734///
735/// # let client = hyper_util::client::legacy::Client::builder(
736/// # hyper_util::rt::TokioExecutor::new()
737/// # )
738/// # .build(
739/// # hyper_rustls::HttpsConnectorBuilder::new()
740/// # .with_native_roots()
741/// # .unwrap()
742/// # .https_or_http()
743/// # .enable_http2()
744/// # .build()
745/// # );
746/// # let mut hub = Verifiedaccess::new(client, auth);
747/// // As the method needs a request, you would usually fill it with the desired information
748/// // into the respective structure. Some of the parts shown here might not be applicable !
749/// // Values shown here are possibly random and not representative !
750/// let mut req = VerifyChallengeResponseRequest::default();
751///
752/// // You can configure optional parameters by calling the respective setters at will, and
753/// // execute the final call using `doit()`.
754/// // Values shown here are possibly random and not representative !
755/// let result = hub.challenge().verify(req)
756/// .doit().await;
757/// # }
758/// ```
759pub struct ChallengeVerifyCall<'a, C>
760where
761 C: 'a,
762{
763 hub: &'a Verifiedaccess<C>,
764 _request: VerifyChallengeResponseRequest,
765 _delegate: Option<&'a mut dyn common::Delegate>,
766 _additional_params: HashMap<String, String>,
767 _scopes: BTreeSet<String>,
768}
769
770impl<'a, C> common::CallBuilder for ChallengeVerifyCall<'a, C> {}
771
772impl<'a, C> ChallengeVerifyCall<'a, C>
773where
774 C: common::Connector,
775{
776 /// Perform the operation you have build so far.
777 pub async fn doit(
778 mut self,
779 ) -> common::Result<(common::Response, VerifyChallengeResponseResult)> {
780 use std::borrow::Cow;
781 use std::io::{Read, Seek};
782
783 use common::{url::Params, ToParts};
784 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
785
786 let mut dd = common::DefaultDelegate;
787 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
788 dlg.begin(common::MethodInfo {
789 id: "verifiedaccess.challenge.verify",
790 http_method: hyper::Method::POST,
791 });
792
793 for &field in ["alt"].iter() {
794 if self._additional_params.contains_key(field) {
795 dlg.finished(false);
796 return Err(common::Error::FieldClash(field));
797 }
798 }
799
800 let mut params = Params::with_capacity(3 + self._additional_params.len());
801
802 params.extend(self._additional_params.iter());
803
804 params.push("alt", "json");
805 let mut url = self.hub._base_url.clone() + "v1/challenge:verify";
806 if self._scopes.is_empty() {
807 self._scopes.insert(Scope::Full.as_ref().to_string());
808 }
809
810 let url = params.parse_with_url(&url);
811
812 let mut json_mime_type = mime::APPLICATION_JSON;
813 let mut request_value_reader = {
814 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
815 common::remove_json_null_values(&mut value);
816 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
817 serde_json::to_writer(&mut dst, &value).unwrap();
818 dst
819 };
820 let request_size = request_value_reader
821 .seek(std::io::SeekFrom::End(0))
822 .unwrap();
823 request_value_reader
824 .seek(std::io::SeekFrom::Start(0))
825 .unwrap();
826
827 loop {
828 let token = match self
829 .hub
830 .auth
831 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
832 .await
833 {
834 Ok(token) => token,
835 Err(e) => match dlg.token(e) {
836 Ok(token) => token,
837 Err(e) => {
838 dlg.finished(false);
839 return Err(common::Error::MissingToken(e));
840 }
841 },
842 };
843 request_value_reader
844 .seek(std::io::SeekFrom::Start(0))
845 .unwrap();
846 let mut req_result = {
847 let client = &self.hub.client;
848 dlg.pre_request();
849 let mut req_builder = hyper::Request::builder()
850 .method(hyper::Method::POST)
851 .uri(url.as_str())
852 .header(USER_AGENT, self.hub._user_agent.clone());
853
854 if let Some(token) = token.as_ref() {
855 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
856 }
857
858 let request = req_builder
859 .header(CONTENT_TYPE, json_mime_type.to_string())
860 .header(CONTENT_LENGTH, request_size as u64)
861 .body(common::to_body(
862 request_value_reader.get_ref().clone().into(),
863 ));
864
865 client.request(request.unwrap()).await
866 };
867
868 match req_result {
869 Err(err) => {
870 if let common::Retry::After(d) = dlg.http_error(&err) {
871 sleep(d).await;
872 continue;
873 }
874 dlg.finished(false);
875 return Err(common::Error::HttpError(err));
876 }
877 Ok(res) => {
878 let (mut parts, body) = res.into_parts();
879 let mut body = common::Body::new(body);
880 if !parts.status.is_success() {
881 let bytes = common::to_bytes(body).await.unwrap_or_default();
882 let error = serde_json::from_str(&common::to_string(&bytes));
883 let response = common::to_response(parts, bytes.into());
884
885 if let common::Retry::After(d) =
886 dlg.http_failure(&response, error.as_ref().ok())
887 {
888 sleep(d).await;
889 continue;
890 }
891
892 dlg.finished(false);
893
894 return Err(match error {
895 Ok(value) => common::Error::BadRequest(value),
896 _ => common::Error::Failure(response),
897 });
898 }
899 let response = {
900 let bytes = common::to_bytes(body).await.unwrap_or_default();
901 let encoded = common::to_string(&bytes);
902 match serde_json::from_str(&encoded) {
903 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
904 Err(error) => {
905 dlg.response_json_decode_error(&encoded, &error);
906 return Err(common::Error::JsonDecodeError(
907 encoded.to_string(),
908 error,
909 ));
910 }
911 }
912 };
913
914 dlg.finished(true);
915 return Ok(response);
916 }
917 }
918 }
919 }
920
921 ///
922 /// Sets the *request* property to the given value.
923 ///
924 /// Even though the property as already been set when instantiating this call,
925 /// we provide this method for API completeness.
926 pub fn request(
927 mut self,
928 new_value: VerifyChallengeResponseRequest,
929 ) -> ChallengeVerifyCall<'a, C> {
930 self._request = new_value;
931 self
932 }
933 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
934 /// while executing the actual API request.
935 ///
936 /// ````text
937 /// It should be used to handle progress information, and to implement a certain level of resilience.
938 /// ````
939 ///
940 /// Sets the *delegate* property to the given value.
941 pub fn delegate(
942 mut self,
943 new_value: &'a mut dyn common::Delegate,
944 ) -> ChallengeVerifyCall<'a, C> {
945 self._delegate = Some(new_value);
946 self
947 }
948
949 /// Set any additional parameter of the query string used in the request.
950 /// It should be used to set parameters which are not yet available through their own
951 /// setters.
952 ///
953 /// Please note that this method must not be used to set any of the known parameters
954 /// which have their own setter method. If done anyway, the request will fail.
955 ///
956 /// # Additional Parameters
957 ///
958 /// * *$.xgafv* (query-string) - V1 error format.
959 /// * *access_token* (query-string) - OAuth access token.
960 /// * *alt* (query-string) - Data format for response.
961 /// * *callback* (query-string) - JSONP
962 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
963 /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
964 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
965 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
966 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
967 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
968 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
969 pub fn param<T>(mut self, name: T, value: T) -> ChallengeVerifyCall<'a, C>
970 where
971 T: AsRef<str>,
972 {
973 self._additional_params
974 .insert(name.as_ref().to_string(), value.as_ref().to_string());
975 self
976 }
977
978 /// Identifies the authorization scope for the method you are building.
979 ///
980 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
981 /// [`Scope::Full`].
982 ///
983 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
984 /// tokens for more than one scope.
985 ///
986 /// Usually there is more than one suitable scope to authorize an operation, some of which may
987 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
988 /// sufficient, a read-write scope will do as well.
989 pub fn add_scope<St>(mut self, scope: St) -> ChallengeVerifyCall<'a, C>
990 where
991 St: AsRef<str>,
992 {
993 self._scopes.insert(String::from(scope.as_ref()));
994 self
995 }
996 /// Identifies the authorization scope(s) for the method you are building.
997 ///
998 /// See [`Self::add_scope()`] for details.
999 pub fn add_scopes<I, St>(mut self, scopes: I) -> ChallengeVerifyCall<'a, C>
1000 where
1001 I: IntoIterator<Item = St>,
1002 St: AsRef<str>,
1003 {
1004 self._scopes
1005 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1006 self
1007 }
1008
1009 /// Removes all scopes, and no default scope will be used either.
1010 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1011 /// for details).
1012 pub fn clear_scopes(mut self) -> ChallengeVerifyCall<'a, C> {
1013 self._scopes.clear();
1014 self
1015 }
1016}