lhisp-oauth-client 1.0.5
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/__tests__/lhisp-oauth-client.test.d.ts +1 -0
- package/__tests__/lhisp-oauth-client.test.js +216 -0
- package/package.json +24 -0
- package/src/index.d.ts +2 -0
- package/src/index.js +18 -0
- package/src/lhisp-oauth-client.d.ts +36 -0
- package/src/lhisp-oauth-client.js +151 -0
- package/src/lhisp-oauth-client.t.d.ts +39 -0
- package/src/lhisp-oauth-client.t.js +12 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
const axios_1 = __importDefault(require("axios"));
|
|
16
|
+
const lhisp_oauth_client_1 = require("../src/lhisp-oauth-client");
|
|
17
|
+
const lhisp_oauth_client_t_1 = require("../src/lhisp-oauth-client.t");
|
|
18
|
+
// Mock jest and set the type
|
|
19
|
+
jest.mock('axios');
|
|
20
|
+
const mockedAxios = axios_1.default;
|
|
21
|
+
const apiUrl = "https://myapi.com";
|
|
22
|
+
const authUrl = "https://auth.myapi.com/oauth/token";
|
|
23
|
+
const clientId = "testClientdId";
|
|
24
|
+
const clientSecret = "testClientSecret";
|
|
25
|
+
const baseClientParams = { apiUrl, authUrl, clientId, clientSecret };
|
|
26
|
+
const basicAuth = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;
|
|
27
|
+
const contentTypeApplicationJson = "application/json";
|
|
28
|
+
const contentTypeApplicationXFormUrlEncoded = "application/x-www-form-urlencoded";
|
|
29
|
+
const defaultGrantValue = 'client_credentials';
|
|
30
|
+
const defaultGrantType = `{"grant_type":"${defaultGrantValue}"}`;
|
|
31
|
+
describe("Get Access Token", () => {
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
mockedAxios.request.mockReset();
|
|
34
|
+
mockedAxios.request.mockResolvedValueOnce({ data: mockedAccessToken });
|
|
35
|
+
});
|
|
36
|
+
it("Shoud Get with Standard Config", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
37
|
+
const cli = getOauthClient();
|
|
38
|
+
yield accessTokenValidator(cli);
|
|
39
|
+
validateDefaultGetAccessToken();
|
|
40
|
+
}));
|
|
41
|
+
it("Shoud Get with Custom Auth Header", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
42
|
+
const cli = getOauthClient(Object.assign(Object.assign({}, baseClientParams), { authHeaderName: 'CustomAuthorizationHeader' }));
|
|
43
|
+
yield accessTokenValidator(cli);
|
|
44
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
45
|
+
url: authUrl,
|
|
46
|
+
method: "POST",
|
|
47
|
+
headers: {
|
|
48
|
+
CustomAuthorizationHeader: basicAuth,
|
|
49
|
+
'Content-Type': contentTypeApplicationJson,
|
|
50
|
+
},
|
|
51
|
+
data: defaultGrantType,
|
|
52
|
+
}));
|
|
53
|
+
}));
|
|
54
|
+
it("Shoud Get with Custom Grant Type", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
55
|
+
const cli = getOauthClient(Object.assign(Object.assign({}, baseClientParams), { grantType: 'PermissaoCustom' }));
|
|
56
|
+
yield accessTokenValidator(cli);
|
|
57
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
58
|
+
url: authUrl,
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers: {
|
|
61
|
+
Authorization: basicAuth,
|
|
62
|
+
'Content-Type': contentTypeApplicationJson,
|
|
63
|
+
},
|
|
64
|
+
data: '{"grant_type":"PermissaoCustom"}',
|
|
65
|
+
}));
|
|
66
|
+
}));
|
|
67
|
+
it("Shoud Get with Custom Auth Scope", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
68
|
+
const cli = getOauthClient(Object.assign(Object.assign({}, baseClientParams), { authScope: 'EscopoCustom' }));
|
|
69
|
+
yield accessTokenValidator(cli);
|
|
70
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
71
|
+
url: authUrl,
|
|
72
|
+
method: "POST",
|
|
73
|
+
headers: {
|
|
74
|
+
Authorization: basicAuth,
|
|
75
|
+
'Content-Type': contentTypeApplicationJson,
|
|
76
|
+
},
|
|
77
|
+
data: `{"grant_type":"${defaultGrantValue}","scope":"EscopoCustom"}`,
|
|
78
|
+
}));
|
|
79
|
+
}));
|
|
80
|
+
it("Shoud Get with Credentials on Request body", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
81
|
+
const cli = getOauthClient(Object.assign(Object.assign({}, baseClientParams), { sendAuthCredentialsOnRequestBody: true }));
|
|
82
|
+
yield accessTokenValidator(cli);
|
|
83
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
84
|
+
url: authUrl,
|
|
85
|
+
method: "POST",
|
|
86
|
+
headers: {
|
|
87
|
+
Authorization: basicAuth,
|
|
88
|
+
'Content-Type': contentTypeApplicationJson,
|
|
89
|
+
},
|
|
90
|
+
data: `{"grant_type":"${defaultGrantValue}","client_id":"${clientId}","client_secret":"${clientSecret}"}`,
|
|
91
|
+
}));
|
|
92
|
+
}));
|
|
93
|
+
});
|
|
94
|
+
describe("Request", () => {
|
|
95
|
+
beforeEach(() => {
|
|
96
|
+
mockedAxios.request.mockReset();
|
|
97
|
+
mockedAxios.request.mockResolvedValueOnce({ data: mockedAccessToken });
|
|
98
|
+
mockedAxios.request.mockResolvedValueOnce({ data: { "status": "ok" } });
|
|
99
|
+
});
|
|
100
|
+
it("Get without Params", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
101
|
+
const cli = getOauthClient();
|
|
102
|
+
const resp = yield cli.get({ path: '/my-test-url' });
|
|
103
|
+
validateDefaultGetAccessToken();
|
|
104
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
105
|
+
url: `${apiUrl}/my-test-url`,
|
|
106
|
+
method: "GET",
|
|
107
|
+
headers: {
|
|
108
|
+
Authorization: `Bearer SomeAccessToken`,
|
|
109
|
+
'Content-Type': contentTypeApplicationJson,
|
|
110
|
+
},
|
|
111
|
+
data: undefined
|
|
112
|
+
}));
|
|
113
|
+
expect(resp).toStrictEqual({ "status": "ok" });
|
|
114
|
+
}));
|
|
115
|
+
it("Get with Params", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
116
|
+
const cli = getOauthClient();
|
|
117
|
+
const resp = yield cli.get({ path: '/my-test-url', params: { id: 1 } });
|
|
118
|
+
validateDefaultGetAccessToken();
|
|
119
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
120
|
+
url: `${apiUrl}/my-test-url`,
|
|
121
|
+
method: "GET",
|
|
122
|
+
headers: {
|
|
123
|
+
Authorization: `Bearer SomeAccessToken`,
|
|
124
|
+
'Content-Type': contentTypeApplicationJson,
|
|
125
|
+
},
|
|
126
|
+
params: { id: 1 },
|
|
127
|
+
data: undefined
|
|
128
|
+
}));
|
|
129
|
+
expect(resp).toStrictEqual({ "status": "ok" });
|
|
130
|
+
}));
|
|
131
|
+
it("Post", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
132
|
+
const cli = getOauthClient();
|
|
133
|
+
const resp = yield cli.post({ path: '/my-test-url-post', data: { id: 1, user: 'test' } });
|
|
134
|
+
validateDefaultGetAccessToken();
|
|
135
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
136
|
+
url: `${apiUrl}/my-test-url-post`,
|
|
137
|
+
method: "POST",
|
|
138
|
+
headers: {
|
|
139
|
+
Authorization: `Bearer SomeAccessToken`,
|
|
140
|
+
'Content-Type': contentTypeApplicationJson,
|
|
141
|
+
},
|
|
142
|
+
data: { id: 1, user: 'test' }
|
|
143
|
+
}));
|
|
144
|
+
expect(resp).toStrictEqual({ "status": "ok" });
|
|
145
|
+
}));
|
|
146
|
+
it("Post with different contentType", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
147
|
+
const cli = getOauthClient();
|
|
148
|
+
const resp = yield cli.post({
|
|
149
|
+
path: '/my-test-url-post',
|
|
150
|
+
data: { id: 1, user: 'test' },
|
|
151
|
+
contentType: lhisp_oauth_client_t_1.ContentType.APPLICATION_X_WWW_FORM_URLENCODED
|
|
152
|
+
});
|
|
153
|
+
validateDefaultGetAccessToken();
|
|
154
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
155
|
+
url: `${apiUrl}/my-test-url-post`,
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: {
|
|
158
|
+
Authorization: `Bearer SomeAccessToken`,
|
|
159
|
+
'Content-Type': contentTypeApplicationXFormUrlEncoded,
|
|
160
|
+
},
|
|
161
|
+
data: { id: 1, user: 'test' }
|
|
162
|
+
}));
|
|
163
|
+
expect(resp).toStrictEqual({ "status": "ok" });
|
|
164
|
+
}));
|
|
165
|
+
it("Post with Different Token Header Name", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
166
|
+
const cli = getOauthClient(Object.assign(Object.assign({}, baseClientParams), { tokenHeaderName: "x-token" }));
|
|
167
|
+
const resp = yield cli.post({
|
|
168
|
+
path: '/my-test-url-post',
|
|
169
|
+
data: { id: 1, user: 'test' },
|
|
170
|
+
contentType: lhisp_oauth_client_t_1.ContentType.APPLICATION_X_WWW_FORM_URLENCODED
|
|
171
|
+
});
|
|
172
|
+
validateDefaultGetAccessToken();
|
|
173
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
174
|
+
url: `${apiUrl}/my-test-url-post`,
|
|
175
|
+
method: "POST",
|
|
176
|
+
headers: {
|
|
177
|
+
'x-token': `Bearer SomeAccessToken`,
|
|
178
|
+
'Content-Type': contentTypeApplicationXFormUrlEncoded,
|
|
179
|
+
},
|
|
180
|
+
data: { id: 1, user: 'test' }
|
|
181
|
+
}));
|
|
182
|
+
expect(resp).toStrictEqual({ "status": "ok" });
|
|
183
|
+
}));
|
|
184
|
+
});
|
|
185
|
+
function validateDefaultGetAccessToken() {
|
|
186
|
+
expect(mockedAxios.request).toBeCalledWith(expect.objectContaining({
|
|
187
|
+
url: authUrl,
|
|
188
|
+
method: "POST",
|
|
189
|
+
headers: {
|
|
190
|
+
Authorization: basicAuth,
|
|
191
|
+
'Content-Type': contentTypeApplicationJson,
|
|
192
|
+
},
|
|
193
|
+
data: defaultGrantType,
|
|
194
|
+
}));
|
|
195
|
+
}
|
|
196
|
+
function accessTokenValidator(cli) {
|
|
197
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
198
|
+
const now = Date.now();
|
|
199
|
+
const accessToken = yield cli.getAccessToken();
|
|
200
|
+
expect(accessToken).toBeDefined();
|
|
201
|
+
expect(accessToken.token_type).toBe(mockedAccessToken.token_type);
|
|
202
|
+
expect(accessToken.access_token).toBe(mockedAccessToken.access_token);
|
|
203
|
+
expect(accessToken.expires_in).toBe(mockedAccessToken.expires_in);
|
|
204
|
+
expect(accessToken.scope).toBe(mockedAccessToken.scope);
|
|
205
|
+
expect(accessToken.created_at).toBeGreaterThanOrEqual(now);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
function getOauthClient(opt = baseClientParams) {
|
|
209
|
+
return new lhisp_oauth_client_1.LhispOauthClient(opt);
|
|
210
|
+
}
|
|
211
|
+
const mockedAccessToken = {
|
|
212
|
+
token_type: "Bearer",
|
|
213
|
+
access_token: "SomeAccessToken",
|
|
214
|
+
expires_in: 600,
|
|
215
|
+
scope: "cobrancas.boletos-requisicao cobrancas.boletos-info",
|
|
216
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "lhisp-oauth-client",
|
|
3
|
+
"version": "1.0.5",
|
|
4
|
+
"main": "src/index",
|
|
5
|
+
"types": "src/index.d.ts",
|
|
6
|
+
"repository": "git@bitbucket.org:leandro_costa/lhisp-oauth-client.git",
|
|
7
|
+
"author": "Leandro Costa <contato@leandrocosta.pro.br>",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"scripts": {
|
|
10
|
+
"build": "tsc",
|
|
11
|
+
"test": "jest",
|
|
12
|
+
"test:watch": "jest --watchAll"
|
|
13
|
+
},
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@types/jest": "^29.4.0",
|
|
16
|
+
"@types/node": "^18.11.18",
|
|
17
|
+
"jest": "^29.4.1",
|
|
18
|
+
"ts-jest": "^29.0.5",
|
|
19
|
+
"typescript": "^4.9.4"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"axios": "^1.2.5"
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/index.d.ts
ADDED
package/src/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./lhisp-oauth-client"), exports);
|
|
18
|
+
__exportStar(require("./lhisp-oauth-client.t"), exports);
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import https from 'https';
|
|
3
|
+
import { AccessToken, ContentType, ExecutarRequestParams, LhispOauthClientConstructorParams } from "./lhisp-oauth-client.t";
|
|
4
|
+
export declare class LhispOauthClient {
|
|
5
|
+
protected authUrl: string;
|
|
6
|
+
protected apiUrl: string;
|
|
7
|
+
protected clientId: string;
|
|
8
|
+
protected clientSecret: string;
|
|
9
|
+
protected authHeaderName: string;
|
|
10
|
+
protected tokenHeaderName: string;
|
|
11
|
+
protected authContentType: ContentType;
|
|
12
|
+
protected certificado?: string;
|
|
13
|
+
protected senhaCertificado?: string;
|
|
14
|
+
protected authScope?: string;
|
|
15
|
+
protected headers?: Headers;
|
|
16
|
+
protected grantType?: string;
|
|
17
|
+
protected agent: https.Agent;
|
|
18
|
+
protected accessToken?: AccessToken;
|
|
19
|
+
protected refreshToken?: AccessToken;
|
|
20
|
+
protected sendAuthCredentialsOnRequestBody?: boolean;
|
|
21
|
+
constructor(params: LhispOauthClientConstructorParams);
|
|
22
|
+
getAuthHeaderValue(): string;
|
|
23
|
+
parseData({ data, contentType }: {
|
|
24
|
+
data: any;
|
|
25
|
+
contentType: string;
|
|
26
|
+
}): string | undefined;
|
|
27
|
+
isTokenValid(token: AccessToken): boolean;
|
|
28
|
+
getAccessToken(): Promise<AccessToken>;
|
|
29
|
+
buildAccessToken(data: Omit<AccessToken, 'created_at'>): AccessToken;
|
|
30
|
+
getAuthToken(): string;
|
|
31
|
+
executarRequest({ method, path, data, params, contentType }: ExecutarRequestParams): Promise<any>;
|
|
32
|
+
get({ path, contentType, params }: ExecutarRequestParams): Promise<any>;
|
|
33
|
+
put({ path, data, contentType }: ExecutarRequestParams): Promise<any>;
|
|
34
|
+
post({ path, data, contentType }: ExecutarRequestParams): Promise<any>;
|
|
35
|
+
delete({ path, contentType }: ExecutarRequestParams): Promise<any>;
|
|
36
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.LhispOauthClient = void 0;
|
|
16
|
+
const querystring_1 = __importDefault(require("querystring"));
|
|
17
|
+
const https_1 = __importDefault(require("https"));
|
|
18
|
+
const axios_1 = __importDefault(require("axios"));
|
|
19
|
+
const lhisp_oauth_client_t_1 = require("./lhisp-oauth-client.t");
|
|
20
|
+
class LhispOauthClient {
|
|
21
|
+
constructor(params) {
|
|
22
|
+
if (params.certificado) {
|
|
23
|
+
this.agent = new https_1.default.Agent({
|
|
24
|
+
pfx: params.certificado,
|
|
25
|
+
passphrase: params.senhaCertificado,
|
|
26
|
+
rejectUnauthorized: false,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
this.agent = new https_1.default.Agent({
|
|
31
|
+
rejectUnauthorized: false
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
this.certificado = params.certificado;
|
|
35
|
+
this.headers = (params.headers ? params.headers : {});
|
|
36
|
+
this.apiUrl = params.apiUrl;
|
|
37
|
+
this.authUrl = params.authUrl;
|
|
38
|
+
this.authScope = params.authScope;
|
|
39
|
+
this.grantType = params.grantType || lhisp_oauth_client_t_1.defaultGrantType;
|
|
40
|
+
this.authContentType = params.authContentType || lhisp_oauth_client_t_1.defaultAuthContentType;
|
|
41
|
+
this.clientId = params.clientId;
|
|
42
|
+
this.clientSecret = params.clientSecret;
|
|
43
|
+
this.authHeaderName = params.authHeaderName || lhisp_oauth_client_t_1.defaultAuthHeaderName;
|
|
44
|
+
this.tokenHeaderName = params.tokenHeaderName || lhisp_oauth_client_t_1.defaultTokenHeaderName;
|
|
45
|
+
this.sendAuthCredentialsOnRequestBody = params.sendAuthCredentialsOnRequestBody;
|
|
46
|
+
}
|
|
47
|
+
getAuthHeaderValue() {
|
|
48
|
+
return `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64")}`;
|
|
49
|
+
}
|
|
50
|
+
parseData({ data, contentType = lhisp_oauth_client_t_1.ContentType.APPLICATION_JSON }) {
|
|
51
|
+
if (!data || Object.keys(data).length === 0)
|
|
52
|
+
return undefined;
|
|
53
|
+
switch (contentType) {
|
|
54
|
+
case lhisp_oauth_client_t_1.ContentType.APPLICATION_JSON: return JSON.stringify(data);
|
|
55
|
+
case lhisp_oauth_client_t_1.ContentType.APPLICATION_X_WWW_FORM_URLENCODED: return querystring_1.default.stringify(data);
|
|
56
|
+
default:
|
|
57
|
+
throw new Error(`Content Type Inválido: [${contentType}]`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
isTokenValid(token) {
|
|
61
|
+
if (!token)
|
|
62
|
+
return false;
|
|
63
|
+
if (!token.created_at)
|
|
64
|
+
return false;
|
|
65
|
+
const timeDiff = (Date.now() - token.created_at) / 1000;
|
|
66
|
+
return timeDiff < token.expires_in - 10;
|
|
67
|
+
}
|
|
68
|
+
getAccessToken() {
|
|
69
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
70
|
+
if (this.accessToken && this.isTokenValid(this.accessToken)) {
|
|
71
|
+
return this.accessToken;
|
|
72
|
+
}
|
|
73
|
+
// TODO: Implementar Refresh Token.
|
|
74
|
+
let authRequestOpt = {
|
|
75
|
+
method: 'POST',
|
|
76
|
+
url: this.authUrl,
|
|
77
|
+
httpsAgent: this.agent,
|
|
78
|
+
headers: {
|
|
79
|
+
[this.authHeaderName]: this.getAuthHeaderValue(),
|
|
80
|
+
'Content-Type': this.authContentType,
|
|
81
|
+
},
|
|
82
|
+
data: {},
|
|
83
|
+
};
|
|
84
|
+
if (this.grantType)
|
|
85
|
+
authRequestOpt.data.grant_type = this.grantType;
|
|
86
|
+
if (this.authScope)
|
|
87
|
+
authRequestOpt.data.scope = this.authScope;
|
|
88
|
+
if (this.sendAuthCredentialsOnRequestBody) {
|
|
89
|
+
if (this.clientId)
|
|
90
|
+
authRequestOpt.data.client_id = this.clientId;
|
|
91
|
+
if (this.clientSecret)
|
|
92
|
+
authRequestOpt.data.client_secret = this.clientSecret;
|
|
93
|
+
}
|
|
94
|
+
authRequestOpt.data = this.parseData({ data: authRequestOpt.data, contentType: this.authContentType });
|
|
95
|
+
const response = yield axios_1.default.request(authRequestOpt);
|
|
96
|
+
return this.buildAccessToken(response.data);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
buildAccessToken(data) {
|
|
100
|
+
this.accessToken = Object.assign(Object.assign({}, data), { created_at: Date.now() });
|
|
101
|
+
return this.accessToken;
|
|
102
|
+
}
|
|
103
|
+
getAuthToken() {
|
|
104
|
+
var _a, _b;
|
|
105
|
+
return `${(_a = this.accessToken) === null || _a === void 0 ? void 0 : _a.token_type} ${(_b = this.accessToken) === null || _b === void 0 ? void 0 : _b.access_token}`;
|
|
106
|
+
}
|
|
107
|
+
executarRequest({ method, path, data, params, contentType = lhisp_oauth_client_t_1.ContentType.APPLICATION_JSON }) {
|
|
108
|
+
var _a;
|
|
109
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
110
|
+
yield this.getAccessToken();
|
|
111
|
+
if (!((_a = this.accessToken) === null || _a === void 0 ? void 0 : _a.token_type)) {
|
|
112
|
+
console.log("## LHOAUTH2 NO TOKEN ?:", this.accessToken);
|
|
113
|
+
}
|
|
114
|
+
let headers = {
|
|
115
|
+
'Content-Type': contentType,
|
|
116
|
+
[this.tokenHeaderName]: this.getAuthToken(),
|
|
117
|
+
// ...this.headers
|
|
118
|
+
};
|
|
119
|
+
const response = yield axios_1.default.request({
|
|
120
|
+
method,
|
|
121
|
+
url: `${this.apiUrl}${path}`,
|
|
122
|
+
httpsAgent: this.agent,
|
|
123
|
+
headers,
|
|
124
|
+
data,
|
|
125
|
+
params
|
|
126
|
+
});
|
|
127
|
+
return response.data;
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
get({ path, contentType = lhisp_oauth_client_t_1.ContentType.APPLICATION_JSON, params }) {
|
|
131
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
132
|
+
return this.executarRequest({ method: 'GET', path, contentType, params });
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
put({ path, data, contentType = lhisp_oauth_client_t_1.ContentType.APPLICATION_JSON }) {
|
|
136
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
137
|
+
return this.executarRequest({ method: 'PUT', path, data, contentType });
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
post({ path, data, contentType = lhisp_oauth_client_t_1.ContentType.APPLICATION_JSON }) {
|
|
141
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
142
|
+
return this.executarRequest({ method: 'POST', path, data, contentType });
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
delete({ path, contentType = lhisp_oauth_client_t_1.ContentType.APPLICATION_JSON }) {
|
|
146
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
147
|
+
return this.executarRequest({ method: 'DELETE', path, contentType });
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
exports.LhispOauthClient = LhispOauthClient;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { AxiosRequestConfig } from "axios";
|
|
2
|
+
export interface Headers {
|
|
3
|
+
[name: string]: any;
|
|
4
|
+
}
|
|
5
|
+
export interface LhispOauthClientConstructorParams {
|
|
6
|
+
authUrl: string;
|
|
7
|
+
apiUrl: string;
|
|
8
|
+
clientId: string;
|
|
9
|
+
clientSecret: string;
|
|
10
|
+
certificado?: string;
|
|
11
|
+
senhaCertificado?: string;
|
|
12
|
+
authScope?: string;
|
|
13
|
+
authHeaderName?: string;
|
|
14
|
+
tokenHeaderName?: string;
|
|
15
|
+
headers?: Headers;
|
|
16
|
+
grantType?: string;
|
|
17
|
+
authContentType?: ContentType;
|
|
18
|
+
sendAuthCredentialsOnRequestBody?: boolean;
|
|
19
|
+
debug?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface ExecutarRequestParams extends AxiosRequestConfig {
|
|
22
|
+
path: string;
|
|
23
|
+
contentType?: ContentType;
|
|
24
|
+
}
|
|
25
|
+
export interface AccessToken {
|
|
26
|
+
token_type: string;
|
|
27
|
+
access_token: string;
|
|
28
|
+
expires_in: number;
|
|
29
|
+
scope?: string;
|
|
30
|
+
created_at?: number;
|
|
31
|
+
}
|
|
32
|
+
export declare enum ContentType {
|
|
33
|
+
APPLICATION_JSON = "application/json",
|
|
34
|
+
APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"
|
|
35
|
+
}
|
|
36
|
+
export declare const defaultGrantType = "client_credentials";
|
|
37
|
+
export declare const defaultAuthContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
|
|
38
|
+
export declare const defaultAuthHeaderName = "Authorization";
|
|
39
|
+
export declare const defaultTokenHeaderName = "Authorization";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defaultTokenHeaderName = exports.defaultAuthHeaderName = exports.defaultAuthContentType = exports.defaultGrantType = exports.ContentType = void 0;
|
|
4
|
+
var ContentType;
|
|
5
|
+
(function (ContentType) {
|
|
6
|
+
ContentType["APPLICATION_JSON"] = "application/json";
|
|
7
|
+
ContentType["APPLICATION_X_WWW_FORM_URLENCODED"] = "application/x-www-form-urlencoded";
|
|
8
|
+
})(ContentType = exports.ContentType || (exports.ContentType = {}));
|
|
9
|
+
exports.defaultGrantType = 'client_credentials';
|
|
10
|
+
exports.defaultAuthContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
|
|
11
|
+
exports.defaultAuthHeaderName = 'Authorization';
|
|
12
|
+
exports.defaultTokenHeaderName = 'Authorization';
|