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
use crate::error::Error;
use crate::types::TokenInfo;
use hyper::client::connect::Connection;
use hyper::header;
use http::Uri;
use serde::{Deserialize, Serialize};
use std::error::Error as StdError;
use tokio::io::{AsyncRead, AsyncWrite};
use tower_service::Service;
use url::form_urlencoded;
const TOKEN_URI: &str = "https://accounts.google.com/o/oauth2/token";
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuthorizedUserSecret {
pub client_id: String,
pub client_secret: String,
pub refresh_token: String,
#[serde(rename = "type")]
pub key_type: String,
}
pub struct AuthorizedUserFlow {
pub(crate) secret: AuthorizedUserSecret,
}
impl AuthorizedUserFlow {
pub(crate) async fn token<S, T>(
&self,
hyper_client: &hyper::Client<S>,
_scopes: &[T],
) -> Result<TokenInfo, Error>
where
T: AsRef<str>,
S: Service<Uri> + Clone + Send + Sync + 'static,
S::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static,
S::Future: Send + Unpin + 'static,
S::Error: Into<Box<dyn StdError + Send + Sync>>,
{
let req = form_urlencoded::Serializer::new(String::new())
.extend_pairs(&[
("client_id", self.secret.client_id.as_str()),
("client_secret", self.secret.client_secret.as_str()),
("refresh_token", self.secret.refresh_token.as_str()),
("grant_type", "refresh_token"),
])
.finish();
let request = hyper::Request::post(TOKEN_URI)
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(hyper::Body::from(req))
.unwrap();
log::debug!("requesting token from authorized user: {:?}", request);
let (head, body) = hyper_client.request(request).await?.into_parts();
let body = hyper::body::to_bytes(body).await?;
log::debug!("received response; head: {:?}, body: {:?}", head, body);
TokenInfo::from_json(&body)
}
}