@emilgroup/public-api-sdk-node 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Emil Public Api SDK for Nodejs
2
2
 
3
- This TypeScript/JavaScript client utilizes [axios](https://github.com/axios/axios). The generated module can be used with client-based applications (i.e. React).
3
+ This TypeScript/JavaScript client utilizes [axios](https://github.com/axios/axios). The generated Node module can be used with Nodejs based applications.
4
4
 
5
5
  Language level
6
6
  * ES5 - you must have a Promises/A+ library installed
@@ -17,11 +17,11 @@ Although this package can be used in both TypeScript and JavaScript, it is inten
17
17
  Navigate to the folder of your consuming project and run one of the following commands:
18
18
 
19
19
  ```
20
- npm install @emilgroup/public-api-sdk-node@1.0.0 --save
20
+ npm install @emilgroup/public-api-sdk-node@1.0.1 --save
21
21
  ```
22
22
  or
23
23
  ```
24
- yarn add @emilgroup/public-api-sdk-node@1.0.0
24
+ yarn add @emilgroup/public-api-sdk-node@1.0.1
25
25
  ```
26
26
 
27
27
  And then you can import `PublicApi`.
@@ -31,15 +31,32 @@ import { PublicApi } from '@emilgroup/public-api-sdk-node'
31
31
 
32
32
  const publicApi = new PublicApi();
33
33
  ```
34
+ ## Credentials
34
35
 
35
- To use authentication protected endpoints, you have to first authorize. To do so, use the `authorize` function in `PublicApi`:
36
+ To use authentication protected endpoints, you have to first authorize. To do so, the easiest way is to provide a configuration file under `~/.emil/credentials` with the following content:
37
+
38
+ ```shell
39
+ emil_username=XXXXX@XXXX.XXX
40
+ emil_password=XXXXXXXXXXXXXX
41
+ ```
42
+
43
+ It is also possible to provide environment variables instead:
44
+
45
+ ```shell
46
+ export EMIL_USERNAME=XXXXX@XXXX.XXX
47
+ export EMIL_PASSWORD=XXXXXXXXXXXXXX
48
+ ```
49
+
50
+ ## Example
51
+
52
+ Here is a basic functionning example:
36
53
 
37
54
  ```ts
38
55
  async function listDocuments(): Promise<Void> {
39
56
  try {
40
57
  const publicApi = new PublicApi();
41
58
 
42
- await publicApi.authorize('username', 'password');
59
+ await publicApi.initialize(); // should be called only once per Api.
43
60
 
44
61
  const { data: { items } } = await publicApi.listDocuments();
45
62
 
@@ -22,6 +22,10 @@ import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObj
22
22
  import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../base';
23
23
  // @ts-ignore
24
24
  import { CreateDocumentRequestDto } from '../models';
25
+ // URLSearchParams not necessarily used
26
+ // @ts-ignore
27
+ import { URL, URLSearchParams } from 'url';
28
+ const FormData = require('form-data');
25
29
  /**
26
30
  * DocumentsApi - axios parameter creator
27
31
  * @export
@@ -24,6 +24,10 @@ import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } fr
24
24
  import { CompletePaymentSetupRequestDto } from '../models';
25
25
  // @ts-ignore
26
26
  import { InitiatePaymentSetupRequestDto } from '../models';
27
+ // URLSearchParams not necessarily used
28
+ // @ts-ignore
29
+ import { URL, URLSearchParams } from 'url';
30
+ const FormData = require('form-data');
27
31
  /**
28
32
  * PaymentSetupApi - axios parameter creator
29
33
  * @export
@@ -26,6 +26,10 @@ import { CreateCustomApplicationRequestDto } from '../models';
26
26
  import { CreateEstimatedInvoiceRequestDto } from '../models';
27
27
  // @ts-ignore
28
28
  import { CreateLeadRequestDto } from '../models';
29
+ // URLSearchParams not necessarily used
30
+ // @ts-ignore
31
+ import { URL, URLSearchParams } from 'url';
32
+ const FormData = require('form-data');
29
33
  /**
30
34
  * ProductsApi - axios parameter creator
31
35
  * @export
package/api.ts CHANGED
@@ -15,6 +15,10 @@
15
15
 
16
16
  import { Configuration } from './configuration';
17
17
  import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
18
+ // URLSearchParams not necessarily used
19
+ // @ts-ignore
20
+ import { URL, URLSearchParams } from 'url';
21
+ import FormData from 'form-data'
18
22
  // Some imports not used depending on template conditions
19
23
  // @ts-ignore
20
24
  import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
package/base.ts CHANGED
@@ -14,13 +14,20 @@
14
14
 
15
15
 
16
16
  import { Configuration } from "./configuration";
17
- import { defaultStorage } from "./common";
18
17
  // Some imports not used depending on template conditions
19
18
  // @ts-ignore
20
19
  import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
21
-
20
+ import * as fs from 'fs';
21
+ import * as path from 'path';
22
+ import * as os from 'os';
22
23
 
23
24
  export const BASE_PATH = "https://apiv2.emil.de".replace(/\/+$/, "");
25
+ const CONFIG_DIRECTORY = '.emil';
26
+ const CONFIG_FILENAME = 'credentials';
27
+ const KEY_USERNAME = 'emil_username';
28
+ const KEY_PASSWORD = 'emil_password';
29
+
30
+ const filePath = os.homedir() + path.sep + CONFIG_DIRECTORY + path.sep + CONFIG_FILENAME;
24
31
  /**
25
32
  *
26
33
  * @export
@@ -59,13 +66,7 @@ export interface RequestArgs {
59
66
  options: AxiosRequestConfig;
60
67
  }
61
68
 
62
- interface TokenData {
63
- accessToken?: string;
64
- username?: string;
65
- }
66
-
67
69
  const NETWORK_ERROR_MESSAGE = "Network Error";
68
- const TOKEN_DATA = 'APP_TOKEN';
69
70
 
70
71
  /**
71
72
  *
@@ -73,31 +74,75 @@ const TOKEN_DATA = 'APP_TOKEN';
73
74
  * @class BaseAPI
74
75
  */
75
76
  export class BaseAPI {
76
- protected configuration: Configuration | undefined;
77
- private tokenData?: TokenData;
78
-
79
- constructor(configuration?: Configuration,
80
- protected basePath: string = BASE_PATH,
81
- protected axios: AxiosInstance = globalAxios) {
82
-
83
- this.loadTokenData();
77
+ protected configuration: Configuration;
78
+ private username?: string;
79
+ private password?: string;
84
80
 
81
+ constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
85
82
  if (configuration) {
86
83
  this.configuration = configuration;
87
84
  this.basePath = configuration.basePath || this.basePath;
88
85
  } else {
89
- const { accessToken, username } = this.tokenData;
90
-
91
86
  this.configuration = new Configuration({
92
87
  basePath: this.basePath,
93
- accessToken: accessToken ? `Bearer ${accessToken}` : '',
94
- username,
95
88
  });
96
89
  }
97
90
 
98
91
  this.attachInterceptor(axios);
99
92
  }
100
93
 
94
+ async initialize(env: Environment = Environment.Production) {
95
+ this.configuration.basePath = env;
96
+
97
+ await this.loadCredentials();
98
+
99
+ if (this.username) {
100
+ await this.authorize(this.username, this.password);
101
+ this.password = null; // to avoid keeping password loaded in memory.
102
+ }
103
+ }
104
+
105
+ private async loadCredentials() {
106
+ try {
107
+ await this.readConfigFile();
108
+ } catch (error) {
109
+ console.warn(`No credentials file found. Check that ${filePath} exists.`);
110
+ }
111
+
112
+ this.readEnvVariables();
113
+
114
+ if (!this.username) {
115
+ console.info(`No credentials found in credentials file or environment variables. Either provide some or use
116
+ authorize() function.`);
117
+ }
118
+ }
119
+
120
+ private async readConfigFile() {
121
+ const file = await fs.promises.readFile(filePath, 'utf-8');
122
+
123
+ const lines = file.split(os.EOL)
124
+ .filter(Boolean);
125
+
126
+ lines.forEach((line: string) => {
127
+ if (line.startsWith(KEY_USERNAME)) {
128
+ this.username = line.length > KEY_USERNAME.length + 1 ? line.substring(KEY_USERNAME.length + 1) : '';
129
+ } else if (line.startsWith(KEY_PASSWORD)) {
130
+ this.password = line.length > KEY_PASSWORD.length + 1 ? line.substring(KEY_PASSWORD.length + 1) : '';
131
+ }
132
+ });
133
+ }
134
+
135
+ private readEnvVariables(): boolean {
136
+ if (process.env.EMIL_USERNAME) {
137
+ this.username = process.env.EMIL_USERNAME;
138
+ this.password = process.env.EMIL_PASSWORD || '';
139
+
140
+ return true;
141
+ }
142
+
143
+ return false;
144
+ }
145
+
101
146
  selectEnvironment(env: Environment) {
102
147
  this.configuration.basePath = env;
103
148
  }
@@ -117,21 +162,18 @@ export class BaseAPI {
117
162
  const response = await globalAxios.request<LoginClass>(options);
118
163
 
119
164
  const { data: { accessToken } } = response;
120
-
121
165
  this.configuration.username = username;
122
166
  this.configuration.accessToken = `Bearer ${accessToken}`;
123
- this.tokenData.username = username;
124
- this.tokenData.accessToken = accessToken;
125
167
 
126
- this.storeTokenData({
127
- ...this.tokenData
128
- });
168
+ const refreshToken = this.extractRefreshToken(response)
169
+ this.configuration.refreshToken = refreshToken;
129
170
  }
130
171
 
131
172
  async refreshToken(): Promise<string> {
132
- const { username } = this.configuration;
173
+ const { username, refreshToken } = this.configuration;
174
+
133
175
 
134
- if (!username) {
176
+ if (!username || !refreshToken) {
135
177
  return '';
136
178
  }
137
179
 
@@ -140,6 +182,7 @@ export class BaseAPI {
140
182
  url: `${this.configuration.basePath}/authservice/v1/refresh-token`,
141
183
  headers: {
142
184
  'Content-Type': 'application/json',
185
+ Cookie: refreshToken,
143
186
  },
144
187
  data: { username: username },
145
188
  withCredentials: true,
@@ -150,20 +193,18 @@ export class BaseAPI {
150
193
  return accessToken;
151
194
  }
152
195
 
153
- private storeTokenData(tokenData?: TokenData) {
154
- if (typeof window !== 'undefined') {
155
- defaultStorage().set<TokenData>(TOKEN_DATA, tokenData);
156
- }
157
- }
196
+ private extractRefreshToken(response: AxiosResponse): string {
197
+ if (response.headers && response.headers['set-cookie']
198
+ && response.headers['set-cookie'].length > 0) {
158
199
 
159
- public loadTokenData() {
160
- if (typeof window !== 'undefined') {
161
- this.tokenData = defaultStorage().get<TokenData>(TOKEN_DATA) || {};
200
+ return `${response.headers['set-cookie'][0].split(';')[0]};`;
162
201
  }
202
+
203
+ return '';
163
204
  }
164
205
 
165
- public cleanTokenData() {
166
- this.storeTokenData(null);
206
+ getConfiguration(): Configuration {
207
+ return this.configuration;
167
208
  }
168
209
 
169
210
  private attachInterceptor(axios: AxiosInstance) {
@@ -173,25 +214,19 @@ export class BaseAPI {
173
214
  },
174
215
  async (err) => {
175
216
  let originalConfig = err.config;
176
- if (err.response && !(err.response instanceof XMLHttpRequest)) { // sometimes buggy and is of type request
217
+ if (err.response) {
177
218
  // Access Token was expired
178
- if ((err.response.status === 401 || err.response.status === 403)
179
- && !originalConfig._retry) {
219
+ if (err.response.status === 401 && !originalConfig._retry) {
180
220
  originalConfig._retry = true;
181
221
  try {
182
- let tokenString = await this.refreshToken();
222
+ const tokenString = await this.refreshToken();
183
223
  const accessToken = `Bearer ${tokenString}`;
184
224
 
185
- delete originalConfig.headers['Authorization']
186
-
187
- originalConfig.headers['Authorization'] = accessToken;
225
+ originalConfig.headers['Authorization'] = `Bearer ${accessToken}`
188
226
 
189
227
  this.configuration.accessToken = accessToken;
190
- this.tokenData.accessToken = tokenString;
191
-
192
- this.storeTokenData(this.tokenData);
193
228
 
194
- return axios(originalConfig);
229
+ return axios.request(originalConfig);
195
230
  } catch (_error) {
196
231
  if (_error.response && _error.response.data) {
197
232
  return Promise.reject(_error.response.data);
@@ -199,22 +234,23 @@ export class BaseAPI {
199
234
  return Promise.reject(_error);
200
235
  }
201
236
  }
202
- } else if (err.message === NETWORK_ERROR_MESSAGE
237
+ if (err.response.status === 403 && err.response.data) {
238
+ return Promise.reject(err.response.data);
239
+ }
240
+ } else if(err.message === NETWORK_ERROR_MESSAGE
241
+ && err.isAxiosError
203
242
  && originalConfig.headers.hasOwnProperty('Authorization')
204
243
  && _retry_count < 4
205
- ) {
244
+ ){
206
245
  _retry_count++;
207
246
  try {
208
- let tokenString = await this.refreshToken();
247
+ const tokenString = await this.refreshToken();
209
248
  const accessToken = `Bearer ${tokenString}`;
210
249
 
211
250
  _retry = true;
212
- originalConfig.headers['Authorization'] = accessToken;
251
+ originalConfig.headers['Authorization'] = accessToken;
213
252
 
214
253
  this.configuration.accessToken = accessToken;
215
- this.tokenData.accessToken = tokenString;
216
-
217
- this.storeTokenData(this.tokenData);
218
254
 
219
255
  return axios.request({
220
256
  ...originalConfig,
@@ -224,7 +260,7 @@ export class BaseAPI {
224
260
  return Promise.reject(_error.response.data);
225
261
  }
226
262
  return Promise.reject(_error);
227
- }
263
+ }
228
264
  }
229
265
  return Promise.reject(err);
230
266
  }
package/common.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  import { Configuration } from "./configuration";
17
17
  import { RequiredError, RequestArgs } from "./base";
18
18
  import { AxiosInstance, AxiosResponse } from 'axios';
19
+ import { URL, URLSearchParams } from 'url';
19
20
  /**
20
21
  *
21
22
  * @export
package/configuration.ts CHANGED
@@ -74,6 +74,14 @@ export class Configuration {
74
74
  */
75
75
  formDataCtor?: new () => any;
76
76
 
77
+ /**
78
+ * parameter for automatically refreshing access token for oauth2 security
79
+ *
80
+ * @type {string}
81
+ * @memberof Configuration
82
+ */
83
+ refreshToken?: string;
84
+
77
85
  constructor(param: ConfigurationParameters = {}) {
78
86
  this.apiKey = param.apiKey;
79
87
  this.username = param.username;
@@ -85,6 +85,10 @@ var axios_1 = __importDefault(require("axios"));
85
85
  var common_1 = require("../common");
86
86
  // @ts-ignore
87
87
  var base_1 = require("../base");
88
+ // URLSearchParams not necessarily used
89
+ // @ts-ignore
90
+ var url_1 = require("url");
91
+ var FormData = require('form-data');
88
92
  /**
89
93
  * DocumentsApi - axios parameter creator
90
94
  * @export
@@ -109,7 +113,7 @@ var DocumentsApiAxiosParamCreator = function (configuration) {
109
113
  // verify required parameter 'createDocumentRequestDto' is not null or undefined
110
114
  (0, common_1.assertParamExists)('createTemporaryDocument', 'createDocumentRequestDto', createDocumentRequestDto);
111
115
  localVarPath = "/publicapi/v1/documents";
112
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
116
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
113
117
  if (configuration) {
114
118
  baseOptions = configuration.baseOptions;
115
119
  baseAccessToken = configuration.accessToken;
@@ -158,7 +162,7 @@ var DocumentsApiAxiosParamCreator = function (configuration) {
158
162
  (0, common_1.assertParamExists)('downloadDocument', 'code', code);
159
163
  localVarPath = "/publicapi/v1/documents/download/{code}"
160
164
  .replace("{".concat("code", "}"), encodeURIComponent(String(code)));
161
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
165
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
162
166
  if (configuration) {
163
167
  baseOptions = configuration.baseOptions;
164
168
  baseAccessToken = configuration.accessToken;
@@ -207,7 +211,7 @@ var DocumentsApiAxiosParamCreator = function (configuration) {
207
211
  switch (_a.label) {
208
212
  case 0:
209
213
  localVarPath = "/publicapi/v1/documents";
210
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
214
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
211
215
  if (configuration) {
212
216
  baseOptions = configuration.baseOptions;
213
217
  baseAccessToken = configuration.accessToken;
@@ -85,6 +85,10 @@ var axios_1 = __importDefault(require("axios"));
85
85
  var common_1 = require("../common");
86
86
  // @ts-ignore
87
87
  var base_1 = require("../base");
88
+ // URLSearchParams not necessarily used
89
+ // @ts-ignore
90
+ var url_1 = require("url");
91
+ var FormData = require('form-data');
88
92
  /**
89
93
  * PaymentSetupApi - axios parameter creator
90
94
  * @export
@@ -109,7 +113,7 @@ var PaymentSetupApiAxiosParamCreator = function (configuration) {
109
113
  // verify required parameter 'completePaymentSetupRequestDto' is not null or undefined
110
114
  (0, common_1.assertParamExists)('completePaymentSetup', 'completePaymentSetupRequestDto', completePaymentSetupRequestDto);
111
115
  localVarPath = "/publicapi/v1/payment-setup/complete";
112
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
116
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
113
117
  if (configuration) {
114
118
  baseOptions = configuration.baseOptions;
115
119
  baseAccessToken = configuration.accessToken;
@@ -157,7 +161,7 @@ var PaymentSetupApiAxiosParamCreator = function (configuration) {
157
161
  // verify required parameter 'initiatePaymentSetupRequestDto' is not null or undefined
158
162
  (0, common_1.assertParamExists)('initiatePaymentSetup', 'initiatePaymentSetupRequestDto', initiatePaymentSetupRequestDto);
159
163
  localVarPath = "/publicapi/v1/payment-setup/initiate";
160
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
164
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
161
165
  if (configuration) {
162
166
  baseOptions = configuration.baseOptions;
163
167
  baseAccessToken = configuration.accessToken;
@@ -85,6 +85,10 @@ var axios_1 = __importDefault(require("axios"));
85
85
  var common_1 = require("../common");
86
86
  // @ts-ignore
87
87
  var base_1 = require("../base");
88
+ // URLSearchParams not necessarily used
89
+ // @ts-ignore
90
+ var url_1 = require("url");
91
+ var FormData = require('form-data');
88
92
  /**
89
93
  * ProductsApi - axios parameter creator
90
94
  * @export
@@ -113,7 +117,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
113
117
  (0, common_1.assertParamExists)('createEstimatedInvoice', 'createEstimatedInvoiceRequestDto', createEstimatedInvoiceRequestDto);
114
118
  localVarPath = "/publicapi/v1/products/{product_code}/product-invoice"
115
119
  .replace("{".concat("product_code", "}"), encodeURIComponent(String(productCode)));
116
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
120
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
117
121
  if (configuration) {
118
122
  baseOptions = configuration.baseOptions;
119
123
  baseAccessToken = configuration.accessToken;
@@ -161,7 +165,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
161
165
  // verify required parameter 'createLeadRequestDto' is not null or undefined
162
166
  (0, common_1.assertParamExists)('createLead', 'createLeadRequestDto', createLeadRequestDto);
163
167
  localVarPath = "/publicapi/v1/leads";
164
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
168
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
165
169
  if (configuration) {
166
170
  baseOptions = configuration.baseOptions;
167
171
  baseAccessToken = configuration.accessToken;
@@ -213,7 +217,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
213
217
  (0, common_1.assertParamExists)('customApplication', 'createCustomApplicationRequestDto', createCustomApplicationRequestDto);
214
218
  localVarPath = "/publicapi/v1/products/{product_code}/custom-application"
215
219
  .replace("{".concat("product_code", "}"), encodeURIComponent(String(productCode)));
216
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
220
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
217
221
  if (configuration) {
218
222
  baseOptions = configuration.baseOptions;
219
223
  baseAccessToken = configuration.accessToken;
@@ -258,7 +262,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
258
262
  switch (_a.label) {
259
263
  case 0:
260
264
  localVarPath = "/publicapi/v1/products/{product_code}/insured-object-types";
261
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
265
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
262
266
  if (configuration) {
263
267
  baseOptions = configuration.baseOptions;
264
268
  baseAccessToken = configuration.accessToken;
@@ -305,7 +309,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
305
309
  (0, common_1.assertParamExists)('getInsuredObjects', 'productCode', productCode);
306
310
  localVarPath = "/publicapi/v1/products/{product_code}/insured-objects"
307
311
  .replace("{".concat("product_code", "}"), encodeURIComponent(String(productCode)));
308
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
312
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
309
313
  if (configuration) {
310
314
  baseOptions = configuration.baseOptions;
311
315
  baseAccessToken = configuration.accessToken;
@@ -352,7 +356,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
352
356
  (0, common_1.assertParamExists)('getProductCustomCss', 'productCode', productCode);
353
357
  localVarPath = "/publicapi/v1/products/{product_code}/custom-css"
354
358
  .replace("{".concat("product_code", "}"), encodeURIComponent(String(productCode)));
355
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
359
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
356
360
  if (configuration) {
357
361
  baseOptions = configuration.baseOptions;
358
362
  baseAccessToken = configuration.accessToken;
@@ -399,7 +403,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
399
403
  (0, common_1.assertParamExists)('getProductFactors', 'productCode', productCode);
400
404
  localVarPath = "/publicapi/v1/products/{product_code}/product-factors"
401
405
  .replace("{".concat("product_code", "}"), encodeURIComponent(String(productCode)));
402
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
406
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
403
407
  if (configuration) {
404
408
  baseOptions = configuration.baseOptions;
405
409
  baseAccessToken = configuration.accessToken;
@@ -442,7 +446,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
442
446
  switch (_a.label) {
443
447
  case 0:
444
448
  localVarPath = "/publicapi/v1/leads/initiate";
445
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
449
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
446
450
  if (configuration) {
447
451
  baseOptions = configuration.baseOptions;
448
452
  baseAccessToken = configuration.accessToken;
@@ -492,7 +496,7 @@ var ProductsApiAxiosParamCreator = function (configuration) {
492
496
  (0, common_1.assertParamExists)('updateLead', 'createLeadRequestDto', createLeadRequestDto);
493
497
  localVarPath = "/publicapi/v1/leads/{code}"
494
498
  .replace("{".concat("code", "}"), encodeURIComponent(String(code)));
495
- localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL);
499
+ localVarUrlObj = new url_1.URL(localVarPath, common_1.DUMMY_BASE_URL);
496
500
  if (configuration) {
497
501
  baseOptions = configuration.baseOptions;
498
502
  baseAccessToken = configuration.accessToken;
package/dist/base.d.ts CHANGED
@@ -48,15 +48,19 @@ export interface RequestArgs {
48
48
  export declare class BaseAPI {
49
49
  protected basePath: string;
50
50
  protected axios: AxiosInstance;
51
- protected configuration: Configuration | undefined;
52
- private tokenData?;
51
+ protected configuration: Configuration;
52
+ private username?;
53
+ private password?;
53
54
  constructor(configuration?: Configuration, basePath?: string, axios?: AxiosInstance);
55
+ initialize(env?: Environment): Promise<void>;
56
+ private loadCredentials;
57
+ private readConfigFile;
58
+ private readEnvVariables;
54
59
  selectEnvironment(env: Environment): void;
55
60
  authorize(username: string, password: string): Promise<void>;
56
61
  refreshToken(): Promise<string>;
57
- private storeTokenData;
58
- loadTokenData(): void;
59
- cleanTokenData(): void;
62
+ private extractRefreshToken;
63
+ getConfiguration(): Configuration;
60
64
  private attachInterceptor;
61
65
  }
62
66
  /**
package/dist/base.js CHANGED
@@ -38,6 +38,29 @@ var __assign = (this && this.__assign) || function () {
38
38
  };
39
39
  return __assign.apply(this, arguments);
40
40
  };
41
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
42
+ if (k2 === undefined) k2 = k;
43
+ var desc = Object.getOwnPropertyDescriptor(m, k);
44
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
45
+ desc = { enumerable: true, get: function() { return m[k]; } };
46
+ }
47
+ Object.defineProperty(o, k2, desc);
48
+ }) : (function(o, m, k, k2) {
49
+ if (k2 === undefined) k2 = k;
50
+ o[k2] = m[k];
51
+ }));
52
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
53
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
54
+ }) : function(o, v) {
55
+ o["default"] = v;
56
+ });
57
+ var __importStar = (this && this.__importStar) || function (mod) {
58
+ if (mod && mod.__esModule) return mod;
59
+ var result = {};
60
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
61
+ __setModuleDefault(result, mod);
62
+ return result;
63
+ };
41
64
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
42
65
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
43
66
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -80,11 +103,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
80
103
  Object.defineProperty(exports, "__esModule", { value: true });
81
104
  exports.RequiredError = exports.BaseAPI = exports.resetRetry = exports.Environment = exports.COLLECTION_FORMATS = exports.BASE_PATH = void 0;
82
105
  var configuration_1 = require("./configuration");
83
- var common_1 = require("./common");
84
106
  // Some imports not used depending on template conditions
85
107
  // @ts-ignore
86
108
  var axios_1 = __importDefault(require("axios"));
109
+ var fs = __importStar(require("fs"));
110
+ var path = __importStar(require("path"));
111
+ var os = __importStar(require("os"));
87
112
  exports.BASE_PATH = "https://apiv2.emil.de".replace(/\/+$/, "");
113
+ var CONFIG_DIRECTORY = '.emil';
114
+ var CONFIG_FILENAME = 'credentials';
115
+ var KEY_USERNAME = 'emil_username';
116
+ var KEY_PASSWORD = 'emil_password';
117
+ var filePath = os.homedir() + path.sep + CONFIG_DIRECTORY + path.sep + CONFIG_FILENAME;
88
118
  /**
89
119
  *
90
120
  * @export
@@ -107,7 +137,6 @@ function resetRetry() {
107
137
  }
108
138
  exports.resetRetry = resetRetry;
109
139
  var NETWORK_ERROR_MESSAGE = "Network Error";
110
- var TOKEN_DATA = 'APP_TOKEN';
111
140
  /**
112
141
  *
113
142
  * @export
@@ -119,27 +148,101 @@ var BaseAPI = /** @class */ (function () {
119
148
  if (axios === void 0) { axios = axios_1.default; }
120
149
  this.basePath = basePath;
121
150
  this.axios = axios;
122
- this.loadTokenData();
123
151
  if (configuration) {
124
152
  this.configuration = configuration;
125
153
  this.basePath = configuration.basePath || this.basePath;
126
154
  }
127
155
  else {
128
- var _a = this.tokenData, accessToken = _a.accessToken, username = _a.username;
129
156
  this.configuration = new configuration_1.Configuration({
130
157
  basePath: this.basePath,
131
- accessToken: accessToken ? "Bearer ".concat(accessToken) : '',
132
- username: username,
133
158
  });
134
159
  }
135
160
  this.attachInterceptor(axios);
136
161
  }
162
+ BaseAPI.prototype.initialize = function (env) {
163
+ if (env === void 0) { env = Environment.Production; }
164
+ return __awaiter(this, void 0, void 0, function () {
165
+ return __generator(this, function (_a) {
166
+ switch (_a.label) {
167
+ case 0:
168
+ this.configuration.basePath = env;
169
+ return [4 /*yield*/, this.loadCredentials()];
170
+ case 1:
171
+ _a.sent();
172
+ if (!this.username) return [3 /*break*/, 3];
173
+ return [4 /*yield*/, this.authorize(this.username, this.password)];
174
+ case 2:
175
+ _a.sent();
176
+ this.password = null; // to avoid keeping password loaded in memory.
177
+ _a.label = 3;
178
+ case 3: return [2 /*return*/];
179
+ }
180
+ });
181
+ });
182
+ };
183
+ BaseAPI.prototype.loadCredentials = function () {
184
+ return __awaiter(this, void 0, void 0, function () {
185
+ var error_1;
186
+ return __generator(this, function (_a) {
187
+ switch (_a.label) {
188
+ case 0:
189
+ _a.trys.push([0, 2, , 3]);
190
+ return [4 /*yield*/, this.readConfigFile()];
191
+ case 1:
192
+ _a.sent();
193
+ return [3 /*break*/, 3];
194
+ case 2:
195
+ error_1 = _a.sent();
196
+ console.warn("No credentials file found. Check that ".concat(filePath, " exists."));
197
+ return [3 /*break*/, 3];
198
+ case 3:
199
+ this.readEnvVariables();
200
+ if (!this.username) {
201
+ console.info("No credentials found in credentials file or environment variables. Either provide some or use \n authorize() function.");
202
+ }
203
+ return [2 /*return*/];
204
+ }
205
+ });
206
+ });
207
+ };
208
+ BaseAPI.prototype.readConfigFile = function () {
209
+ return __awaiter(this, void 0, void 0, function () {
210
+ var file, lines;
211
+ var _this = this;
212
+ return __generator(this, function (_a) {
213
+ switch (_a.label) {
214
+ case 0: return [4 /*yield*/, fs.promises.readFile(filePath, 'utf-8')];
215
+ case 1:
216
+ file = _a.sent();
217
+ lines = file.split(os.EOL)
218
+ .filter(Boolean);
219
+ lines.forEach(function (line) {
220
+ if (line.startsWith(KEY_USERNAME)) {
221
+ _this.username = line.length > KEY_USERNAME.length + 1 ? line.substring(KEY_USERNAME.length + 1) : '';
222
+ }
223
+ else if (line.startsWith(KEY_PASSWORD)) {
224
+ _this.password = line.length > KEY_PASSWORD.length + 1 ? line.substring(KEY_PASSWORD.length + 1) : '';
225
+ }
226
+ });
227
+ return [2 /*return*/];
228
+ }
229
+ });
230
+ });
231
+ };
232
+ BaseAPI.prototype.readEnvVariables = function () {
233
+ if (process.env.EMIL_USERNAME) {
234
+ this.username = process.env.EMIL_USERNAME;
235
+ this.password = process.env.EMIL_PASSWORD || '';
236
+ return true;
237
+ }
238
+ return false;
239
+ };
137
240
  BaseAPI.prototype.selectEnvironment = function (env) {
138
241
  this.configuration.basePath = env;
139
242
  };
140
243
  BaseAPI.prototype.authorize = function (username, password) {
141
244
  return __awaiter(this, void 0, void 0, function () {
142
- var options, response, accessToken;
245
+ var options, response, accessToken, refreshToken;
143
246
  return __generator(this, function (_a) {
144
247
  switch (_a.label) {
145
248
  case 0:
@@ -159,9 +262,8 @@ var BaseAPI = /** @class */ (function () {
159
262
  accessToken = response.data.accessToken;
160
263
  this.configuration.username = username;
161
264
  this.configuration.accessToken = "Bearer ".concat(accessToken);
162
- this.tokenData.username = username;
163
- this.tokenData.accessToken = accessToken;
164
- this.storeTokenData(__assign({}, this.tokenData));
265
+ refreshToken = this.extractRefreshToken(response);
266
+ this.configuration.refreshToken = refreshToken;
165
267
  return [2 /*return*/];
166
268
  }
167
269
  });
@@ -169,12 +271,12 @@ var BaseAPI = /** @class */ (function () {
169
271
  };
170
272
  BaseAPI.prototype.refreshToken = function () {
171
273
  return __awaiter(this, void 0, void 0, function () {
172
- var username, options, accessToken;
173
- return __generator(this, function (_a) {
174
- switch (_a.label) {
274
+ var _a, username, refreshToken, options, accessToken;
275
+ return __generator(this, function (_b) {
276
+ switch (_b.label) {
175
277
  case 0:
176
- username = this.configuration.username;
177
- if (!username) {
278
+ _a = this.configuration, username = _a.username, refreshToken = _a.refreshToken;
279
+ if (!username || !refreshToken) {
178
280
  return [2 /*return*/, ''];
179
281
  }
180
282
  options = {
@@ -182,30 +284,28 @@ var BaseAPI = /** @class */ (function () {
182
284
  url: "".concat(this.configuration.basePath, "/authservice/v1/refresh-token"),
183
285
  headers: {
184
286
  'Content-Type': 'application/json',
287
+ Cookie: refreshToken,
185
288
  },
186
289
  data: { username: username },
187
290
  withCredentials: true,
188
291
  };
189
292
  return [4 /*yield*/, axios_1.default.request(options)];
190
293
  case 1:
191
- accessToken = (_a.sent()).data.accessToken;
294
+ accessToken = (_b.sent()).data.accessToken;
192
295
  return [2 /*return*/, accessToken];
193
296
  }
194
297
  });
195
298
  });
196
299
  };
197
- BaseAPI.prototype.storeTokenData = function (tokenData) {
198
- if (typeof window !== 'undefined') {
199
- (0, common_1.defaultStorage)().set(TOKEN_DATA, tokenData);
200
- }
201
- };
202
- BaseAPI.prototype.loadTokenData = function () {
203
- if (typeof window !== 'undefined') {
204
- this.tokenData = (0, common_1.defaultStorage)().get(TOKEN_DATA) || {};
300
+ BaseAPI.prototype.extractRefreshToken = function (response) {
301
+ if (response.headers && response.headers['set-cookie']
302
+ && response.headers['set-cookie'].length > 0) {
303
+ return "".concat(response.headers['set-cookie'][0].split(';')[0], ";");
205
304
  }
305
+ return '';
206
306
  };
207
- BaseAPI.prototype.cleanTokenData = function () {
208
- this.storeTokenData(null);
307
+ BaseAPI.prototype.getConfiguration = function () {
308
+ return this.configuration;
209
309
  };
210
310
  BaseAPI.prototype.attachInterceptor = function (axios) {
211
311
  var _this = this;
@@ -217,9 +317,8 @@ var BaseAPI = /** @class */ (function () {
217
317
  switch (_a.label) {
218
318
  case 0:
219
319
  originalConfig = err.config;
220
- if (!(err.response && !(err.response instanceof XMLHttpRequest))) return [3 /*break*/, 5];
221
- if (!((err.response.status === 401 || err.response.status === 403)
222
- && !originalConfig._retry)) return [3 /*break*/, 4];
320
+ if (!err.response) return [3 /*break*/, 5];
321
+ if (!(err.response.status === 401 && !originalConfig._retry)) return [3 /*break*/, 4];
223
322
  originalConfig._retry = true;
224
323
  _a.label = 1;
225
324
  case 1:
@@ -228,21 +327,23 @@ var BaseAPI = /** @class */ (function () {
228
327
  case 2:
229
328
  tokenString = _a.sent();
230
329
  accessToken = "Bearer ".concat(tokenString);
231
- delete originalConfig.headers['Authorization'];
232
- originalConfig.headers['Authorization'] = accessToken;
330
+ originalConfig.headers['Authorization'] = "Bearer ".concat(accessToken);
233
331
  this.configuration.accessToken = accessToken;
234
- this.tokenData.accessToken = tokenString;
235
- this.storeTokenData(this.tokenData);
236
- return [2 /*return*/, axios(originalConfig)];
332
+ return [2 /*return*/, axios.request(originalConfig)];
237
333
  case 3:
238
334
  _error_1 = _a.sent();
239
335
  if (_error_1.response && _error_1.response.data) {
240
336
  return [2 /*return*/, Promise.reject(_error_1.response.data)];
241
337
  }
242
338
  return [2 /*return*/, Promise.reject(_error_1)];
243
- case 4: return [3 /*break*/, 9];
339
+ case 4:
340
+ if (err.response.status === 403 && err.response.data) {
341
+ return [2 /*return*/, Promise.reject(err.response.data)];
342
+ }
343
+ return [3 /*break*/, 9];
244
344
  case 5:
245
345
  if (!(err.message === NETWORK_ERROR_MESSAGE
346
+ && err.isAxiosError
246
347
  && originalConfig.headers.hasOwnProperty('Authorization')
247
348
  && _retry_count < 4)) return [3 /*break*/, 9];
248
349
  _retry_count++;
@@ -256,8 +357,6 @@ var BaseAPI = /** @class */ (function () {
256
357
  _retry = true;
257
358
  originalConfig.headers['Authorization'] = accessToken;
258
359
  this.configuration.accessToken = accessToken;
259
- this.tokenData.accessToken = tokenString;
260
- this.storeTokenData(this.tokenData);
261
360
  return [2 /*return*/, axios.request(__assign({}, originalConfig))];
262
361
  case 8:
263
362
  _error_2 = _a.sent();
package/dist/common.d.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  import { Configuration } from "./configuration";
13
13
  import { RequestArgs } from "./base";
14
14
  import { AxiosInstance, AxiosResponse } from 'axios';
15
+ import { URL } from 'url';
15
16
  /**
16
17
  *
17
18
  * @export
package/dist/common.js CHANGED
@@ -62,6 +62,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
62
62
  Object.defineProperty(exports, "__esModule", { value: true });
63
63
  exports.defaultStorage = exports.LocalStorage = exports.createRequestFunction = exports.toPathString = exports.serializeDataIfNeeded = exports.setSearchParams = exports.setOAuthToObject = exports.setBearerAuthToObject = exports.setBasicAuthToObject = exports.setApiKeyToObject = exports.assertParamExists = exports.DUMMY_BASE_URL = void 0;
64
64
  var base_1 = require("./base");
65
+ var url_1 = require("url");
65
66
  /**
66
67
  *
67
68
  * @export
@@ -187,7 +188,7 @@ var setSearchParams = function (url) {
187
188
  for (var _i = 1; _i < arguments.length; _i++) {
188
189
  objects[_i - 1] = arguments[_i];
189
190
  }
190
- var searchParams = new URLSearchParams(url.search);
191
+ var searchParams = new url_1.URLSearchParams(url.search);
191
192
  for (var _a = 0, objects_1 = objects; _a < objects_1.length; _a++) {
192
193
  var object = objects_1[_a];
193
194
  for (var key in object) {
@@ -68,6 +68,13 @@ export declare class Configuration {
68
68
  * @type {new () => FormData}
69
69
  */
70
70
  formDataCtor?: new () => any;
71
+ /**
72
+ * parameter for automatically refreshing access token for oauth2 security
73
+ *
74
+ * @type {string}
75
+ * @memberof Configuration
76
+ */
77
+ refreshToken?: string;
71
78
  constructor(param?: ConfigurationParameters);
72
79
  /**
73
80
  * Check if the given MIME is a JSON MIME.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emilgroup/public-api-sdk-node",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "OpenAPI client for @emilgroup/public-api-sdk-node",
5
5
  "author": "OpenAPI-Generator Contributors",
6
6
  "keywords": [
@@ -18,10 +18,12 @@
18
18
  "prepare": "npm run build"
19
19
  },
20
20
  "dependencies": {
21
- "axios": "^0.27.2"
21
+ "axios": "^0.27.2",
22
+ "form-data": "^4.0.0",
23
+ "url": "^0.11.0"
22
24
  },
23
25
  "devDependencies": {
24
-
26
+ "@types/node": "^12.11.5",
25
27
  "typescript": "^4.0"
26
28
  }
27
29
  }