@zcatalyst/auth-admin 0.0.3

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.
@@ -0,0 +1,229 @@
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 _ZCAuth_instances, _ZCAuth_appCollection, _ZCAuth_loadOptionsFromObj, _ZCAuth_loadOptionsFromEnvVar;
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.CatalystAppError = exports.TicketCredential = exports.RefreshTokenCredential = exports.Credential = exports.AccessTokenCredential = exports.CatalystApp = exports.ZCAuth = void 0;
10
+ exports.addDefaultAppHeaders = addDefaultAppHeaders;
11
+ const utils_1 = require("@zcatalyst/utils");
12
+ Object.defineProperty(exports, "CatalystAppError", { enumerable: true, get: function () { return utils_1.CatalystAppError; } });
13
+ const credential_1 = require("./credential");
14
+ const { INIT_TYPE, PROJECT_HEADER, DEFAULT_ENV, DEFAULT_APP_NAME, CREDENTIAL_USER, CATALYST_ORIGIN, AUTH_HEADER, COOKIE_HEADER, CREDENTIAL_HEADER, PROJECT_KEY_NAME, ENVIRONMENT_KEY_NAME, ENVIRONMENT, X_ZOHO_CATALYST_ORG_ID } = utils_1.CONSTANTS;
15
+ let appOptions = {};
16
+ class ZCAuth {
17
+ constructor() {
18
+ _ZCAuth_instances.add(this);
19
+ this.config = {};
20
+ _ZCAuth_appCollection.set(this, {});
21
+ }
22
+ init(options, { type, appName, scope } = {
23
+ type: 'auto'
24
+ }) {
25
+ switch (type) {
26
+ case INIT_TYPE.advancedio:
27
+ if (!options || typeof options.headers !== 'object') {
28
+ throw new utils_1.CatalystAppError('INVALID_APP_OPTIONS', 'the options passed to initialize method is not valid', options);
29
+ }
30
+ appOptions = __classPrivateFieldGet(this, _ZCAuth_instances, "m", _ZCAuth_loadOptionsFromObj).call(this, options['headers']);
31
+ appOptions.credential = new credential_1.CatalystCredential(options['headers'], scope);
32
+ break;
33
+ case INIT_TYPE.basicio:
34
+ if (!options || typeof options.catalystHeaders !== 'object') {
35
+ throw new utils_1.CatalystAppError('INVALID_APP_OPTIONS', 'the options passed to initialize method is not valid', options);
36
+ }
37
+ appOptions = __classPrivateFieldGet(this, _ZCAuth_instances, "m", _ZCAuth_loadOptionsFromObj).call(this, options['catalystHeaders']);
38
+ appOptions.credential = new credential_1.CatalystCredential(options['catalystHeaders'], scope);
39
+ break;
40
+ case INIT_TYPE.custom:
41
+ if (!options || !options['credential']) {
42
+ throw new utils_1.CatalystAppError('INVALID_APP_OPTIONS', 'the options passed to initialize method is not valid', options);
43
+ }
44
+ if (appName && (0, utils_1.isNonEmptyString)(appName) && appName in __classPrivateFieldGet(this, _ZCAuth_appCollection, "f")) {
45
+ throw new utils_1.CatalystAppError('APP_ALREADY_EXISTS', `The app with name ${appName} already exists. Please use a different name.`, appName);
46
+ }
47
+ appOptions = options;
48
+ appOptions.credential = new credential_1.ApplicationCustomCredential(options['credential']);
49
+ break;
50
+ default:
51
+ if (options && typeof options.headers === 'object') {
52
+ return this.init(options, { type: INIT_TYPE.advancedio, appName, scope });
53
+ }
54
+ if (options && typeof options.catalystHeaders === 'object') {
55
+ return this.init(options, { type: INIT_TYPE.basicio, appName, scope });
56
+ }
57
+ if (options && options['credential']) {
58
+ return this.init(options, { type: INIT_TYPE.custom, appName, scope });
59
+ }
60
+ throw new utils_1.CatalystAppError('APP_ERROR', 'Unable to find the type of initialisation. kindly specify one', options);
61
+ }
62
+ const catalystApp = new CatalystApp(appOptions);
63
+ if (appName !== undefined && (0, utils_1.isNonEmptyString)(appName)) {
64
+ __classPrivateFieldGet(this, _ZCAuth_appCollection, "f")[appName] = catalystApp;
65
+ }
66
+ else {
67
+ __classPrivateFieldGet(this, _ZCAuth_appCollection, "f")[DEFAULT_APP_NAME] = catalystApp;
68
+ }
69
+ return catalystApp;
70
+ }
71
+ getDefaultCredentials(appName) {
72
+ if (typeof appName === 'undefined') {
73
+ appName = DEFAULT_APP_NAME;
74
+ }
75
+ if (!(0, utils_1.isNonEmptyObject)(appOptions)) {
76
+ appOptions = __classPrivateFieldGet(this, _ZCAuth_instances, "m", _ZCAuth_loadOptionsFromEnvVar).call(this);
77
+ if (!(0, utils_1.isNonEmptyObject)(appOptions)) {
78
+ throw new utils_1.CatalystAppError('AUTH_ERROR', 'Unable to get the app credentials, please initialize the app before perform operations.', appOptions);
79
+ }
80
+ }
81
+ if (typeof appOptions.credential === 'undefined') {
82
+ appOptions.credential = new credential_1.ApplicationDefaultCredential();
83
+ }
84
+ const app = new CatalystApp(appOptions);
85
+ app.credential.switchUser(CREDENTIAL_USER.admin);
86
+ __classPrivateFieldGet(this, _ZCAuth_appCollection, "f")[appName] = app;
87
+ return app;
88
+ }
89
+ app(appName) {
90
+ if (typeof appName === 'undefined') {
91
+ appName = DEFAULT_APP_NAME;
92
+ }
93
+ if (!(0, utils_1.isNonEmptyString)(appName)) {
94
+ throw new utils_1.CatalystAppError('INVALID_APP_NAME', 'Invalid app name provided. App name must be a non-empty string.', appName);
95
+ }
96
+ else if (!(appName in __classPrivateFieldGet(this, _ZCAuth_appCollection, "f"))) {
97
+ let errorMessage = appName === DEFAULT_APP_NAME
98
+ ? 'The default project does not exist. '
99
+ : `project named "${appName}" does not exist. `;
100
+ errorMessage += 'Make sure you call init() before getting the desired app';
101
+ throw new utils_1.CatalystAppError('no_app', errorMessage, appName);
102
+ }
103
+ return __classPrivateFieldGet(this, _ZCAuth_appCollection, "f")[appName];
104
+ }
105
+ }
106
+ exports.ZCAuth = ZCAuth;
107
+ _ZCAuth_appCollection = new WeakMap(), _ZCAuth_instances = new WeakSet(), _ZCAuth_loadOptionsFromObj = function _ZCAuth_loadOptionsFromObj(obj) {
108
+ const projectId = obj[PROJECT_HEADER.id];
109
+ const projectKey = obj[PROJECT_HEADER.key];
110
+ const environment = obj[PROJECT_HEADER.environment] || DEFAULT_ENV;
111
+ const projectDomain = obj[PROJECT_HEADER.domain] || CATALYST_ORIGIN;
112
+ const projectSecretKey = obj[PROJECT_HEADER.projectSecretKey];
113
+ const origin = obj['host'] && obj['host'].trim()
114
+ ? `http://${obj['host']}`
115
+ : `https://${projectDomain}`;
116
+ if (!projectId) {
117
+ throw new utils_1.CatalystAppError('PROJECT_ERROR', 'Invalid project details. Failed to parse an object.', obj);
118
+ }
119
+ return {
120
+ projectId,
121
+ projectKey,
122
+ environment,
123
+ projectDomain,
124
+ projectSecretKey,
125
+ origin
126
+ };
127
+ }, _ZCAuth_loadOptionsFromEnvVar = function _ZCAuth_loadOptionsFromEnvVar() {
128
+ const projectId = process.env[PROJECT_HEADER.id];
129
+ const projectKey = process.env[PROJECT_HEADER.key];
130
+ const environment = process.env[PROJECT_HEADER.environment] || DEFAULT_ENV;
131
+ const projectDomain = process.env[PROJECT_HEADER.domain] || CATALYST_ORIGIN;
132
+ const projectSecretKey = process.env[PROJECT_HEADER.projectSecretKey];
133
+ if (!(0, utils_1.isNonEmptyString)(!projectId)) {
134
+ return {};
135
+ }
136
+ try {
137
+ return {
138
+ projectId,
139
+ projectKey,
140
+ environment,
141
+ projectDomain,
142
+ projectSecretKey
143
+ };
144
+ }
145
+ catch (err) {
146
+ throw new utils_1.CatalystAppError('INVALID_APP_OPTIONS', 'Failed to parse app options : ' + err, err);
147
+ }
148
+ };
149
+ class CatalystApp {
150
+ constructor(options) {
151
+ try {
152
+ (0, utils_1.isNonNullObject)(options, 'options', true);
153
+ (0, utils_1.ObjectHasProperties)(options, ['credential'], 'options', true);
154
+ (0, utils_1.isNonNullObject)(options.credential, 'options.credential', true);
155
+ (0, utils_1.isValidType)(options.credential.getToken, 'function', 'options.credential', true);
156
+ (0, utils_1.isNonEmptyStringOrNumber)(options.project_id || options.projectId, 'projectId', true);
157
+ }
158
+ catch (e) {
159
+ if (e instanceof utils_1.CatalystError) {
160
+ throw new utils_1.CatalystAppError(e.code, e.message, e);
161
+ }
162
+ throw e;
163
+ }
164
+ this.credential = options.credential;
165
+ this.config = {
166
+ projectId: (options.project_id || options.projectId),
167
+ projectKey: (options.project_key || options.projectKey),
168
+ projectDomain: (options.project_domain || options.projectDomain),
169
+ environment: options.environment || DEFAULT_ENV,
170
+ projectSecretKey: (options.project_secret_key || options.projectSecretKey),
171
+ origin: options.origin || CATALYST_ORIGIN
172
+ };
173
+ }
174
+ setOauthHeader(headers, token) {
175
+ headers[AUTH_HEADER] = 'Zoho-oauthtoken ' + token;
176
+ }
177
+ setTicketHeader(headers, token) {
178
+ headers[AUTH_HEADER] = 'Zoho-ticket ' + token;
179
+ }
180
+ async authenticateRequest(req) {
181
+ const headers = Object.assign({}, req.headers);
182
+ if (this.credential instanceof credential_1.AccessTokenCredential ||
183
+ this.credential instanceof credential_1.RefreshTokenCredential) {
184
+ const token = await this.credential.getToken();
185
+ this.setOauthHeader(headers, token.access_token);
186
+ req.headers = headers;
187
+ return;
188
+ }
189
+ if (this.credential instanceof credential_1.TicketCredential) {
190
+ const token = await this.credential.getToken();
191
+ this.setTicketHeader(headers, token.ticket);
192
+ req.headers = headers;
193
+ return;
194
+ }
195
+ if (this.credential instanceof credential_1.CatalystCredential ||
196
+ this.credential instanceof credential_1.ApplicationDefaultCredential) {
197
+ const token = (await this.credential.getToken());
198
+ if ((0, utils_1.isNonEmptyString)(token.access_token)) {
199
+ this.setOauthHeader(headers, token.access_token);
200
+ }
201
+ else if ((0, utils_1.isNonEmptyString)(token.ticket)) {
202
+ this.setTicketHeader(headers, token.ticket);
203
+ }
204
+ else if ((0, utils_1.isNonEmptyString)(token.cookie)) {
205
+ headers[COOKIE_HEADER] = token.cookie;
206
+ headers[CREDENTIAL_HEADER.zcsrf] = token.zcrf_header;
207
+ }
208
+ req.headers = headers;
209
+ }
210
+ }
211
+ }
212
+ exports.CatalystApp = CatalystApp;
213
+ function addDefaultAppHeaders(headers, values) {
214
+ headers[PROJECT_KEY_NAME] = values?.projectKey;
215
+ headers[ENVIRONMENT_KEY_NAME] = values?.environment;
216
+ headers[ENVIRONMENT] = values?.environment;
217
+ if ((0, utils_1.isNonEmptyString)(process.env.X_ZOHO_CATALYST_ORG_ID)) {
218
+ headers[X_ZOHO_CATALYST_ORG_ID] = process.env.X_ZOHO_CATALYST_ORG_ID;
219
+ }
220
+ if ((0, utils_1.isNonEmptyString)(values?.projectSecretKey)) {
221
+ headers[PROJECT_HEADER.projectSecretKey] = values?.projectSecretKey;
222
+ }
223
+ return headers;
224
+ }
225
+ var credential_2 = require("./credential");
226
+ Object.defineProperty(exports, "AccessTokenCredential", { enumerable: true, get: function () { return credential_2.AccessTokenCredential; } });
227
+ Object.defineProperty(exports, "Credential", { enumerable: true, get: function () { return credential_2.Credential; } });
228
+ Object.defineProperty(exports, "RefreshTokenCredential", { enumerable: true, get: function () { return credential_2.RefreshTokenCredential; } });
229
+ Object.defineProperty(exports, "TicketCredential", { enumerable: true, get: function () { return credential_2.TicketCredential; } });
@@ -0,0 +1,348 @@
1
+ import { CONSTANTS } from '@zcatalyst/utils';
2
+ import { readFileSync } from 'fs';
3
+ import http from 'http';
4
+ import https from 'https';
5
+ import { resolve } from 'path';
6
+ import { stringify } from 'querystring';
7
+ import { CatalystAuthError } from './errors';
8
+ const { CREDENTIAL_SUFFIX, REQ_METHOD, CREDENTIAL_HEADER, CREDENTIAL_TYPE, CREDENTIAL_USER, CSRF_TOKEN_NAME, ACCOUNTS_ORIGIN } = CONSTANTS;
9
+ export const globalValue = {};
10
+ const CREDENTIAL_PATH = process.env.HOME
11
+ ? resolve(resolve(process.env.HOME, '.config'), CREDENTIAL_SUFFIX)
12
+ : resolve('.', CREDENTIAL_SUFFIX);
13
+ function getAttr(from, key, alt) {
14
+ const tmp = from[key] || (alt ? from[alt] : undefined);
15
+ if (typeof tmp === 'undefined') {
16
+ throw new CatalystAuthError('INVALID_CREDENTIAL', `Unable to get ${alt} from credential Object provided`, from);
17
+ }
18
+ return tmp;
19
+ }
20
+ function fromPath(filePath) {
21
+ let jsonString;
22
+ try {
23
+ jsonString = readFileSync(filePath, 'utf8');
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ try {
29
+ return JSON.parse(jsonString);
30
+ }
31
+ catch (err) {
32
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'Failed to parse token file: ' + err, err);
33
+ }
34
+ }
35
+ function fromEnv() {
36
+ const clientId = process.env['CLIENT_ID'];
37
+ const clientSecret = process.env['CLIENT_SECRET'];
38
+ const refreshToken = process.env['REFRESH_TOKEN'];
39
+ if (clientId && clientSecret && refreshToken) {
40
+ return {
41
+ client_id: clientId,
42
+ client_secret: clientSecret,
43
+ refresh_token: refreshToken
44
+ };
45
+ }
46
+ else {
47
+ throw new CatalystAuthError('INVALID_CREDENTIAL', `Failed to get the credential string from env variables`);
48
+ }
49
+ }
50
+ function _appendQueryData(url, data) {
51
+ if (data && Object.keys(data).length > 0) {
52
+ url += url.includes('?') ? '&' : '?';
53
+ url += stringify(data);
54
+ }
55
+ return url;
56
+ }
57
+ function isHttps(url) {
58
+ if (url === undefined) {
59
+ return false;
60
+ }
61
+ const parsedUrl = url instanceof URL ? url : new URL(url);
62
+ return parsedUrl.protocol !== 'http:';
63
+ }
64
+ async function _request(config) {
65
+ config.url = _appendQueryData(String(config.origin) + String(config.path), config.qs);
66
+ const parsedUrl = new URL(config.url);
67
+ if (parsedUrl.hostname === null) {
68
+ throw new CatalystAuthError('unparsable_config', 'Hostname cannot be null', config.path);
69
+ }
70
+ const isHttpsProtocol = isHttps(parsedUrl);
71
+ parsedUrl.searchParams?.sort();
72
+ const options = {
73
+ hostname: parsedUrl.hostname,
74
+ port: parsedUrl.port,
75
+ path: parsedUrl.pathname + parsedUrl.search,
76
+ method: config.method,
77
+ headers: {
78
+ 'Content-Type': 'application/json',
79
+ ...(config.headers || {})
80
+ }
81
+ };
82
+ const transport = isHttpsProtocol ? https : http;
83
+ return new Promise((resolve, reject) => {
84
+ const req = transport.request(options, (res) => {
85
+ const chunks = [];
86
+ res.on('data', (chunk) => {
87
+ chunks.push(chunk);
88
+ });
89
+ res.on('end', () => {
90
+ const body = Buffer.concat(chunks).toString();
91
+ const response = {
92
+ headers: res.headers,
93
+ request: req,
94
+ stream: res,
95
+ statusCode: res.statusCode,
96
+ config,
97
+ body
98
+ };
99
+ resolve(response);
100
+ });
101
+ });
102
+ req.on('error', (err) => {
103
+ reject(err);
104
+ });
105
+ req.write(JSON.stringify({ your: 'data' }));
106
+ req.end();
107
+ });
108
+ }
109
+ async function requestAccessToken(request) {
110
+ const options = {
111
+ method: request.method,
112
+ origin: request.origin,
113
+ qs: request.qs,
114
+ path: request.path
115
+ };
116
+ const resp = await _request(options);
117
+ const json = JSON.parse(resp.body);
118
+ if (json.error) {
119
+ const errorMessage = 'Error fetching access token: ' + json.error;
120
+ return Promise.reject(errorMessage);
121
+ }
122
+ else if (!json.access_token || !json.expires_in) {
123
+ return Promise.reject(`Unexpected response while fetching access token: ${JSON.stringify(json)}`);
124
+ }
125
+ else {
126
+ return json;
127
+ }
128
+ }
129
+ export class Credential {
130
+ getCurrentUser() {
131
+ return CREDENTIAL_USER.admin;
132
+ }
133
+ switchUser(_givenUser) {
134
+ return null;
135
+ }
136
+ getCurrentUserType() {
137
+ return CREDENTIAL_USER.admin;
138
+ }
139
+ }
140
+ export class RefreshTokenCredential extends Credential {
141
+ constructor(refreshObj) {
142
+ super();
143
+ this.clientId = getAttr(refreshObj, 'clientId', 'client_id');
144
+ this.clientSecret = getAttr(refreshObj, 'clientSecret', 'client_secret');
145
+ this.refreshToken = getAttr(refreshObj, 'refreshToken', 'refresh_token');
146
+ this.cachedToken = null;
147
+ }
148
+ async getToken() {
149
+ if (this.cachedToken === null || this.cachedToken['expires_in'] <= Date.now()) {
150
+ const token = await requestAccessToken({
151
+ method: REQ_METHOD.post,
152
+ origin: ACCOUNTS_ORIGIN,
153
+ path: '/oauth/v2/token',
154
+ qs: {
155
+ client_id: this.clientId,
156
+ client_secret: this.clientSecret,
157
+ refresh_token: this.refreshToken,
158
+ grant_type: 'refresh_token'
159
+ }
160
+ });
161
+ this.cachedToken = token;
162
+ this.cachedToken.expires_in = Date.now() + token.expires_in * 1000;
163
+ }
164
+ return this.cachedToken;
165
+ }
166
+ }
167
+ export class AccessTokenCredential extends Credential {
168
+ constructor(accessObj) {
169
+ super();
170
+ this.accessToken = getAttr(accessObj, 'accessToken', 'access_token');
171
+ }
172
+ async getToken() {
173
+ return Promise.resolve({
174
+ access_token: this.accessToken
175
+ });
176
+ }
177
+ }
178
+ export class TicketCredential extends Credential {
179
+ constructor(ticketObj) {
180
+ super();
181
+ this.ticket = getAttr(ticketObj, 'ticket', 'ticket');
182
+ }
183
+ async getToken() {
184
+ return Promise.resolve({ ticket: this.ticket });
185
+ }
186
+ }
187
+ export class CookieCredential extends Credential {
188
+ constructor(cookieObj) {
189
+ super();
190
+ this.cookie = getAttr(cookieObj, 'cookie', 'cookie');
191
+ this.cookieObj = {};
192
+ }
193
+ getAsObject() {
194
+ if (Object.keys(this.cookieObj).length > 0) {
195
+ return this.cookieObj;
196
+ }
197
+ this.cookie.split(';').forEach((cookie) => {
198
+ const parts = cookie.split('=');
199
+ this.cookieObj[parts.shift()?.trim()] = decodeURI(parts.join('='));
200
+ });
201
+ return this.cookieObj;
202
+ }
203
+ getZCSRFHeader() {
204
+ const cookieObj = this.getAsObject();
205
+ return 'zd_csrparam=' + cookieObj[CSRF_TOKEN_NAME];
206
+ }
207
+ async getToken() {
208
+ return Promise.resolve({ cookie: this.cookie, zcrf_header: this.getZCSRFHeader() });
209
+ }
210
+ }
211
+ export class CatalystCredential extends Credential {
212
+ constructor(credObj, scope) {
213
+ super();
214
+ this.adminCredType = getAttr(credObj, 'adminType', CREDENTIAL_HEADER.admin_cred_type);
215
+ this.adminToken = getAttr(credObj, 'adminToken', CREDENTIAL_HEADER.admin_token);
216
+ this.userCredType = credObj[CREDENTIAL_HEADER.user_cred_type];
217
+ this.userToken = credObj[CREDENTIAL_HEADER.user_token];
218
+ this.cookieStr = credObj[CREDENTIAL_HEADER.cookie];
219
+ this.userType =
220
+ credObj[CREDENTIAL_HEADER.user] === CREDENTIAL_USER.admin
221
+ ? CREDENTIAL_USER.admin
222
+ : CREDENTIAL_USER.user;
223
+ this.scope = scope || this.userType;
224
+ if (this.scope === CREDENTIAL_USER.user) {
225
+ if (this.userType === CREDENTIAL_USER.admin) {
226
+ throw new CatalystAuthError('AUTH_ERROR', 'User not authenticated. Please login to proceed with user scope', credObj);
227
+ }
228
+ if (this.userToken === undefined && this.cookieStr === undefined) {
229
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'missing user credentials', credObj);
230
+ }
231
+ }
232
+ switch (this.adminCredType) {
233
+ case CREDENTIAL_TYPE.ticket:
234
+ this.adminCred = new TicketCredential({ ticket: this.adminToken });
235
+ break;
236
+ case CREDENTIAL_TYPE.token:
237
+ this.adminCred = new AccessTokenCredential({ access_token: this.adminToken });
238
+ break;
239
+ default:
240
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'admin credential type is unknown', credObj);
241
+ }
242
+ switch (this.userCredType) {
243
+ case CREDENTIAL_TYPE.ticket:
244
+ this.userCred = new TicketCredential({ ticket: this.userToken });
245
+ break;
246
+ case CREDENTIAL_TYPE.token:
247
+ this.userCred = new AccessTokenCredential({
248
+ access_token: this.userToken
249
+ });
250
+ break;
251
+ default:
252
+ if (this.cookieStr !== undefined) {
253
+ this.userCred = new CookieCredential({
254
+ cookie: this.cookieStr
255
+ });
256
+ }
257
+ }
258
+ }
259
+ async getToken() {
260
+ switch (this.scope) {
261
+ case CREDENTIAL_USER.admin:
262
+ return this.adminCred.getToken();
263
+ case CREDENTIAL_USER.user:
264
+ if (this.userCred === undefined) {
265
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'User Credential is not initialised', this.scope);
266
+ }
267
+ return this.userCred.getToken();
268
+ default:
269
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'user provided is not recognized', this.scope);
270
+ }
271
+ }
272
+ getScope() {
273
+ return this.scope;
274
+ }
275
+ getCurrentUser() {
276
+ return this.scope;
277
+ }
278
+ getCurrentUserType() {
279
+ if (this.scope === CREDENTIAL_USER.user) {
280
+ return this.userType;
281
+ }
282
+ return this.scope;
283
+ }
284
+ switchUser(givenUser) {
285
+ if (givenUser === undefined) {
286
+ switch (this.scope) {
287
+ case CREDENTIAL_USER.admin:
288
+ givenUser = CREDENTIAL_USER.user;
289
+ break;
290
+ case CREDENTIAL_USER.user:
291
+ givenUser = CREDENTIAL_USER.admin;
292
+ break;
293
+ }
294
+ }
295
+ this.scope = givenUser;
296
+ return this.scope;
297
+ }
298
+ }
299
+ export class ApplicationDefaultCredential extends Credential {
300
+ constructor() {
301
+ super();
302
+ let token = fromPath(CREDENTIAL_PATH);
303
+ if (token === undefined || token === null) {
304
+ token = fromEnv();
305
+ }
306
+ if (token === undefined || token === null) {
307
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'Unable to get token object from path or env', token);
308
+ }
309
+ if ('refresh_token' in token) {
310
+ this.credential = new RefreshTokenCredential(token);
311
+ }
312
+ else if ('access_token' in token) {
313
+ this.credential = new AccessTokenCredential(token);
314
+ }
315
+ else if ('ticket' in token) {
316
+ this.credential = new TicketCredential(token);
317
+ }
318
+ else {
319
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'The given token object does not contain proper credentials', token);
320
+ }
321
+ }
322
+ async getToken() {
323
+ return this.credential.getToken();
324
+ }
325
+ }
326
+ export class ApplicationCustomCredential extends Credential {
327
+ constructor(credObj) {
328
+ super();
329
+ if (credObj === undefined || credObj === null) {
330
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'Unable to get token object from path or env', credObj);
331
+ }
332
+ if ('refresh_token' in credObj) {
333
+ this.credential = new RefreshTokenCredential(credObj);
334
+ }
335
+ else if ('access_token' in credObj) {
336
+ this.credential = new AccessTokenCredential(credObj);
337
+ }
338
+ else if ('ticket' in credObj) {
339
+ this.credential = new TicketCredential(credObj);
340
+ }
341
+ else {
342
+ throw new CatalystAuthError('INVALID_CREDENTIAL', 'The given token object does not contain proper credentials', credObj);
343
+ }
344
+ }
345
+ async getToken() {
346
+ return this.credential.getToken();
347
+ }
348
+ }
@@ -0,0 +1,6 @@
1
+ import { PrefixedCatalystError } from '@zcatalyst/utils';
2
+ export class CatalystAuthError extends PrefixedCatalystError {
3
+ constructor(code, message, value) {
4
+ super('app', code, message, value);
5
+ }
6
+ }