Skip to content

Commit b443573

Browse files
euankwing328
authored andcommitted
[Rust] Implement minimal auth support (#7338)
* [Rust] Implement minimal auth support This is pretty much the bare minimum needed to get v2 auth working. This is partly based on the Go implementation. * [Rust] properly format query string * [Rust] Improve auth formatting * [Rust] Regenerate petstore sample
1 parent 6c7813e commit b443573

File tree

7 files changed

+428
-85
lines changed

7 files changed

+428
-85
lines changed

modules/swagger-codegen/src/main/resources/rust/api.mustache

Lines changed: 66 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
use std::rc::Rc;
33
use std::borrow::Borrow;
44
use std::borrow::Cow;
5+
use std::collections::HashMap;
56

67
use hyper;
78
use serde_json;
@@ -39,26 +40,71 @@ impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
3940
fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{.}}}{{/returnType}}, Error = Error<serde_json::Value>>> {
4041
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
4142
43+
{{#hasAuthMethods}}
44+
let mut auth_headers = HashMap::<String, String>::new();
45+
let mut auth_query = HashMap::<String, String>::new();
46+
{{#authMethods}}
47+
{{#isApiKey}}
48+
if let Some(ref apikey) = configuration.api_key {
49+
let key = apikey.key.clone();
50+
let val = match apikey.prefix {
51+
Some(ref prefix) => format!("{} {}", prefix, key),
52+
None => key,
53+
};
54+
{{#isKeyInHeader}}
55+
auth_headers.insert("{{keyParamName}}".to_owned(), val);
56+
{{/isKeyInHeader}}
57+
{{#isKeyInQuery}}
58+
auth_query.insert("{{keyParamName}}".to_owned(), val);
59+
{{/isKeyInQuery}}
60+
};
61+
{{/isApiKey}}
62+
{{#isBasic}}
63+
if let Some(ref auth_conf) = configuration.basic_auth {
64+
let auth = hyper::header::Authorization(
65+
hyper::header::Basic {
66+
username: auth_conf.0.to_owned(),
67+
password: auth_conf.1.to_owned(),
68+
}
69+
);
70+
auth_headers.insert("Authorization".to_owned(), auth.to_string());
71+
};
72+
{{/isBasic}}
73+
{{#isOAuth}}
74+
if let Some(ref token) = configuration.oauth_access_token {
75+
let auth = hyper::header::Authorization(
76+
hyper::header::Bearer {
77+
token: token.to_owned(),
78+
}
79+
);
80+
auth_headers.insert("Authorization".to_owned(), auth.to_string());
81+
};
82+
{{/isOAuth}}
83+
{{/authMethods}}
84+
{{/hasAuthMethods}}
4285
let method = hyper::Method::{{httpMethod}};
4386

44-
{{^hasQueryParams}}
45-
let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
46-
{{/hasQueryParams}}
47-
{{#hasQueryParams}}
48-
let query = ::url::form_urlencoded::Serializer::new(String::new())
49-
{{#queryParams}}
50-
.append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
51-
{{/queryParams}}
52-
.finish();
53-
let uri_str = format!("{}{{{path}}}{}", configuration.base_path, query{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
54-
{{/hasQueryParams}}
55-
56-
let uri = uri_str.parse();
87+
let query_string = {
88+
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
89+
{{#queryParams}}
90+
query.append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
91+
{{/queryParams}}
92+
{{#hasAuthMethods}}
93+
for (key, val) in &auth_query {
94+
query.append_pair(key, val);
95+
}
96+
{{/hasAuthMethods}}
97+
query.finish()
98+
};
99+
let uri_str = format!("{}{{{path}}}?{}", configuration.base_path, query_string{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
100+
57101
// TODO(farcaller): handle error
58102
// if let Err(e) = uri {
59103
// return Box::new(futures::future::err(e));
60104
// }
61-
let mut req = hyper::Request::new(method, uri.unwrap());
105+
let mut uri: hyper::Uri = uri_str.parse().unwrap();
106+
107+
let mut req = hyper::Request::new(method, uri);
62108

63109
if let Some(ref user_agent) = configuration.user_agent {
64110
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -73,6 +119,12 @@ impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
73119
}
74120
{{/hasHeaderParams}}
75121

122+
{{#hasAuthMethods}}
123+
for (key, val) in auth_headers {
124+
req.headers_mut().set_raw(key, val);
125+
}
126+
{{/hasAuthMethods}}
127+
76128
{{#hasBodyParam}}
77129
{{#bodyParams}}
78130
let serialized = serde_json::to_string(&{{paramName}}).unwrap();

modules/swagger-codegen/src/main/resources/rust/configuration.mustache

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
11
{{>partial_header}}
22
use hyper;
3+
use std::collections::HashMap;
34

45
pub struct Configuration<C: hyper::client::Connect> {
56
pub base_path: String,
67
pub user_agent: Option<String>,
78
pub client: hyper::client::Client<C>,
9+
pub basic_auth: Option<BasicAuth>,
10+
pub oauth_access_token: Option<String>,
11+
pub api_key: Option<ApiKey>,
12+
// TODO: take an oauth2 token source, similar to the go one
13+
}
14+
15+
pub type BasicAuth = (String, Option<String>);
16+
17+
pub struct ApiKey {
18+
pub prefix: Option<String>,
19+
pub key: String,
820
}
921

1022
impl<C: hyper::client::Connect> Configuration<C> {
@@ -13,6 +25,9 @@ impl<C: hyper::client::Connect> Configuration<C> {
1325
base_path: "{{{basePath}}}".to_owned(),
1426
user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("Swagger-Codegen/{{version}}/rust".to_owned()){{/httpUserAgent}},
1527
client: client,
28+
basic_auth: None,
29+
oauth_access_token: None,
30+
api_key: None,
1631
}
1732
}
1833
}

samples/client/petstore/rust/docs/UserApi.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ Get user by user name
132132

133133
Name | Type | Description | Notes
134134
------------- | ------------- | ------------- | -------------
135-
**username** | **String**| The name that needs to be fetched. Use user1 for testing. |
135+
**username** | **String**| The name that needs to be fetched. Use user1 for testing. |
136136

137137
### Return type
138138

samples/client/petstore/rust/src/apis/configuration.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,23 @@
99
*/
1010

1111
use hyper;
12+
use std::collections::HashMap;
1213

1314
pub struct Configuration<C: hyper::client::Connect> {
1415
pub base_path: String,
1516
pub user_agent: Option<String>,
1617
pub client: hyper::client::Client<C>,
18+
pub basic_auth: Option<BasicAuth>,
19+
pub oauth_access_token: Option<String>,
20+
pub api_key: Option<ApiKey>,
21+
// TODO: take an oauth2 token source, similar to the go one
22+
}
23+
24+
pub type BasicAuth = (String, Option<String>);
25+
26+
pub struct ApiKey {
27+
pub prefix: Option<String>,
28+
pub key: String,
1729
}
1830

1931
impl<C: hyper::client::Connect> Configuration<C> {
@@ -22,6 +34,9 @@ impl<C: hyper::client::Connect> Configuration<C> {
2234
base_path: "http://petstore.swagger.io/v2".to_owned(),
2335
user_agent: Some("Swagger-Codegen/1.0.0/rust".to_owned()),
2436
client: client,
37+
basic_auth: None,
38+
oauth_access_token: None,
39+
api_key: None,
2540
}
2641
}
2742
}

0 commit comments

Comments
 (0)