Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add injectable token provider for authenticated endpoints #248

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions ng-swagger-gen.js
Original file line number Diff line number Diff line change
Expand Up @@ -1167,12 +1167,21 @@ function processServices(swagger, models, options) {
descriptor.operationIds
);

var hasBearerAuth = !!(def.security && (def.security.filter(v => v && v.hasOwnProperty('bearer'))).length > 0);

var parameters = def.parameters || [];

if (methodParameters) {
parameters = parameters.concat(methodParameters);
}

var tokenParameter = null;
if (hasBearerAuth) {
var tokenParameterIdx = parameters.findIndex(param => !!(param.in === 'header' && (param.name || '').match(/authorization/i)));
var param = parameters.splice(tokenParameterIdx, 1)[0];
tokenParameter = { paramName: param.name, paramIn: param.in };
}

var paramsClass = null;
var paramsClassComments = null;
if (parameters.length >= minParamsForContainer) {
Expand All @@ -1197,6 +1206,7 @@ function processServices(swagger, models, options) {
var paramDescriptor = {
paramName: param.name,
paramIn: param.in,
paramPlaceholderVar: 'paramValue_' + paramVar,
paramVar: paramVar,
paramFullVar: (paramsClass == null ? '' : 'params.') + paramVar,
paramRequired: param.required === true || param.in === 'path',
Expand Down Expand Up @@ -1296,6 +1306,7 @@ function processServices(swagger, models, options) {
operationHttpResponseType: '__StrictHttpResponse<' + resultType + '>',
operationComments: toComments(docString, 1),
operationParameters: operationParameters,
tokenParameter: tokenParameter,
operationResponses: operationResponses,
};
var modelResult = models[normalizeModelName(removeBrackets(resultType))];
Expand Down
24 changes: 14 additions & 10 deletions templates/operationResponse.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,21 @@
__body = __formData;{{/operationIsMultipart}}
{{#operationParameters}}{{>parameter}}
{{/operationParameters}}
let req = new HttpRequest<any>(
'{{operationMethod}}',
this.rootUrl + `{{{operationPathExpression}}}`,
__body,
{
headers: __headers,
params: __params,
responseType: '{{{operationResponseType}}}'
});
return {{#tokenParameter}}this.tokenProvider('{{paramName}}'){{/tokenParameter}}{{^tokenParameter}}__of(null){{/tokenParameter}}.pipe(
__switchMap(_token => {
{{#tokenParameter}}if (_token != null) __headers = __headers.set('{{paramName}}', _token.toString());
{{/tokenParameter}}let req = new HttpRequest<any>(
'{{operationMethod}}',
this.rootUrl + `{{{operationPathExpression}}}`,
__body,
{
headers: __headers,
params: __params,
responseType: '{{{operationResponseType}}}'
});

return this.http.request<any>(req).pipe(
return this.http.request<any>(req);
}),
__filter(_r => _r instanceof HttpResponse),
__map((_r) => {
{{#operationIsVoid}}return (_r as HttpResponse<any>).clone({ body: null }) as {{{operationHttpResponseType}}}{{/operationIsVoid
Expand Down
23 changes: 18 additions & 5 deletions templates/service.mustache
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
/* tslint:disable */
import { Injectable } from '@angular/core';
import { Injectable, InjectionToken, Optional, Inject } from '@angular/core';
import { HttpClient, HttpRequest, HttpResponse, HttpHeaders } from '@angular/common/http';
import { BaseService as __BaseService } from '../base-service';
import { {{ configurationClass }} as __Configuration } from '../{{configurationFile}}';
import { StrictHttpResponse as __StrictHttpResponse } from '../strict-http-response';
import { Observable as __Observable } from 'rxjs';
import { map as __map, filter as __filter } from 'rxjs/operators';
import { Observable as __Observable, of as __of } from 'rxjs';
import { map as __map, filter as __filter, switchMap as __switchMap } from 'rxjs/operators';

interface {{serviceClass}}TokenProvider {
getToken: (name: string) => __Observable<string>;
}

const {{serviceClass}}TokenProviderInjectionToken = new InjectionToken<{{serviceClass}}TokenProvider>('{{serviceClass}}TokenProviderInjectionToken')

{{#serviceDependencies}}import { {{modelClass}} } from '../models/{{modelFile}}';
{{/serviceDependencies}}
Expand All @@ -15,12 +21,19 @@ import { map as __map, filter as __filter } from 'rxjs/operators';
class {{serviceClass}} extends __BaseService {
{{#serviceOperations}}{{>operationEndpoints}}{{/serviceOperations}}

private tokenProvider: (name: string) => __Observable<string> = _ => __of(null);

constructor(
config: __Configuration,
http: HttpClient
http: HttpClient,
@Optional() @Inject({{serviceClass}}TokenProviderInjectionToken) tokenProvider: {{serviceClass}}TokenProvider,
) {
super(config, http);
if (tokenProvider) {
this.tokenProvider = (v: string) => tokenProvider.getToken(v);
}
}

{{#serviceOperations}}{{>operationResponse}}{{>operationBody}}{{/serviceOperations}}
}

Expand All @@ -34,4 +47,4 @@ module {{serviceClass}} {
{{/operationParamsClass}}{{/serviceOperations}}
}

export { {{serviceClass}} }
export { {{serviceClass}}, {{serviceClass}}TokenProvider, {{serviceClass}}TokenProviderInjectionToken }
2 changes: 1 addition & 1 deletion templates/services.mustache
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{{#services}}
export { {{serviceClass}} } from './services/{{serviceFile}}';
export { {{serviceClass}}, {{serviceClass}}TokenProvider, {{serviceClass}}TokenProviderInjectionToken } from './services/{{serviceFile}}';
{{/services}}