yup_oauth2/
authorized_user.rs

1//! This module provides a token source (`GetToken`) that obtains tokens using user credentials
2//! for use by software (i.e., non-human actors) to get access to Google services.
3//!
4//! Resources:
5//! - [gcloud auth application-default login](https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login)
6//!
7use crate::client::SendRequest;
8use crate::error::Error;
9use crate::types::TokenInfo;
10use http::header;
11use http_body_util::BodyExt;
12use serde::{Deserialize, Serialize};
13
14use url::form_urlencoded;
15
16const TOKEN_URI: &str = "https://accounts.google.com/o/oauth2/token";
17
18/// JSON schema of authorized user secret. You can obtain it by
19/// running on the client: `gcloud auth application-default login`.
20///
21/// You can use `helpers::read_authorized_user_secret()` to read a JSON file
22/// into a `AuthorizedUserSecret`.
23#[derive(Serialize, Deserialize, Debug, Clone)]
24pub struct AuthorizedUserSecret {
25    /// client_id
26    pub client_id: String,
27    /// client_secret
28    pub client_secret: String,
29    /// refresh_token
30    pub refresh_token: String,
31    #[serde(rename = "type")]
32    /// key_type
33    pub key_type: String,
34}
35
36/// AuthorizedUserFlow can fetch oauth tokens using an authorized user secret.
37pub struct AuthorizedUserFlow {
38    pub(crate) secret: AuthorizedUserSecret,
39}
40
41impl AuthorizedUserFlow {
42    /// Send a request for a new Bearer token to the OAuth provider.
43    pub(crate) async fn token<T>(
44        &self,
45        hyper_client: &impl SendRequest,
46        _scopes: &[T],
47    ) -> Result<TokenInfo, Error>
48    where
49        T: AsRef<str>,
50    {
51        let req = form_urlencoded::Serializer::new(String::new())
52            .extend_pairs(&[
53                ("client_id", self.secret.client_id.as_str()),
54                ("client_secret", self.secret.client_secret.as_str()),
55                ("refresh_token", self.secret.refresh_token.as_str()),
56                ("grant_type", "refresh_token"),
57            ])
58            .finish();
59
60        let request = http::Request::post(TOKEN_URI)
61            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
62            .body(req)
63            .unwrap();
64
65        log::debug!("requesting token from authorized user: {:?}", request);
66        let (head, body) = hyper_client.request(request).await?.into_parts();
67        let body = body.collect().await?.to_bytes();
68        log::debug!("received response; head: {:?}, body: {:?}", head, body);
69        TokenInfo::from_json(&body)
70    }
71}