wunderlist.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. //!
  2. //! This example showcases the Wunderlist OAuth2 process for requesting access to the user's todo lists.
  3. //! Wunderlist does not implement the correct token response, so this serves as an example of how to
  4. //! implement a custom client.
  5. //!
  6. //! Before running it, you'll need to create your own wunderlist app.
  7. //!
  8. //! In order to run the example call:
  9. //!
  10. //! ```sh
  11. //! WUNDER_CLIENT_ID=xxx WUNDER_CLIENT_SECRET=yyy cargo run --example wunderlist
  12. //! ```
  13. //!
  14. //! ...and follow the instructions.
  15. //!
  16. use oauth2::TokenType;
  17. use oauth2::{
  18. basic::{
  19. BasicErrorResponse, BasicRevocationErrorResponse, BasicTokenIntrospectionResponse,
  20. BasicTokenType,
  21. },
  22. revocation::StandardRevocableToken,
  23. };
  24. // Alternatively, this can be `oauth2::curl::http_client` or a custom client.
  25. use oauth2::helpers;
  26. use oauth2::reqwest::http_client;
  27. use oauth2::{
  28. AccessToken, AuthUrl, AuthorizationCode, Client, ClientId, ClientSecret, CsrfToken,
  29. EmptyExtraTokenFields, ExtraTokenFields, RedirectUrl, RefreshToken, Scope, TokenResponse,
  30. TokenUrl,
  31. };
  32. use serde::{Deserialize, Serialize};
  33. use std::time::Duration;
  34. use std::env;
  35. use std::io::{BufRead, BufReader, Write};
  36. use std::net::TcpListener;
  37. use url::Url;
  38. type SpecialTokenResponse = NonStandardTokenResponse<EmptyExtraTokenFields>;
  39. type SpecialClient = Client<
  40. BasicErrorResponse,
  41. SpecialTokenResponse,
  42. BasicTokenType,
  43. BasicTokenIntrospectionResponse,
  44. StandardRevocableToken,
  45. BasicRevocationErrorResponse,
  46. >;
  47. fn default_token_type() -> Option<BasicTokenType> {
  48. Some(BasicTokenType::Bearer)
  49. }
  50. ///
  51. /// Non Standard OAuth2 token response.
  52. ///
  53. /// This struct includes the fields defined in
  54. /// [Section 5.1 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-5.1), as well as
  55. /// extensions defined by the `EF` type parameter.
  56. /// In this particular example token_type is optional to showcase how to deal with a non
  57. /// compliant provider.
  58. ///
  59. #[derive(Clone, Debug, Deserialize, Serialize)]
  60. pub struct NonStandardTokenResponse<EF: ExtraTokenFields> {
  61. access_token: AccessToken,
  62. // In this example wunderlist does not follow the RFC specs and don't return the
  63. // token_type. `NonStandardTokenResponse` makes the `token_type` optional.
  64. #[serde(default = "default_token_type")]
  65. token_type: Option<BasicTokenType>,
  66. #[serde(skip_serializing_if = "Option::is_none")]
  67. expires_in: Option<u64>,
  68. #[serde(skip_serializing_if = "Option::is_none")]
  69. refresh_token: Option<RefreshToken>,
  70. #[serde(rename = "scope")]
  71. #[serde(deserialize_with = "helpers::deserialize_space_delimited_vec")]
  72. #[serde(serialize_with = "helpers::serialize_space_delimited_vec")]
  73. #[serde(skip_serializing_if = "Option::is_none")]
  74. #[serde(default)]
  75. scopes: Option<Vec<Scope>>,
  76. #[serde(bound = "EF: ExtraTokenFields")]
  77. #[serde(flatten)]
  78. extra_fields: EF,
  79. }
  80. impl<EF> TokenResponse<BasicTokenType> for NonStandardTokenResponse<EF>
  81. where
  82. EF: ExtraTokenFields,
  83. BasicTokenType: TokenType,
  84. {
  85. ///
  86. /// REQUIRED. The access token issued by the authorization server.
  87. ///
  88. fn access_token(&self) -> &AccessToken {
  89. &self.access_token
  90. }
  91. ///
  92. /// REQUIRED. The type of the token issued as described in
  93. /// [Section 7.1](https://tools.ietf.org/html/rfc6749#section-7.1).
  94. /// Value is case insensitive and deserialized to the generic `TokenType` parameter.
  95. /// But in this particular case as the service is non compliant, it has a default value
  96. ///
  97. fn token_type(&self) -> &BasicTokenType {
  98. match &self.token_type {
  99. Some(t) => t,
  100. None => &BasicTokenType::Bearer,
  101. }
  102. }
  103. ///
  104. /// RECOMMENDED. The lifetime in seconds of the access token. For example, the value 3600
  105. /// denotes that the access token will expire in one hour from the time the response was
  106. /// generated. If omitted, the authorization server SHOULD provide the expiration time via
  107. /// other means or document the default value.
  108. ///
  109. fn expires_in(&self) -> Option<Duration> {
  110. self.expires_in.map(Duration::from_secs)
  111. }
  112. ///
  113. /// OPTIONAL. The refresh token, which can be used to obtain new access tokens using the same
  114. /// authorization grant as described in
  115. /// [Section 6](https://tools.ietf.org/html/rfc6749#section-6).
  116. ///
  117. fn refresh_token(&self) -> Option<&RefreshToken> {
  118. self.refresh_token.as_ref()
  119. }
  120. ///
  121. /// OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The
  122. /// scipe of the access token as described by
  123. /// [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). If included in the response,
  124. /// this space-delimited field is parsed into a `Vec` of individual scopes. If omitted from
  125. /// the response, this field is `None`.
  126. ///
  127. fn scopes(&self) -> Option<&Vec<Scope>> {
  128. self.scopes.as_ref()
  129. }
  130. }
  131. fn main() {
  132. let client_id_str = env::var("WUNDERLIST_CLIENT_ID")
  133. .expect("Missing the WUNDERLIST_CLIENT_ID environment variable.");
  134. let client_secret_str = env::var("WUNDERLIST_CLIENT_SECRET")
  135. .expect("Missing the WUNDERLIST_CLIENT_SECRET environment variable.");
  136. let wunder_client_id = ClientId::new(client_id_str.clone());
  137. let wunderlist_client_secret = ClientSecret::new(client_secret_str.clone());
  138. let auth_url = AuthUrl::new("https://www.wunderlist.com/oauth/authorize".to_string())
  139. .expect("Invalid authorization endpoint URL");
  140. let token_url = TokenUrl::new("https://www.wunderlist.com/oauth/access_token".to_string())
  141. .expect("Invalid token endpoint URL");
  142. // Set up the config for the Wunderlist OAuth2 process.
  143. let client = SpecialClient::new(
  144. wunder_client_id,
  145. Some(wunderlist_client_secret),
  146. auth_url,
  147. Some(token_url),
  148. )
  149. // This example will be running its own server at localhost:8080.
  150. // See below for the server implementation.
  151. .set_redirect_uri(
  152. RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
  153. );
  154. // Generate the authorization URL to which we'll redirect the user.
  155. let (authorize_url, csrf_state) = client.authorize_url(CsrfToken::new_random).url();
  156. println!(
  157. "Open this URL in your browser:\n{}\n",
  158. authorize_url.to_string()
  159. );
  160. // A very naive implementation of the redirect server.
  161. let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
  162. for stream in listener.incoming() {
  163. if let Ok(mut stream) = stream {
  164. let code;
  165. let state;
  166. {
  167. let mut reader = BufReader::new(&stream);
  168. let mut request_line = String::new();
  169. reader.read_line(&mut request_line).unwrap();
  170. let redirect_url = request_line.split_whitespace().nth(1).unwrap();
  171. let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
  172. let code_pair = url
  173. .query_pairs()
  174. .find(|pair| {
  175. let &(ref key, _) = pair;
  176. key == "code"
  177. })
  178. .unwrap();
  179. let (_, value) = code_pair;
  180. code = AuthorizationCode::new(value.into_owned());
  181. let state_pair = url
  182. .query_pairs()
  183. .find(|pair| {
  184. let &(ref key, _) = pair;
  185. key == "state"
  186. })
  187. .unwrap();
  188. let (_, value) = state_pair;
  189. state = CsrfToken::new(value.into_owned());
  190. }
  191. let message = "Go back to your terminal :)";
  192. let response = format!(
  193. "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
  194. message.len(),
  195. message
  196. );
  197. stream.write_all(response.as_bytes()).unwrap();
  198. println!(
  199. "Wunderlist returned the following code:\n{}\n",
  200. code.secret()
  201. );
  202. println!(
  203. "Wunderlist returned the following state:\n{} (expected `{}`)\n",
  204. state.secret(),
  205. csrf_state.secret()
  206. );
  207. // Exchange the code with a token.
  208. let token_res = client
  209. .exchange_code(code)
  210. .add_extra_param("client_id", client_id_str)
  211. .add_extra_param("client_secret", client_secret_str)
  212. .request(http_client);
  213. println!(
  214. "Wunderlist returned the following token:\n{:?}\n",
  215. token_res
  216. );
  217. break;
  218. }
  219. }
  220. }