Skip to content

Commit

Permalink
add auth generation for dart jaguar
Browse files Browse the repository at this point in the history
  • Loading branch information
jaumard committed Sep 21, 2018
1 parent 012247b commit 4dde500
Show file tree
Hide file tree
Showing 11 changed files with 195 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,18 @@ public void processOpts() {

final String libFolder = sourceFolder + File.separator + "lib";
supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml"));
supportingFiles.add(new SupportingFile("analysis_options.mustache", "", ".analysis_options"));
supportingFiles.add(new SupportingFile("analysis_options.mustache", "", "analysis_options.yaml"));
supportingFiles.add(new SupportingFile("apilib.mustache", libFolder, "api.dart"));

supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));

final String authFolder = sourceFolder + File.separator + "lib" + File.separator + "auth";
supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart"));
supportingFiles.add(new SupportingFile("auth/basic_auth.mustache", authFolder, "basic_auth.dart"));
supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart"));
supportingFiles.add(new SupportingFile("auth/auth.mustache", authFolder, "auth.dart"));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class {{classname}} extends _${{classname}}Client implements ApiClient {
/// {{summary}}
///
/// {{notes}}
@{{httpMethod}}Req(path: '{{path}}')
@{{httpMethod}}Req(path: "{{path}}"{{#hasAuthMethods}}, metadata: {"auth": [{{#authMethods}} {"type": "{{type}}", "name": "{{name}}"{{#isApiKey}}, "keyName": "{{keyParamName}}", "where": "{{#isKeyInQuery}}query{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}"{{/isApiKey}} }{{#hasMore}}, {{/hasMore}}{{/authMethods}}]}{{/hasAuthMethods}})
Future<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{nickname}}(
{{#pathParams}}
{{dataType}} {{paramName}}{{#hasMore}}, {{/hasMore}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
library {{pubName}}.api;

import 'package:http/http.dart';
import 'package:jaguar_serializer/jaguar_serializer.dart';
import 'package:jaguar_retrofit/jaguar_retrofit.dart';
import 'package:{{pubName}}/auth/api_key_auth.dart';
import 'package:{{pubName}}/auth/basic_auth.dart';
import 'package:{{pubName}}/auth/oauth.dart';

{{#apiInfo}}{{#apis}}import 'package:{{pubName}}/api/{{classFilename}}.dart';
{{/apis}}{{/apiInfo}}
Expand All @@ -12,19 +16,52 @@ final jsonJaguarRepo = JsonRepo()
{{#models}}{{#model}}..add({{classname}}Serializer())
{{/model}}{{/models}};

final baseSwaggerPath = "{{basePath}}";
final _baseRoute = Route(baseSwaggerPath);
final _defaultInterceptors = [OAuthInterceptor(), BasicAuthInterceptor(), ApiKeyAuthInterceptor()];

class SwaggerGen {
final List<Interceptor> interceptors;
SwaggerGen({this.interceptors = const []}) {
interceptors.forEach((interceptor) {
List<Interceptor> interceptors;
String baseSwaggerPath = "{{basePath}}";
Route _baseRoute;
/**
* Add custom global interceptors, put overrideInterceptors to true to set your interceptors only (auth interceptors will not be added)
*/
SwaggerGen({List<Interceptor> interceptors, bool overrideInterceptors = false, String baseUrl}) {
_baseRoute = Route(baseUrl ?? baseSwaggerPath).withClient(globalClient ?? IOClient());
if(interceptors == null) {
this.interceptors = _defaultInterceptors;
}
else if(overrideInterceptors){
this.interceptors = interceptors;
}
else {
this.interceptors = List.from(_defaultInterceptors)..addAll(interceptors);
}

this.interceptors.forEach((interceptor) {
_baseRoute.before(interceptor.before);
_baseRoute.after(interceptor.after);
});
}

{{#apiInfo}}{{#apis}}{{classname}} get{{classname}}({Route base, SerializerRepo serializers}) {
void setOAuthToken(String name, String token) {
(_defaultInterceptors[0] as OAuthInterceptor).tokens[name] = token;
}

void setBasicAuth(String name, String username, String password) {
(_defaultInterceptors[1] as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password);
}

void setApiKey(String name, String apiKey) {
(_defaultInterceptors[2] as ApiKeyAuthInterceptor).apiKeys[name] = apiKey;
}

{{#apiInfo}}{{#apis}}
/**
* Get {{classname}} instance, base route and serializer can be overridden by a given but be careful,
* by doing that all interceptors will not be executed
*/
{{classname}} get{{classname}}({Route base, SerializerRepo serializers}) {
if(base == null) {
base = _baseRoute;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
library openapi.api;

import 'package:http/http.dart';
import 'package:jaguar_serializer/jaguar_serializer.dart';
import 'package:jaguar_retrofit/jaguar_retrofit.dart';
import 'package:openapi/auth/api_key_auth.dart';
import 'package:openapi/auth/basic_auth.dart';
import 'package:openapi/auth/oauth.dart';

import 'package:openapi/api/pet_api.dart';
import 'package:openapi/api/store_api.dart';
Expand All @@ -24,18 +28,51 @@ final jsonJaguarRepo = JsonRepo()
..add(UserSerializer())
;

final baseSwaggerPath = "http://petstore.swagger.io/v2";
final _baseRoute = Route(baseSwaggerPath);
final _defaultInterceptors = [OAuthInterceptor(), BasicAuthInterceptor(), ApiKeyAuthInterceptor()];

class SwaggerGen {
final List<Interceptor> interceptors;
SwaggerGen({this.interceptors = const []}) {
interceptors.forEach((interceptor) {
List<Interceptor> interceptors;
String baseSwaggerPath = "http://petstore.swagger.io/v2";
Route _baseRoute;

/**
* Add custom global interceptors, put overrideInterceptors to true to set your interceptors only (auth interceptors will not be added)
*/
SwaggerGen({List<Interceptor> interceptors, bool overrideInterceptors = false, String baseUrl}) {
_baseRoute = Route(baseUrl ?? baseSwaggerPath).withClient(globalClient ?? IOClient());
if(interceptors == null) {
this.interceptors = _defaultInterceptors;
}
else if(overrideInterceptors){
this.interceptors = interceptors;
}
else {
this.interceptors = List.from(_defaultInterceptors)..addAll(interceptors);
}

this.interceptors.forEach((interceptor) {
_baseRoute.before(interceptor.before);
_baseRoute.after(interceptor.after);
});
}

void setOAuthToken(String name, String token) {
(_defaultInterceptors[0] as OAuthInterceptor).tokens[name] = token;
}

void setBasicAuth(String name, String username, String password) {
(_defaultInterceptors[1] as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password);
}

void setApiKey(String name, String apiKey) {
(_defaultInterceptors[2] as ApiKeyAuthInterceptor).apiKeys[name] = apiKey;
}


/**
* Get PetApi instance, base route and serializer can be overridden by a given but be careful,
* by doing that all interceptors will not be executed
*/
PetApi getPetApi({Route base, SerializerRepo serializers}) {
if(base == null) {
base = _baseRoute;
Expand All @@ -46,6 +83,11 @@ class SwaggerGen {
return PetApi(base: base, serializers: serializers);
}


/**
* Get StoreApi instance, base route and serializer can be overridden by a given but be careful,
* by doing that all interceptors will not be executed
*/
StoreApi getStoreApi({Route base, SerializerRepo serializers}) {
if(base == null) {
base = _baseRoute;
Expand All @@ -56,6 +98,11 @@ class SwaggerGen {
return StoreApi(base: base, serializers: serializers);
}


/**
* Get UserApi instance, base route and serializer can be overridden by a given but be careful,
* by doing that all interceptors will not be executed
*/
UserApi getUserApi({Route base, SerializerRepo serializers}) {
if(base == null) {
base = _baseRoute;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class PetApi extends _$PetApiClient implements ApiClient {
/// Add a new pet to the store
///
///
@PostReq(path: '/pet')
@PostReq(path: "/pet", metadata: {"auth": [ {"type": "oauth2", "name": "petstore_auth" }]})
Future<void> addPet(

@AsJson() Pet pet
Expand All @@ -29,7 +29,7 @@ class PetApi extends _$PetApiClient implements ApiClient {
/// Deletes a pet
///
///
@DeleteReq(path: '/pet/:petId')
@DeleteReq(path: "/pet/:petId", metadata: {"auth": [ {"type": "oauth2", "name": "petstore_auth" }]})
Future<void> deletePet(
int petId
,
Expand All @@ -39,7 +39,7 @@ class PetApi extends _$PetApiClient implements ApiClient {
/// Finds Pets by status
///
/// Multiple status values can be provided with comma separated strings
@GetReq(path: '/pet/findByStatus')
@GetReq(path: "/pet/findByStatus", metadata: {"auth": [ {"type": "oauth2", "name": "petstore_auth" }]})
Future<List<Pet>> findPetsByStatus(

@QueryParam("status") List<String> status
Expand All @@ -48,7 +48,7 @@ class PetApi extends _$PetApiClient implements ApiClient {
/// Finds Pets by tags
///
/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
@GetReq(path: '/pet/findByTags')
@GetReq(path: "/pet/findByTags", metadata: {"auth": [ {"type": "oauth2", "name": "petstore_auth" }]})
Future<List<Pet>> findPetsByTags(

@QueryParam("tags") List<String> tags
Expand All @@ -57,15 +57,15 @@ class PetApi extends _$PetApiClient implements ApiClient {
/// Find pet by ID
///
/// Returns a single pet
@GetReq(path: '/pet/:petId')
@GetReq(path: "/pet/:petId", metadata: {"auth": [ {"type": "apiKey", "name": "api_key", "keyName": "api_key", "where": "header" }]})
Future<Pet> getPetById(
int petId
);

/// Update an existing pet
///
///
@PutReq(path: '/pet')
@PutReq(path: "/pet", metadata: {"auth": [ {"type": "oauth2", "name": "petstore_auth" }]})
Future<void> updatePet(

@AsJson() Pet pet
Expand All @@ -74,7 +74,7 @@ class PetApi extends _$PetApiClient implements ApiClient {
/// Updates a pet in the store with form data
///
///
@PostReq(path: '/pet/:petId')
@PostReq(path: "/pet/:petId", metadata: {"auth": [ {"type": "oauth2", "name": "petstore_auth" }]})
Future<void> updatePetWithForm(
int petId
,
Expand All @@ -86,7 +86,7 @@ class PetApi extends _$PetApiClient implements ApiClient {
/// uploads an image
///
///
@PostReq(path: '/pet/:petId/uploadImage')
@PostReq(path: "/pet/:petId/uploadImage", metadata: {"auth": [ {"type": "oauth2", "name": "petstore_auth" }]})
Future<ApiResponse> uploadFile(
int petId
,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,30 +19,30 @@ class StoreApi extends _$StoreApiClient implements ApiClient {
/// Delete purchase order by ID
///
/// For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
@DeleteReq(path: '/store/order/:orderId')
@DeleteReq(path: "/store/order/:orderId")
Future<void> deleteOrder(
String orderId
);

/// Returns pet inventories by status
///
/// Returns a map of status codes to quantities
@GetReq(path: '/store/inventory')
@GetReq(path: "/store/inventory", metadata: {"auth": [ {"type": "apiKey", "name": "api_key", "keyName": "api_key", "where": "header" }]})
Future<Map<String, int>> getInventory(
);

/// Find purchase order by ID
///
/// For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
@GetReq(path: '/store/order/:orderId')
@GetReq(path: "/store/order/:orderId")
Future<Order> getOrderById(
int orderId
);

/// Place an order for a pet
///
///
@PostReq(path: '/store/order')
@PostReq(path: "/store/order")
Future<Order> placeOrder(

@AsJson() Order order
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class UserApi extends _$UserApiClient implements ApiClient {
/// Create user
///
/// This can only be done by the logged in user.
@PostReq(path: '/user')
@PostReq(path: "/user")
Future<void> createUser(

@AsJson() User user
Expand All @@ -28,7 +28,7 @@ class UserApi extends _$UserApiClient implements ApiClient {
/// Creates list of users with given input array
///
///
@PostReq(path: '/user/createWithArray')
@PostReq(path: "/user/createWithArray")
Future<void> createUsersWithArrayInput(

@AsJson() List<User> user
Expand All @@ -37,7 +37,7 @@ class UserApi extends _$UserApiClient implements ApiClient {
/// Creates list of users with given input array
///
///
@PostReq(path: '/user/createWithList')
@PostReq(path: "/user/createWithList")
Future<void> createUsersWithListInput(

@AsJson() List<User> user
Expand All @@ -46,23 +46,23 @@ class UserApi extends _$UserApiClient implements ApiClient {
/// Delete user
///
/// This can only be done by the logged in user.
@DeleteReq(path: '/user/:username')
@DeleteReq(path: "/user/:username")
Future<void> deleteUser(
String username
);

/// Get user by user name
///
///
@GetReq(path: '/user/:username')
@GetReq(path: "/user/:username")
Future<User> getUserByName(
String username
);

/// Logs user into the system
///
///
@GetReq(path: '/user/login')
@GetReq(path: "/user/login")
Future<String> loginUser(

@QueryParam("username") String username,
Expand All @@ -73,14 +73,14 @@ class UserApi extends _$UserApiClient implements ApiClient {
/// Logs out current logged in user session
///
///
@GetReq(path: '/user/logout')
@GetReq(path: "/user/logout")
Future<void> logoutUser(
);

/// Updated user
///
/// This can only be done by the logged in user.
@PutReq(path: '/user/:username')
@PutReq(path: "/user/:username")
Future<void> updateUser(
String username
,
Expand Down
Loading

0 comments on commit 4dde500

Please sign in to comment.