use crate::error::Error;
use crate::types::{ApplicationSecret, TokenInfo};
use hyper::header;
use url::form_urlencoded;
pub(crate) struct RefreshFlow;
impl RefreshFlow {
pub(crate) async fn refresh_token<C>(
client: &hyper::Client<C>,
client_secret: &ApplicationSecret,
refresh_token: &str,
) -> Result<TokenInfo, Error>
where
C: hyper::client::connect::Connect + Clone + Send + Sync + 'static,
{
log::debug!(
"refreshing access token with refresh token: {}",
refresh_token
);
let req = form_urlencoded::Serializer::new(String::new())
.extend_pairs(&[
("client_id", client_secret.client_id.as_str()),
("client_secret", client_secret.client_secret.as_str()),
("refresh_token", refresh_token),
("grant_type", "refresh_token"),
])
.finish();
let request = hyper::Request::post(&client_secret.token_uri)
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(hyper::Body::from(req))
.unwrap();
log::debug!("Sending request: {:?}", request);
let (head, body) = client.request(request).await?.into_parts();
let body = hyper::body::to_bytes(body).await?;
log::debug!("Received response; head: {:?}, body: {:?}", head, body);
let mut token = TokenInfo::from_json(&body)?;
token
.refresh_token
.get_or_insert_with(|| refresh_token.to_owned());
Ok(token)
}
}