@qoretechnologies/ts-toolkit 0.4.0

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.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -0
  3. package/dist/QorusAuthenticator.d.ts +181 -0
  4. package/dist/QorusAuthenticator.d.ts.map +1 -0
  5. package/dist/QorusAuthenticator.js +386 -0
  6. package/dist/QorusAuthenticator.js.map +1 -0
  7. package/dist/QorusConfigItems.d.ts +13 -0
  8. package/dist/QorusConfigItems.d.ts.map +1 -0
  9. package/dist/QorusConfigItems.js +41 -0
  10. package/dist/QorusConfigItems.js.map +1 -0
  11. package/dist/QorusDataProvider.d.ts +206 -0
  12. package/dist/QorusDataProvider.d.ts.map +1 -0
  13. package/dist/QorusDataProvider.js +262 -0
  14. package/dist/QorusDataProvider.js.map +1 -0
  15. package/dist/QorusOptions.d.ts +108 -0
  16. package/dist/QorusOptions.d.ts.map +1 -0
  17. package/dist/QorusOptions.js +181 -0
  18. package/dist/QorusOptions.js.map +1 -0
  19. package/dist/QorusRequest.d.ts +91 -0
  20. package/dist/QorusRequest.d.ts.map +1 -0
  21. package/dist/QorusRequest.js +103 -0
  22. package/dist/QorusRequest.js.map +1 -0
  23. package/dist/QorusValidator.d.ts +33 -0
  24. package/dist/QorusValidator.d.ts.map +1 -0
  25. package/dist/QorusValidator.js +385 -0
  26. package/dist/QorusValidator.js.map +1 -0
  27. package/dist/index.d.ts +21 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +43 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/managers/LocalStorage.d.ts +24 -0
  32. package/dist/managers/LocalStorage.d.ts.map +1 -0
  33. package/dist/managers/LocalStorage.js +46 -0
  34. package/dist/managers/LocalStorage.js.map +1 -0
  35. package/dist/managers/error/Error.d.ts +7 -0
  36. package/dist/managers/error/Error.d.ts.map +1 -0
  37. package/dist/managers/error/Error.js +16 -0
  38. package/dist/managers/error/Error.js.map +1 -0
  39. package/dist/managers/error/ErrorInternal.d.ts +6 -0
  40. package/dist/managers/error/ErrorInternal.d.ts.map +1 -0
  41. package/dist/managers/error/ErrorInternal.js +14 -0
  42. package/dist/managers/error/ErrorInternal.js.map +1 -0
  43. package/dist/managers/error/ErrorQorusRequest.d.ts +11 -0
  44. package/dist/managers/error/ErrorQorusRequest.d.ts.map +1 -0
  45. package/dist/managers/error/ErrorQorusRequest.js +22 -0
  46. package/dist/managers/error/ErrorQorusRequest.js.map +1 -0
  47. package/dist/managers/error/errorCodes.d.ts +8 -0
  48. package/dist/managers/error/errorCodes.d.ts.map +1 -0
  49. package/dist/managers/error/errorCodes.js +30 -0
  50. package/dist/managers/error/errorCodes.js.map +1 -0
  51. package/dist/managers/logger.d.ts +11 -0
  52. package/dist/managers/logger.d.ts.map +1 -0
  53. package/dist/managers/logger.js +22 -0
  54. package/dist/managers/logger.js.map +1 -0
  55. package/dist/utils/apiPaths.d.ts +63 -0
  56. package/dist/utils/apiPaths.d.ts.map +1 -0
  57. package/dist/utils/apiPaths.js +37 -0
  58. package/dist/utils/apiPaths.js.map +1 -0
  59. package/dist/utils/index.d.ts +3 -0
  60. package/dist/utils/index.d.ts.map +1 -0
  61. package/dist/utils/index.js +27 -0
  62. package/dist/utils/index.js.map +1 -0
  63. package/dist/utils/validation.d.ts +107 -0
  64. package/dist/utils/validation.d.ts.map +1 -0
  65. package/dist/utils/validation.js +108 -0
  66. package/dist/utils/validation.js.map +1 -0
  67. package/package.json +113 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Qore Technologies, s.r.o.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ <div align="center">
