use crate::error::Error;
use crate::types::TokenInfo;
use http::header;
use http_body_util::BodyExt;
use hyper_util::client::legacy::connect::Connect;
use serde::{Deserialize, Serialize};
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<C, T>(
&self,
hyper_client: &hyper_util::client::legacy::Client<C, String>,
_scopes: &[T],
) -> Result<TokenInfo, Error>
where
T: AsRef<str>,
C: Connect + Clone + Send + Sync + 'static,
{
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 = http::Request::post(TOKEN_URI)
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(req)
.unwrap();
log::debug!("requesting token from authorized user: {:?}", request);
let (head, body) = hyper_client.request(request).await?.into_parts();
let body = body.collect().await?.to_bytes();
log::debug!("received response; head: {:?}, body: {:?}", head, body);
TokenInfo::from_json(&body)
}
}