changeset 135:c8b387f52907

Don't do authorization on methods not needing it.
author Lewin Bormann <lbo@spheniscida.de>
date Mon, 26 Oct 2020 18:25:06 +0100
parents 9327368fb3f6
children 798df1eb1fd2
files generate/generate.py generate/templates.py
diffstat 2 files changed, 34 insertions(+), 12 deletions(-) [+]
line wrap: on
line diff
--- a/generate/generate.py	Mon Oct 26 18:22:43 2020 +0100
+++ b/generate/generate.py	Mon Oct 26 18:25:06 2020 +0100
@@ -16,7 +16,6 @@
 
 from templates import *
 
-
 def optionalize(name, optional=True):
     return 'Option<{}>'.format(name) if optional else name
 
@@ -24,6 +23,7 @@
 def replace_keywords(name):
     return {
         'type': ('typ', 'type'),
+        'enum': ('enums', 'enum'),
     }.get(name, name)
 
 
@@ -283,6 +283,7 @@
         out_type = method['response']['$ref'] if 'response' in method else '()'
 
         is_download = method.get('supportsMediaDownload', False)
+        is_authd = 'scopes' in method
 
         media_upload = method.get('mediaUpload', {})
         supported_uploads = []
@@ -336,7 +337,8 @@
                 'description':
                 method.get('description', ''),
                 'http_method':
-                http_method
+                http_method,
+                'wants_auth': is_authd,
             }
             method_fragments.append(chevron.render(DownloadMethodTmpl, data_download))
         else:
@@ -368,7 +370,8 @@
                 'description':
                 method.get('description', ''),
                 'http_method':
-                http_method
+                http_method,
+                'wants_auth': is_authd,
             }
             method_fragments.append(chevron.render(NormalMethodTmpl, data_normal))
 
@@ -396,6 +399,7 @@
             }],
             'description': method.get('description', ''),
             'http_method': http_method,
+            'wants_auth': is_authd,
         }
         if 'simple' in supported_uploads:
             method_fragments.append(chevron.render(UploadMethodTmpl, data_upload))
@@ -411,7 +415,6 @@
             } for t in method_fragments]
         }) + '\n'.join(subresource_fragments)
 
-
 def generate_scopes_type(name, scopes):
     """Generate types for the `scopes` dictionary (path: auth.oauth2.scopes in a discovery document),
     containing { scope_url: { description: "..." } }.
--- a/generate/templates.py	Mon Oct 26 18:22:43 2020 +0100
+++ b/generate/templates.py	Mon Oct 26 18:25:06 2020 +0100
@@ -129,6 +129,9 @@
 
     let rel_path = {{{rel_path_expr}}};
     let path = "{{{base_path}}}".to_string() + &rel_path;
+
+    let mut headers = vec![];
+    {{#wants_auth}}
     let tok;
     if self.scopes.is_empty() {
         let scopes = &[{{#scopes}}"{{{scope}}}".to_string(),
@@ -137,6 +140,9 @@
     } else {
         tok = self.authenticator.token(&self.scopes).await?;
     }
+    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
+    {{/wants_auth}}
+
     let mut url_params = format!("?{params}", params=params);
     {{#global_params_name}}
     if let Some(ref api_params) = &params.{{{global_params_name}}} {
@@ -151,7 +157,7 @@
     let opt_request = Some(req);
     {{/in_type}}
     do_request(&self.client, &full_uri,
-        &[(hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str()))],
+        &headers,
         "{{{http_method}}}", opt_request).await
   }
 '''
@@ -170,6 +176,8 @@
     let rel_path = {{{simple_rel_path_expr}}};
     let path = "{{{base_path}}}".to_string() + &rel_path;
 
+    let mut headers = vec![];
+    {{#wants_auth}}
     let tok;
     if self.scopes.is_empty() {
         let scopes = &[{{#scopes}}"{{{scope}}}".to_string(),
@@ -178,6 +186,9 @@
     } else {
         tok = self.authenticator.token(&self.scopes).await?;
     }
+    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
+    {{/wants_auth}}
+
     let mut url_params = format!("?uploadType=multipart{params}", params=params);
 
     {{#global_params_name}}
@@ -193,7 +204,7 @@
     {{/in_type}}
 
     do_upload_multipart(&self.client, &full_uri,
-        &[(hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str()))],
+        &headers,
         "{{{http_method}}}", opt_request, data).await
   }
 '''
@@ -215,6 +226,9 @@
 
     let rel_path = {{{resumable_rel_path_expr}}};
     let path = "{{{base_path}}}".to_string() + &rel_path;
+
+    let mut headers = vec![];
+    {{#wants_auth}}
     let tok;
     if self.scopes.is_empty() {
         let scopes = &[{{#scopes}}"{{{scope}}}".to_string(),
@@ -223,6 +237,9 @@
     } else {
         tok = self.authenticator.token(&self.scopes).await?;
     }
+    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
+    {{/wants_auth}}
+
     let mut url_params = format!("?uploadType=resumable{params}", params=params);
     {{#global_params_name}}
     if let Some(ref api_params) = &params.{{{global_params_name}}} {
@@ -237,7 +254,7 @@
     let opt_request = Some(req);
     {{/in_type}}
     let (_resp, headers): (EmptyResponse, hyper::HeaderMap) = do_request_with_headers(
-        &self.client, &full_uri, &[(hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str()))], "{{{http_method}}}", opt_request).await?;
+        &self.client, &full_uri, &headers, "{{{http_method}}}", opt_request).await?;
     if let Some(dest) = headers.get(hyper::header::LOCATION) {
         use std::convert::TryFrom;
         Ok(ResumableUpload::new(hyper::Uri::try_from(dest.to_str()?)?, &self.client, 5*1024*1024))
@@ -256,10 +273,7 @@
 DownloadMethodTmpl = '''
 /// {{{description}}}
 ///
-/// This method downloads data. Depending on the server returning a `Content-Type` of `application/json`
-/// or a non-JSON type, the returned value indicates if a download took place or data was written to
-/// `dst`. If `dst` is `None` despite data being available for download, `ApiError::DataAvailableError`
-/// is returned.
+/// This method potentially downloads data. See documentation of `Download`.
 pub async fn {{{name}}}<'a>(
     &'a mut self, params: &{{{param_type}}}, {{#in_type}}req: &'a {{{in_type}}}{{/in_type}})
     -> Result<Download<'a, {{{download_in_type}}}, {{{out_type}}}>> {
@@ -267,6 +281,8 @@
     let rel_path = {{{rel_path_expr}}};
     let path = "{{{base_path}}}".to_string() + &rel_path;
 
+    let mut headers = vec![];
+    {{#wants_auth}}
     let tok;
     if self.scopes.is_empty() {
         let scopes = &[{{#scopes}}"{{{scope}}}".to_string(),
@@ -275,6 +291,9 @@
     } else {
         tok = self.authenticator.token(&self.scopes).await?;
     }
+    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
+    {{/wants_auth}}
+
     let mut url_params = format!("?{params}", params=params);
     {{#global_params_name}}
     if let Some(ref api_params) = &params.{{{global_params_name}}} {
@@ -289,7 +308,7 @@
     {{/in_type}}
 
     do_download(&self.client, &full_uri,
-        vec![(hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str()))],
+        headers,
         "{{{http_method}}}".into(), opt_request).await
   }
 '''