Skip to content

Commit

Permalink
Merge pull request #22 from qoretechnologies/20-bug-port-is-stripped-…
Browse files Browse the repository at this point in the history
…from-the-url

20 bug port is stripped from the url
  • Loading branch information
rishabhmalik759 authored Nov 23, 2022
2 parents eeb71c0 + 94ef78d commit bd8cbd4
Show file tree
Hide file tree
Showing 10 changed files with 171 additions and 134 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
"titleBar.inactiveForeground": "#e7e7e799"
},
"peacock.remoteColor": "#22147d",
"cSpell.words": ["jsyaml"]
"cSpell.words": ["jsyaml", "noauth"]
}
28 changes: 14 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@qoretechnologies/qorus-toolkit",
"version": "0.2.5",
"version": "0.2.6",
"description": "Utility library to interact with Qorus Integration Engine",
"keywords": [
"qoretechnologies",
Expand Down
2 changes: 1 addition & 1 deletion pullRequestRelease.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"version": "0.2.51669093648"}
{"version": "0.2.61669207848"}
66 changes: 38 additions & 28 deletions src/QorusAuthenticator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,27 +131,30 @@ export class QorusAuthenticator {
};

// Check if the server has noauth enabled
checkNoAuth = async (): Promise<boolean> => {
checkNoAuth = async (endpoint?: Endpoint): Promise<boolean> => {
let resp;

try {
resp = await QorusRequest.get({ path: `${this.apiPathsAuthenticator.validateNoAuth}` });
if (!resp || !resp.data || !resp.data.noauth) {
resp = await QorusRequest.get({ path: `${this.apiPathsAuthenticator.validateNoAuth}` }, endpoint);
if (!resp || !resp.data || typeof resp.data.noauth === 'undefined') {
throw new ErrorInternal(`Cannot verify no-auth please check your url "${endpoint?.url}" and try again`);
}

if (typeof resp.data.noauth === 'boolean' && resp.data.noauth === false) {
this.noauth = false;
console.log('No auth disabled, authentication is required with username and password');
return false;
}
const _noauth = resp.data.noauth;

if (typeof _noauth === 'boolean' && _noauth === true) {
this.noauth = _noauth;
if (typeof resp.data.noauth === 'boolean' && resp.data.noauth === true) {
this.noauth = resp.data.noauth;
console.log('No auth enabled, authentication not required');
return true;
}
this.noauth = false;
return false;
} catch (error: any) {
console.error(new ErrorAxios(error as AxiosError));
return false;
throw new ErrorInternal(`Cannot verify no-auth please check your url "${endpoint?.url}" and try again`);
}
};

Expand Down Expand Up @@ -222,25 +225,26 @@ export class QorusAuthenticator {
throw new ErrorInternal('Username and password is required to authenticate the user for the first time');
}

const resp = await QorusRequest.post({
path: `${this.apiPathsAuthenticator.login}`,
data: { user, pass },
});
const responseData = resp as AxiosResponse;
const error = resp as unknown as AxiosError;

if (error?.response?.status) {
throw new ErrorAxios(error);
}
try {
const resp = await QorusRequest.post({
path: `${this.apiPathsAuthenticator.login}`,
data: { user, pass },
});
const responseData = resp as AxiosResponse;
if (typeof responseData.data === 'undefined') {
throw new ErrorInternal(`${responseData}`);
}
const { token } = responseData?.data ?? null;
if (!token) {
throw new ErrorInternal('There was an error authenticating user, token is invalid, please try again.');
}

const { token }: { token: string } = responseData?.data ?? null;
if (!token) {
throw new ErrorInternal('There was an error authenticating user, please try again.');
this.selectedEndpoint.authToken = token;
setKeyValLocal({ key: `auth-token-${id}`, value: token });
return token;
} catch (error: any) {
throw new ErrorInternal(`Error authenticating user ${error.message}`);
}

this.selectedEndpoint.authToken = token;
setKeyValLocal({ key: `auth-token-${id}`, value: token });
return token;
};

/**
Expand All @@ -251,6 +255,13 @@ export class QorusAuthenticator {
*/
initEndpoint = async (endpointConfig: InitEndpoint): Promise<Endpoint | undefined> => {
const { id, url, version, user, pass } = endpointConfig;
let checkEndpoint;
try {
checkEndpoint = await this.selectEndpoint(id);
} catch (error) {}
if (checkEndpoint?.url) {
throw new ErrorInternal(`Endpoint with the id "${id}" already exists, please try again with a different id`);
}

if (!isValidStringArray([id, url])) {
throw new ErrorInternal('Id and url is required to initialize an endpoint');
Expand All @@ -260,6 +271,8 @@ export class QorusAuthenticator {
...endpointConfig,
version: version ?? 'latest',
};
await this.checkNoAuth(newEndpoint);

const storedEndpoint = this.getEndpointById(id);

if (!storedEndpoint) {
Expand All @@ -271,10 +284,7 @@ export class QorusAuthenticator {
} else {
this.selectedEndpoint = newEndpoint;
}

await this.checkNoAuth();
if (isValidStringArray([user, pass])) await this.login({ user, pass });
else console.error(new ErrorInternal('Please provide valid username and password to authenticate the user.'));

return this.selectedEndpoint;
};
Expand Down
31 changes: 20 additions & 11 deletions src/QorusRequest.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import axios, { AxiosError, AxiosRequestHeaders, AxiosResponse } from 'axios';
import ErrorInternal from './managers/error/ErrorInternal';
import QorusAuthenticator from './QorusAuthenticator';
import QorusAuthenticator, { Endpoint } from './QorusAuthenticator';
import { Agent } from 'https';

export const httpsAxios = axios.create();
export const httpsAgent = new Agent({
rejectUnauthorized: false,
});

export const httpsAxios = axios.create({ httpsAgent });

export interface QorusRequestParams {
/**
Expand Down Expand Up @@ -37,9 +42,10 @@ export class QorusRequest {
makeRequest = async (
type: 'GET' | 'PUT' | 'POST' | 'DELETE',
props: QorusRequestParams,
endpoint?: Endpoint,
): Promise<AxiosResponse | AxiosError | undefined> => {
const { path, data, headers = this.defaultHeaders, params } = props;
const selectedEndpoint = QorusAuthenticator.getSelectedEndpoint();
const selectedEndpoint = endpoint ?? QorusAuthenticator.getSelectedEndpoint();
if (headers != this.defaultHeaders) {
Object.assign(headers, { ...this.defaultHeaders, headers });
}
Expand Down Expand Up @@ -71,8 +77,8 @@ export class QorusRequest {
*
* Returns the promise with the result of the get request
*/
get = async (props: QorusRequestParams): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('GET', props);
get = async (props: QorusRequestParams, endpoint?: Endpoint): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('GET', props, endpoint);
return result;
};

Expand All @@ -83,8 +89,8 @@ export class QorusRequest {
*
* Returns the promise with the result of the post request
*/
post = async (props: QorusRequestParams): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('POST', props);
post = async (props: QorusRequestParams, endpoint?: Endpoint): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('POST', props, endpoint);
return result;
};

Expand All @@ -95,8 +101,8 @@ export class QorusRequest {
*
* Returns the promise with the result of the put request
*/
put = async (props: QorusRequestParams): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('PUT', props);
put = async (props: QorusRequestParams, endpoint?: Endpoint): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('PUT', props, endpoint);
return result;
};

Expand All @@ -107,8 +113,11 @@ export class QorusRequest {
*
* Returns the promise with the result of the delete request
*/
deleteReq = async (props: QorusRequestParams): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('DELETE', props);
deleteReq = async (
props: QorusRequestParams,
endpoint?: Endpoint,
): Promise<AxiosResponse | AxiosError | undefined> => {
const result = await this.makeRequest('DELETE', props, endpoint);
return result;
};
}
Expand Down
15 changes: 12 additions & 3 deletions src/managers/error/ErrorAxios.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { AxiosError } from 'axios';
import BaseError from './Error';
import { errorCodes } from './errorCodes';

class ErrorAxios extends BaseError {
constructor(error: AxiosError) {
const response = error.response;
const data = response?.data as AxiosErrorResponseData;
super(data.desc, true, data.err, response?.status);
if (
typeof error.response === 'undefined' ||
typeof error.response.data === 'undefined' ||
typeof (error.response.data as AxiosErrorResponseData).desc === 'undefined'
) {
super(`${error}`, true, errorCodes.INTERNAL.name, undefined);
} else {
const response = error.response;
const data = response?.data as AxiosErrorResponseData;
super(data.desc, true, data.err, response?.status);
}
}
}

Expand Down
Loading

0 comments on commit bd8cbd4

Please sign in to comment.