2
+ <br><br><br>
3
+ <img src="./public/logo.png" alt="Unstated Logo" width="350">
4
+ <br><br><br>
5
+ </div>
6
+
7
+ # @qoretechnologies/qorus-toolkit
8
+
9
+ > Currently in beta, more features and integrations yet to be added
10
+
11
+ A modern TypeScript utility library for enhancing QoreTechnologies no-code infrastructure solutions.
12
+
13
+ ![](./coverage/badge-functions.svg) ![](./coverage/badge-lines.svg) ![](./coverage/badge-statements.svg)
14
+
15
+ ## Installation
16
+
17
+ Before installing, [download and install Node.js](https://nodejs.org/en/download/).
18
+ Latest stable Node.js is required.
19
+
20
+ Installation is done using the
21
+ [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
22
+
23
+ ```console
24
+ $ yarn add @qoretechnologies/qorus-toolkit
25
+ ```
26
+
27
+ Alternatively you can also use npm
28
+
29
+ ```console
30
+ $ npm install @qoretechnologies/qorus-toolkit
31
+ ```
32
+
33
+ ## Current Features
34
+
35
+ - QorusAuthenticator
36
+
37
+ An authenticator for Qorus Integration Engine(R), allows users to create multiple connections as endpoints and manage authentication to them.
38
+
39
+ - QorusDataProvider
40
+
41
+ Provides an API to interact with Qorus Integration Engine(R) data providers, and allows the user to fetch, add and edit Data Providers.
42
+
43
+ - QorusRequest
44
+
45
+ An HTTPS request handler to manage API requests to Qorus Integration Engine(R)
46
+
47
+ - QorusOptions
48
+ A Qorus Integration Engine(R) API options manager
49
+
50
+ ## Docs & Community
51
+
52
+ - [Documentation](https://toolkit.qoretechnologies.com)
53
+ - [GitHub Organization](https://github.com/qoretechnologies) for Official open-source projects
54
+ - [Discord](https://discord.gg/T7vgS6nh) for support, discussion, news and latest release updates
55
+
56
+ ## Philosophy
57
+
58
+ The Qorus-Toolkit philosophy is to provide a fast and modular API wrapper to connect with Qore Technologies server API which enables it to be utilized in any node project with ease.
59
+
60
+ Qorus-Toolkit will be used with Qorus-Toolkit-React to provide a complete solution with modular components to our enterprise clients.
61
+
62
+ ## Contributing
63
+
64
+ The Qorus Toolkit project welcomes all constructive contributions. Contributions can be of many forms including bug fixes, enhancements, fixes to documentation, additional tests and more!
65
+
66
+ See the [Contributing Guide](CONTRIBUTING.MD) for more technical details on contributing.
67
+
68
+ ### Security Issues
69
+
70
+ If you discover a security vulnerability in Qorus Toolkit, please see [Security Policies and Procedures](SECURITY.md).
71
+
72
+ ## License
73
+
74
+ [MIT](LICENSE)
@@ -0,0 +1,181 @@
1
+ import { IApiPaths, IAuthenticatorApiPaths, IWithEndpointVersion, TVersion } from './utils/apiPaths';
2
+ export interface IValidateEndpointData extends IAddEndpoint, ILoginParams {
3
+ }
4
+ /**
5
+ * Endpoint id for a Qorus server endpoint
6
+ */
7
+ export type TQorusEndpointId = string;
8
+ /**
9
+ * Authentication token for a Qorus server endpoint
10
+ */
11
+ export type TQorusAuthToken = string;
12
+ /**
13
+ * Url for a Qorus server endpoint
14
+ */
15
+ export type TQorusEndpointURL = string;
16
+ export interface IWithQorusEndpointId {
17
+ /**
18
+ * Id for a endpoint provided by the user, unique for every endpoint
19
+ */
20
+ endpointId: TQorusEndpointId;
21
+ }
22
+ export interface IWithQorusAuthToken {
23
+ /**
24
+ * Authentication token for the user provided endpoint
25
+ */
26
+ authToken?: TQorusAuthToken;
27
+ }
28
+ export interface IWithQorusURL {
29
+ /**
30
+ * URL to Qorus server for the provided endpoint
31
+ */
32
+ url: TQorusEndpointURL;
33
+ }
34
+ export interface ILoginParams {
35
+ /**
36
+ * Username for the authentication to Qorus server
37
+ */
38
+ user?: string;
39
+ /**
40
+ * Password for the authentication to Qorus server
41
+ */
42
+ pass?: string;
43
+ }
44
+ export interface IAddEndpoint extends IWithQorusURL, IWithEndpointVersion, IWithQorusEndpointId {
45
+ }
46
+ export interface IEndpoint extends IWithQorusURL, IWithEndpointVersion, IWithQorusAuthToken, IWithQorusEndpointId {
47
+ }
48
+ /**
49
+ * Authentication token for a Qorus Endpoint
50
+ */
51
+ export type TToken = string;
52
+ /**
53
+ * QorusAuthenticator class provides methods to authenticate a user for a Qorus server endpoint
54
+ * - Add Multiple endpoint for different versions of Qorus apis
55
+ * - Supports no-auth for the Qorus server api
56
+ * - Uses locally stored token or user and password for authentication
57
+ * @returns QorusAuthenticator class object
58
+ * @Category QorusAuthenticator
59
+ */
60
+ export declare class QorusAuthenticator {
61
+ #private;
62
+ /**
63
+ * Array of user defined endpoints
64
+ */
65
+ endpoints: IEndpoint[];
66
+ /** Object of Api paths for the selected endpoint */
67
+ allApiPaths: IApiPaths;
68
+ /** Api paths for the QorusAuthenticator */
69
+ apiPathsAuthenticator: IAuthenticatorApiPaths;
70
+ /** Selected endpoint from the endpoints array */
71
+ selectedEndpoint: IEndpoint | undefined;
72
+ /** No auth identifier to identify if the no-auth is enabled for the user */
73
+ noauth: boolean;
74
+ reset(): void;
75
+ /**
76
+ * A getter to get the endpoint if it exist in the Endpoints array
77
+ * @param id ID of the endpoint ex: "rippy"
78
+ * @returns Endpoint object if the endpoint with the provided id exist in the endpoints array, undefined otherwise.
79
+ */
80
+ getEndpointById(endpointId: string): IEndpoint | undefined;
81
+ /**
82
+ * Logs out the current user from the selected endpoint
83
+ * @returns True if the operation is successful, False otherwise
84
+ */
85
+ logout(): Promise<boolean>;
86
+ /**
87
+ * Select an endpoint from the available Endpoints array
88
+ * @param id Id of the endpoint
89
+ * @returns Endpoint if the operation is successful, undefined otherwise.
90
+ */
91
+ selectEndpoint(id: string): Promise<IEndpoint | undefined>;
92
+ /**
93
+ * Checks if the Qorus endpoint supports no-auth
94
+ * @param endpoint Endpoint config to add the data
95
+ * @returns True if the no-auth is enabled for the user, False otherwise
96
+ */
97
+ checkNoAuth(endpoint?: IEndpoint): Promise<boolean>;
98
+ /**
99
+ * A getter to get selected Endpoint
100
+ * @returns Selected Endpoint if the endpoint exists, undefined otherwise
101
+ */
102
+ getSelectedEndpoint(): IEndpoint | undefined;
103
+ /**
104
+ * Checks the validity of the selected endpoint
105
+ * @param data Endpoint data to be checked
106
+ * @param withCredentials boolean to check if the endpoint has credentials
107
+ * @returns True if the Endpoint data is valid, False otherwise
108
+ */
109
+ validateEndpointData(data: IValidateEndpointData, withCredentials?: boolean): boolean;
110
+ /**
111
+ * Validates the local stored authentication token for the Endpoint
112
+ * @param endpointId Id of the endpoint
113
+ * @returns Authentication token, if the authentication is successful, null otherwise
114
+ */
115
+ validateLocalUserToken(endpointId: string): Promise<string | null>;
116
+ /**
117
+ * Authenticates the user to interact with the Qorus api.
118
+ * If the username and password is not provided it tries to authenticate the user using the locally stored token from the selected Endpoint
119
+ * @param loginParams LoginParams, user and pass is required to authenticate the user.
120
+ * @returns Authentication token if the authentication is successful, undefined otherwise.
121
+ */
122
+ login(loginParams?: ILoginParams): Promise<string | undefined>;
123
+ /**
124
+ * Add a new Qorus Endpoint to interact with the qorus api
125
+ * @param endpointConfig Endpoint configuration required to add a new endpoint
126
+ * @returns Newly added endpoint
127
+ */
128
+ addEndpoint(endpointConfig: IAddEndpoint): IEndpoint;
129
+ /**
130
+ * Allows the user to renew the selected endpoint authentication token
131
+ * @param loginParams LoginParams optional username and password can be provided
132
+ * @returns Token if the authentication is successful, undefined otherwise
133
+ */
134
+ renewSelectedEndpointToken(loginParams: ILoginParams): Promise<string | undefined>;
135
+ /**
136
+ * A getter to return the auth token of the selected Endpoint
137
+ * @returns token if the the selected endpoint exists and the user is authenticated, otherwise returns undefined
138
+ */
139
+ getAuthToken(): string | undefined;
140
+ /**
141
+ * A getter to get the api Version of a Endpoint
142
+ * @param endpointId Optional id parameter to get the version of a particular endpoint
143
+ * @returns Version of the selected endpoint or version of the the endpoint found by id,
144
+ * if the endpoint doesn't exists it returns undefined
145
+ */
146
+ getEndpointVersion(endpointId?: string): TVersion | undefined;
147
+ /**
148
+ * Validates if the provided version is an accepted api version
149
+ * @param version Version of the endpoint
150
+ * @returns True if the version is valid, False otherwise
151
+ */
152
+ private validateVersion;
153
+ /**
154
+ * A setter to set the Version of a Endpoint
155
+ * @param version Version of the qorus api
156
+ * @param endpointId Optional parameter to change the url of a particular endpoint from the endpoints array
157
+ * @returns Version of the endpoint if the operation is successful, undefined otherwise
158
+ *
159
+ */
160
+ setEndpointVersion(version: TVersion, endpointId?: string): Promise<TVersion | undefined>;
161
+ /**
162
+ * A setter to set the url of the selected Endpoint
163
+ * @param url Base url for the endpoint
164
+ * @param id Optional id parameter to change the url of a particular endpoint
165
+ * @returns Url of the endpoint if the operation is successful, undefined otherwise
166
+ */
167
+ setEndpointUrl(url: string, endpointId?: string): Promise<string | undefined>;
168
+ /**
169
+ * A getter to return the api paths for the selected Endpoint
170
+ * @returns ApiPaths for the selected endpoint if exists, otherwise returns default api paths
171
+ */
172
+ getApiPaths(): IApiPaths;
173
+ /**
174
+ * A getter to get all the available Endpoints
175
+ * @returns Endpoints array with all the available endpoints
176
+ */
177
+ getAllEndpoints(): IEndpoint[];
178
+ }
179
+ declare const _default: QorusAuthenticator;
180
+ export default _default;
181
+ //# sourceMappingURL=QorusAuthenticator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"QorusAuthenticator.d.ts","sourceRoot":"","sources":["../src/QorusAuthenticator.ts"],"names":[],"mappings":"AAMA,OAAO,EAGL,SAAS,EACT,sBAAsB,EACtB,oBAAoB,EAC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AAe,IAAI,SAAS,EAAE;CAG/B;;AAED,wBAAwC"}
@@ -0,0 +1,386 @@
1
+ "use strict";
2
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
+ };
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ var _QorusAuthenticator_instances, _QorusAuthenticator_fixEndpointData;
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.QorusAuthenticator = void 0;
13
+ const ErrorInternal_1 = __importDefault(require("./managers/error/ErrorInternal"));
14
+ const LocalStorage_1 = require("./managers/LocalStorage");
15
+ const logger_1 = __importDefault(require("./managers/logger"));
16
+ const QorusRequest_1 = __importDefault(require("./QorusRequest"));
17
+ const QorusValidator_1 = __importDefault(require("./QorusValidator"));
18
+ const utils_1 = require("./utils");
19
+ const apiPaths_1 = require("./utils/apiPaths");
20
+ /**
21
+ * QorusAuthenticator class provides methods to authenticate a user for a Qorus server endpoint
22
+ * - Add Multiple endpoint for different versions of Qorus apis
23
+ * - Supports no-auth for the Qorus server api
24
+ * - Uses locally stored token or user and password for authentication
25
+ * @returns QorusAuthenticator class object
26
+ * @Category QorusAuthenticator
27
+ */
28
+ class QorusAuthenticator {
29
+ constructor() {
30
+ _QorusAuthenticator_instances.add(this);
31
+ /**
32
+ * Array of user defined endpoints
33
+ */
34
+ this.endpoints = [];
35
+ /** Object of Api paths for the selected endpoint */
36
+ this.allApiPaths = apiPaths_1.apiPathsInitial;
37
+ /** Api paths for the QorusAuthenticator */
38
+ this.apiPathsAuthenticator = apiPaths_1.apiPathsInitial.authenticator;
39
+ /** No auth identifier to identify if the no-auth is enabled for the user */
40
+ this.noauth = false;
41
+ }
42
+ reset() {
43
+ this.endpoints = [];
44
+ this.allApiPaths = apiPaths_1.apiPathsInitial;
45
+ this.apiPathsAuthenticator = apiPaths_1.apiPathsInitial.authenticator;
46
+ this.selectedEndpoint = undefined;
47
+ this.noauth = false;
48
+ }
49
+ /**
50
+ * A getter to get the endpoint if it exist in the Endpoints array
51
+ * @param id ID of the endpoint ex: "rippy"
52
+ * @returns Endpoint object if the endpoint with the provided id exist in the endpoints array, undefined otherwise.
53
+ */
54
+ getEndpointById(endpointId) {
55
+ return this.endpoints.find((endpoint) => endpoint.endpointId === endpointId);
56
+ }
57
+ /**
58
+ * Logs out the current user from the selected endpoint
59
+ * @returns True if the operation is successful, False otherwise
60
+ */
61
+ async logout() {
62
+ if (!this.selectedEndpoint || !(0, utils_1.isValidString)(this.selectedEndpoint.authToken)) {
63
+ return true;
64
+ }
65
+ try {
66
+ await QorusRequest_1.default.post({ path: `${this.apiPathsAuthenticator.logout}` });
67
+ return true;
68
+ }
69
+ catch (error) {
70
+ throw new ErrorInternal_1.default(`Unable to logout user from the endpoint ${this.selectedEndpoint}`);
71
+ }
72
+ finally {
73
+ this.selectedEndpoint.authToken = undefined;
74
+ this.allApiPaths = apiPaths_1.apiPathsInitial;
75
+ this.apiPathsAuthenticator = apiPaths_1.apiPathsInitial.authenticator;
76
+ this.noauth = false;
77
+ }
78
+ }
79
+ /**
80
+ * Select an endpoint from the available Endpoints array
81
+ * @param id Id of the endpoint
82
+ * @returns Endpoint if the operation is successful, undefined otherwise.
83
+ */
84
+ async selectEndpoint(id) {
85
+ var _a;
86
+ if (!(0, utils_1.isValidString)(id)) {
87
+ throw new ErrorInternal_1.default('Id is not valid, please provide a valid id or initialize a new endpoint.');
88
+ }
89
+ const endpoint = this.getEndpointById(id);
90
+ if (!endpoint || !(0, utils_1.isValidString)(endpoint.url)) {
91
+ throw new ErrorInternal_1.default('Selected endpoint is not valid, please create a new endpoint.');
92
+ }
93
+ if ((_a = this.selectedEndpoint) === null || _a === void 0 ? void 0 : _a.authToken) {
94
+ await this.logout();
95
+ }
96
+ this.selectedEndpoint = endpoint;
97
+ this.allApiPaths = (0, apiPaths_1.createApiPaths)({ version: endpoint.version });
98
+ this.apiPathsAuthenticator = this.allApiPaths.authenticator;
99
+ return endpoint;
100
+ }
101
+ /**
102
+ * Checks if the Qorus endpoint supports no-auth
103
+ * @param endpoint Endpoint config to add the data
104
+ * @returns True if the no-auth is enabled for the user, False otherwise
105
+ */
106
+ async checkNoAuth(endpoint) {
107
+ var _a, _b;
108
+ const actualEndpoint = endpoint !== null && endpoint !== void 0 ? endpoint : this.selectedEndpoint;
109
+ /* Throwing an error if the actualEndpoint is not defined. */
110
+ if (!actualEndpoint) {
111
+ throw new ErrorInternal_1.default('No endpoint selected, please select an endpoint.');
112
+ }
113
+ /* Trying to connect to the endpoint and check if the endpoint is using noauth. */
114
+ try {
115
+ const resp = await QorusRequest_1.default.get({ path: `${this.apiPathsAuthenticator.validateNoAuth}` }, endpoint);
116
+ if (!(resp === null || resp === void 0 ? void 0 : resp.data)) {
117
+ throw new ErrorInternal_1.default(`Cannot verify no-auth please check your url "${(_a = endpoint === null || endpoint === void 0 ? void 0 : endpoint.url) !== null && _a !== void 0 ? _a : (_b = this.selectedEndpoint) === null || _b === void 0 ? void 0 : _b.url}" and try again`);
118
+ }
119
+ if (!resp.data.noauth) {
120
+ this.noauth = false;
121
+ console.log('No auth disabled, authentication is required with username and password');
122
+ return false;
123
+ }
124
+ this.noauth = resp.data.noauth;
125
+ console.log('No auth enabled, authentication not required');
126
+ return true;
127
+ }
128
+ catch (error) {
129
+ throw new ErrorInternal_1.default(`Unable to connect to ${actualEndpoint.url}, please check the url / connection and try again. ${error ? JSON.stringify(error) : ''}`);
130
+ }
131
+ }
132
+ /**
133
+ * A getter to get selected Endpoint
134
+ * @returns Selected Endpoint if the endpoint exists, undefined otherwise
135
+ */
136
+ getSelectedEndpoint() {
137
+ return this.selectedEndpoint;
138
+ }
139
+ /**
140
+ * Checks the validity of the selected endpoint
141
+ * @param data Endpoint data to be checked
142
+ * @param withCredentials boolean to check if the endpoint has credentials
143
+ * @returns True if the Endpoint data is valid, False otherwise
144
+ */
145
+ validateEndpointData(data, withCredentials) {
146
+ let valid = true;
147
+ const fixedData = __classPrivateFieldGet(this, _QorusAuthenticator_instances, "m", _QorusAuthenticator_fixEndpointData).call(this, data);
148
+ if (!(QorusValidator_1.default.validate('string', fixedData.endpointId) &&
149
+ QorusValidator_1.default.validate('string', fixedData.url) &&
150
+ QorusValidator_1.default.validate('version', fixedData.version))) {
151
+ valid = false;
152
+ }
153
+ if (withCredentials &&
154
+ !(QorusValidator_1.default.validate('string', fixedData.user) && QorusValidator_1.default.validate('string', fixedData.pass))) {
155
+ valid = false;
156
+ }
157
+ return valid;
158
+ }
159
+ /**
160
+ * Validates the local stored authentication token for the Endpoint
161
+ * @param endpointId Id of the endpoint
162
+ * @returns Authentication token, if the authentication is successful, null otherwise
163
+ */
164
+ async validateLocalUserToken(endpointId) {
165
+ const authToken = (0, LocalStorage_1.getKeyValLocal)(`auth-token-${endpointId}`);
166
+ if (!(0, utils_1.isValidString)(authToken)) {
167
+ return null;
168
+ }
169
+ try {
170
+ const resp = await QorusRequest_1.default.get({
171
+ path: `${this.apiPathsAuthenticator.validateToken}`,
172
+ data: { token: authToken },
173
+ });
174
+ if (typeof resp === 'string') {
175
+ return authToken;
176
+ }
177
+ else {
178
+ return null;
179
+ }
180
+ }
181
+ catch (error) {
182
+ return null;
183
+ }
184
+ }
185
+ /**
186
+ * Authenticates the user to interact with the Qorus api.
187
+ * If the username and password is not provided it tries to authenticate the user using the locally stored token from the selected Endpoint
188
+ * @param loginParams LoginParams, user and pass is required to authenticate the user.
189
+ * @returns Authentication token if the authentication is successful, undefined otherwise.
190
+ */
191
+ async login(loginParams) {
192
+ var _a, _b, _c;
193
+ await this.checkNoAuth();
194
+ if (this.noauth) {
195
+ logger_1.default.log('No-auth enabled authentication not required.');
196
+ return undefined;
197
+ }
198
+ if (!this.selectedEndpoint || !(0, utils_1.isValidString)(this.selectedEndpoint.url)) {
199
+ throw new ErrorInternal_1.default('Endpoint must be initialized before authentication.');
200
+ }
201
+ if (!(0, utils_1.isValidStringArray)([loginParams === null || loginParams === void 0 ? void 0 : loginParams.user, loginParams === null || loginParams === void 0 ? void 0 : loginParams.pass])) {
202
+ throw new ErrorInternal_1.default('Username and password is required for authentication');
203
+ }
204
+ const user = (_a = loginParams === null || loginParams === void 0 ? void 0 : loginParams.user) !== null && _a !== void 0 ? _a : undefined;
205
+ const pass = (_b = loginParams === null || loginParams === void 0 ? void 0 : loginParams.pass) !== null && _b !== void 0 ? _b : undefined;
206
+ const { endpointId } = this.selectedEndpoint;
207
+ const currentUserToken = await this.validateLocalUserToken(endpointId);
208
+ if (currentUserToken && currentUserToken !== 'invalid' && this.selectedEndpoint) {
209
+ this.selectedEndpoint.authToken = currentUserToken;
210
+ return currentUserToken;
211
+ }
212
+ const resp = await QorusRequest_1.default.post({
213
+ path: `${this.apiPathsAuthenticator.login}`,
214
+ data: { user, pass },
215
+ });
216
+ const responseData = resp;
217
+ if (typeof (responseData === null || responseData === void 0 ? void 0 : responseData.data) === 'undefined') {
218
+ throw new ErrorInternal_1.default(`${responseData !== null && responseData !== void 0 ? responseData : ''}`);
219
+ }
220
+ if ((_c = responseData === null || responseData === void 0 ? void 0 : responseData.data) === null || _c === void 0 ? void 0 : _c.token) {
221
+ const { token } = responseData === null || responseData === void 0 ? void 0 : responseData.data;
222
+ if (!token) {
223
+ throw new Error('There was an error authenticating user, token is invalid, please try again.');
224
+ }
225
+ this.selectedEndpoint.authToken = token;
226
+ (0, LocalStorage_1.setKeyValLocal)({ key: `auth-token-${endpointId}`, value: token });
227
+ return token;
228
+ }
229
+ return undefined;
230
+ }
231
+ /**
232
+ * Add a new Qorus Endpoint to interact with the qorus api
233
+ * @param endpointConfig Endpoint configuration required to add a new endpoint
234
+ * @returns Newly added endpoint
235
+ */
236
+ addEndpoint(endpointConfig) {
237
+ const { endpointId, url } = endpointConfig;
238
+ const newEndpoint = __classPrivateFieldGet(this, _QorusAuthenticator_instances, "m", _QorusAuthenticator_fixEndpointData).call(this, endpointConfig);
239
+ /* Checking if the id and url are valid strings. */
240
+ if (!(0, utils_1.isValidStringArray)([endpointId, url])) {
241
+ throw new ErrorInternal_1.default('Id and url is required to initialize an endpoint');
242
+ }
243
+ /* Checking if the endpoint already exists. */
244
+ if (this.getEndpointById(endpointId)) {
245
+ throw new ErrorInternal_1.default(`Endpoint with the id "${endpointId}" already exists, please try again with a different id`);
246
+ }
247
+ /* Adding a new endpoint to the endpoints array. */
248
+ this.endpoints.push(newEndpoint);
249
+ this.selectedEndpoint = newEndpoint;
250
+ return this.selectedEndpoint;
251
+ }
252
+ /**
253
+ * Allows the user to renew the selected endpoint authentication token
254
+ * @param loginParams LoginParams optional username and password can be provided
255
+ * @returns Token if the authentication is successful, undefined otherwise
256
+ */
257
+ async renewSelectedEndpointToken(loginParams) {
258
+ const { user, pass } = loginParams;
259
+ if (!this.selectedEndpoint || !(0, utils_1.isValidString)(this.selectedEndpoint.url)) {
260
+ console.error(new ErrorInternal_1.default('Endpoint is not selected, please initialize an endpoint to renew token'));
261
+ return undefined;
262
+ }
263
+ if (!(0, utils_1.isValidStringArray)([user, pass])) {
264
+ throw new ErrorInternal_1.default('Username and password is required to revalidate endpoint token.');
265
+ }
266
+ const token = await this.login({ user, pass });
267
+ if ((0, utils_1.isValidString)(token)) {
268
+ this.selectedEndpoint.authToken = token;
269
+ return token;
270
+ }
271
+ console.error(new ErrorInternal_1.default('Username and password are not valid, please try again'));
272
+ return undefined;
273
+ }
274
+ /**
275
+ * A getter to return the auth token of the selected Endpoint
276
+ * @returns token if the the selected endpoint exists and the user is authenticated, otherwise returns undefined
277
+ */
278
+ getAuthToken() {
279
+ var _a;
280
+ return (_a = this.selectedEndpoint) === null || _a === void 0 ? void 0 : _a.authToken;
281
+ }
282
+ /**
283
+ * A getter to get the api Version of a Endpoint
284
+ * @param endpointId Optional id parameter to get the version of a particular endpoint
285
+ * @returns Version of the selected endpoint or version of the the endpoint found by id,
286
+ * if the endpoint doesn't exists it returns undefined
287
+ */
288
+ getEndpointVersion(endpointId) {
289
+ var _a;
290
+ if ((0, utils_1.isValidString)(endpointId)) {
291
+ return (_a = this.getEndpointById(endpointId)) === null || _a === void 0 ? void 0 : _a.version;
292
+ }
293
+ else {
294
+ if (this.selectedEndpoint) {
295
+ return this.selectedEndpoint.version;
296
+ }
297
+ }
298
+ return undefined;
299
+ }
300
+ /**
301
+ * Validates if the provided version is an accepted api version
302
+ * @param version Version of the endpoint
303
+ * @returns True if the version is valid, False otherwise
304
+ */
305
+ validateVersion(version) {
306
+ const versions = [1, 2, 3, 4, 5, 6, 'latest'];
307
+ return versions.includes(version);
308
+ }
309
+ /**
310
+ * A setter to set the Version of a Endpoint
311
+ * @param version Version of the qorus api
312
+ * @param endpointId Optional parameter to change the url of a particular endpoint from the endpoints array
313
+ * @returns Version of the endpoint if the operation is successful, undefined otherwise
314
+ *
315
+ */
316
+ async setEndpointVersion(version, endpointId) {
317
+ var _a;
318
+ if (!endpointId)
319
+ endpointId = (_a = this.selectedEndpoint) === null || _a === void 0 ? void 0 : _a.endpointId;
320
+ if ((0, utils_1.isValidString)(endpointId) && this.validateVersion(version)) {
321
+ const endpoint = this.getEndpointById(endpointId);
322
+ await this.logout();
323
+ if (endpoint && (0, utils_1.isValidString)(endpoint.url)) {
324
+ this.endpoints[this.endpoints.indexOf(endpoint)].version = version;
325
+ if (this.selectedEndpoint && this.selectedEndpoint.endpointId === endpoint.endpointId) {
326
+ this.selectedEndpoint.version = version;
327
+ this.allApiPaths = (0, apiPaths_1.createApiPaths)({ version });
328
+ this.apiPathsAuthenticator = this.allApiPaths.authenticator;
329
+ }
330
+ logger_1.default.log('Changed endpoint version successfully.');
331
+ return version;
332
+ }
333
+ throw new ErrorInternal_1.default('Endpoint does not exist, please initialize an endpoint and try again.');
334
+ }
335
+ throw new ErrorInternal_1.default('Id and a valid version is required to change the version of a endpoint.');
336
+ }
337
+ /**
338
+ * A setter to set the url of the selected Endpoint
339
+ * @param url Base url for the endpoint
340
+ * @param id Optional id parameter to change the url of a particular endpoint
341
+ * @returns Url of the endpoint if the operation is successful, undefined otherwise
342
+ */
343
+ async setEndpointUrl(url, endpointId) {
344
+ var _a;
345
+ if (!(0, utils_1.isValidString)(endpointId))
346
+ endpointId = (_a = this.selectedEndpoint) === null || _a === void 0 ? void 0 : _a.endpointId;
347
+ if ((0, utils_1.isValidStringArray)([endpointId, url])) {
348
+ const endpoint = this.getEndpointById(endpointId);
349
+ await this.logout();
350
+ if (endpoint && (0, utils_1.isValidString)(endpoint.url)) {
351
+ this.endpoints[this.endpoints.indexOf(endpoint)].url = url;
352
+ if (this.selectedEndpoint && this.selectedEndpoint.endpointId === endpoint.endpointId) {
353
+ this.selectedEndpoint.url = url;
354
+ }
355
+ logger_1.default.log('Changed endpoint url successfully.');
356
+ return url;
357
+ }
358
+ throw new ErrorInternal_1.default('Endpoint does not exist, please initialize an endpoint and try again.');
359
+ }
360
+ throw new ErrorInternal_1.default('Id and url is required to change the version of a endpoint.');
361
+ }
362
+ /**
363
+ * A getter to return the api paths for the selected Endpoint
364
+ * @returns ApiPaths for the selected endpoint if exists, otherwise returns default api paths
365
+ */
366
+ getApiPaths() {
367
+ return this.allApiPaths;
368
+ }
369
+ /**
370
+ * A getter to get all the available Endpoints
371
+ * @returns Endpoints array with all the available endpoints
372
+ */
373
+ getAllEndpoints() {
374
+ return this.endpoints;
375
+ }
376
+ }
377
+ exports.QorusAuthenticator = QorusAuthenticator;
378
+ _QorusAuthenticator_instances = new WeakSet(), _QorusAuthenticator_fixEndpointData = function _QorusAuthenticator_fixEndpointData(data) {
379
+ const newData = Object.assign({}, data);
380
+ if (!newData.version) {
381
+ newData.version = 'latest';
382
+ }
383
+ return newData;
384
+ };
385
+ exports.default = new QorusAuthenticator();
386
+ //# sourceMappingURL=QorusAuthenticator.js.map