|
| 1 | +use crate::device_code_responses::*; |
| 2 | +use async_timer::timer::new_timer; |
| 3 | +use azure_sdk_core::errors::AzureError; |
| 4 | +use futures::stream::unfold; |
| 5 | +use log::debug; |
| 6 | +pub use oauth2::{ClientId, ClientSecret}; |
| 7 | +use std::convert::TryInto; |
| 8 | +use std::sync::Arc; |
| 9 | +use std::time::Duration; |
| 10 | +use url::form_urlencoded; |
| 11 | + |
| 12 | +#[derive(Debug, Clone, Deserialize)] |
| 13 | +pub struct DeviceCodePhaseOneResponse<'a> { |
| 14 | + device_code: String, |
| 15 | + user_code: String, |
| 16 | + verification_uri: String, |
| 17 | + expires_in: u64, |
| 18 | + interval: u64, |
| 19 | + message: String, |
| 20 | + // the skipped fields below do not come |
| 21 | + // from the Azure answer. They will be added |
| 22 | + // manually after deserialization |
| 23 | + #[serde(skip)] |
| 24 | + client: Arc<reqwest::Client>, |
| 25 | + #[serde(skip)] |
| 26 | + tenant_id: &'a str, |
| 27 | + // we store the ClientId as string instead of |
| 28 | + // the original type because it does not |
| 29 | + // implement Default and it's in another |
| 30 | + // create |
| 31 | + #[serde(skip)] |
| 32 | + client_id: String, |
| 33 | +} |
| 34 | + |
| 35 | +pub async fn begin_authorize_device_code_flow<'a, 'b>( |
| 36 | + client: Arc<reqwest::Client>, |
| 37 | + tenant_id: &'a str, |
| 38 | + client_id: &'a ClientId, |
| 39 | + scopes: &'b [&'b str], |
| 40 | +) -> Result<DeviceCodePhaseOneResponse<'a>, AzureError> { |
| 41 | + let mut encoded = form_urlencoded::Serializer::new(String::new()); |
| 42 | + let encoded = encoded.append_pair("client_id", client_id.as_str()); |
| 43 | + let encoded = encoded.append_pair("scope", &scopes.join(" ")); |
| 44 | + let encoded = encoded.finish(); |
| 45 | + |
| 46 | + debug!("encoded ==> {}", encoded); |
| 47 | + |
| 48 | + let url = url::Url::parse(&format!( |
| 49 | + "https://login.microsoftonline.com/{}/oauth2/v2.0/devicecode", |
| 50 | + tenant_id |
| 51 | + ))?; |
| 52 | + |
| 53 | + client |
| 54 | + .post(url) |
| 55 | + .header("ContentType", "application/x-www-form-urlencoded") |
| 56 | + .body(encoded) |
| 57 | + .send() |
| 58 | + .await |
| 59 | + .map_err(|e| AzureError::GenericErrorWithText(e.to_string()))? |
| 60 | + .text() |
| 61 | + .await |
| 62 | + .map_err(|e| AzureError::GenericErrorWithText(e.to_string())) |
| 63 | + .and_then(|s| { |
| 64 | + serde_json::from_str::<DeviceCodePhaseOneResponse>(&s) |
| 65 | + // we need to capture some variables that will be useful in |
| 66 | + // the second phase (the client, the tenant_id and the client_id) |
| 67 | + .map(|device_code_reponse| DeviceCodePhaseOneResponse { |
| 68 | + device_code: device_code_reponse.device_code, |
| 69 | + user_code: device_code_reponse.user_code, |
| 70 | + verification_uri: device_code_reponse.verification_uri, |
| 71 | + expires_in: device_code_reponse.expires_in, |
| 72 | + interval: device_code_reponse.interval, |
| 73 | + message: device_code_reponse.message, |
| 74 | + client: client.clone(), |
| 75 | + tenant_id, |
| 76 | + client_id: client_id.as_str().to_string(), |
| 77 | + }) |
| 78 | + .map_err(|e| { |
| 79 | + serde_json::from_str::<crate::errors::ErrorResponse>(&s) |
| 80 | + .map(|er| AzureError::GenericErrorWithText(er.to_string())) |
| 81 | + .unwrap_or_else(|_| { |
| 82 | + AzureError::GenericErrorWithText(format!( |
| 83 | + "Failed to parse Azure response: {}", |
| 84 | + e.to_string() |
| 85 | + )) |
| 86 | + }) |
| 87 | + }) |
| 88 | + }) |
| 89 | +} |
| 90 | + |
| 91 | +impl<'a> DeviceCodePhaseOneResponse<'a> { |
| 92 | + pub fn message(&self) -> &str { |
| 93 | + &self.message |
| 94 | + } |
| 95 | + |
| 96 | + pub fn stream( |
| 97 | + &self, |
| 98 | + ) -> impl futures::Stream<Item = Result<DeviceCodeResponse, DeviceCodeError>> + '_ { |
| 99 | + #[derive(Debug, Clone, PartialEq)] |
| 100 | + enum NextState { |
| 101 | + Continue, |
| 102 | + Finish, |
| 103 | + } |
| 104 | + |
| 105 | + unfold( |
| 106 | + NextState::Continue, |
| 107 | + async move |state: NextState| match state { |
| 108 | + NextState::Continue => { |
| 109 | + let uri = format!( |
| 110 | + "https://login.microsoftonline.com/{}/oauth2/v2.0/token", |
| 111 | + self.tenant_id, |
| 112 | + ); |
| 113 | + |
| 114 | + // throttle down as specified by Azure. This could be |
| 115 | + // smarter: we could calculate the elapsed time since the |
| 116 | + // last poll and wait only the delta. For now we do not |
| 117 | + // need such precision. |
| 118 | + new_timer(Duration::from_secs(self.interval)).await; |
| 119 | + debug!("posting to {}", &uri); |
| 120 | + |
| 121 | + let mut encoded = form_urlencoded::Serializer::new(String::new()); |
| 122 | + let encoded = encoded |
| 123 | + .append_pair("grant_type", "urn:ietf:params:oauth:grant-type:device_code"); |
| 124 | + let encoded = encoded.append_pair("client_id", self.client_id.as_str()); |
| 125 | + let encoded = encoded.append_pair("device_code", &self.device_code); |
| 126 | + let encoded = encoded.finish(); |
| 127 | + |
| 128 | + let result = match self |
| 129 | + .client |
| 130 | + .post(&uri) |
| 131 | + .header("ContentType", "application/x-www-form-urlencoded") |
| 132 | + .body(encoded) |
| 133 | + .send() |
| 134 | + .await |
| 135 | + .map_err(DeviceCodeError::ReqwestError) |
| 136 | + { |
| 137 | + Ok(result) => result, |
| 138 | + Err(error) => return Some((Err(error), NextState::Finish)), |
| 139 | + }; |
| 140 | + debug!("result (raw) ==> {:?}", result); |
| 141 | + |
| 142 | + let result = match result.text().await.map_err(DeviceCodeError::ReqwestError) { |
| 143 | + Ok(result) => result, |
| 144 | + Err(error) => return Some((Err(error), NextState::Finish)), |
| 145 | + }; |
| 146 | + debug!("result (as text) ==> {}", result); |
| 147 | + |
| 148 | + // here either we get an error response from Azure |
| 149 | + // or we get a success. A success can be either "Pending" or |
| 150 | + // "Completed". We finish the loop only on "Completed" (ie Success) |
| 151 | + match result.try_into() { |
| 152 | + Ok(device_code_response) => { |
| 153 | + let next_state = match &device_code_response { |
| 154 | + DeviceCodeResponse::AuthorizationSucceded(_) => NextState::Finish, |
| 155 | + DeviceCodeResponse::AuthorizationPending(_) => NextState::Continue, |
| 156 | + }; |
| 157 | + |
| 158 | + Some((Ok(device_code_response), next_state)) |
| 159 | + } |
| 160 | + Err(error) => Some((Err(error), NextState::Finish)), |
| 161 | + } |
| 162 | + } |
| 163 | + NextState::Finish => None, |
| 164 | + }, |
| 165 | + ) |
| 166 | + } |
| 167 | +} |
0 commit comments