feat: access token generic para permitir customização

This commit is contained in:
Leandro Costa 2023-06-16 19:06:10 -03:00
parent 4b61c118ad
commit 477d9fc6a7
3 changed files with 46 additions and 52 deletions

View file

@ -1,2 +1,2 @@
export * from './lhisp-oauth-client'; export * from "./lhisp-oauth-client";
export * from './lhisp-oauth-client.t'; export * from "./lhisp-oauth-client.t";

View file

@ -1,45 +1,44 @@
import { AxiosRequestConfig } from "axios"; import { AxiosRequestConfig } from "axios";
export interface Headers { export interface Headers {
[name: string]: any; [name: string]: any;
} }
export interface LhispOauthClientConstructorParams { export interface LhispOauthClientConstructorParams {
authUrl: string; authUrl: string;
apiUrl: string; apiUrl: string;
clientId: string; clientId: string;
clientSecret: string; clientSecret: string;
certificado?: string; certificado?: string;
senhaCertificado?: string; senhaCertificado?: string;
authScope?: string; authScope?: string;
authHeaderName?: string; authHeaderName?: string;
tokenHeaderName?: string; tokenHeaderName?: string;
headers?: Headers; headers?: Headers;
grantType?: string; grantType?: string;
authContentType?: ContentType; authContentType?: ContentType;
sendAuthCredentialsOnRequestBody?: boolean; sendAuthCredentialsOnRequestBody?: boolean;
debug?: boolean; debug?: boolean;
} }
export interface ExecutarRequestParams extends AxiosRequestConfig { export interface ExecutarRequestParams extends AxiosRequestConfig {
path: string; path: string;
contentType?: ContentType, contentType?: ContentType;
} }
export interface AccessToken { export interface AccessToken {
token_type: string; token_type: string;
access_token: string; access_token: string;
expires_in: number; expires_in: number;
scope?: string; scope?: string;
created_at?: number;
} }
export enum ContentType { export enum ContentType {
APPLICATION_JSON='application/json', APPLICATION_JSON = "application/json",
APPLICATION_X_WWW_FORM_URLENCODED='application/x-www-form-urlencoded', APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded",
} }
export const defaultGrantType = 'client_credentials'; export const defaultGrantType = "client_credentials";
export const defaultAuthContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED; export const defaultAuthContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
export const defaultAuthHeaderName = 'Authorization'; export const defaultAuthHeaderName = "Authorization";
export const defaultTokenHeaderName = 'Authorization'; export const defaultTokenHeaderName = "Authorization";

View file

@ -13,7 +13,7 @@ import {
} from "./lhisp-oauth-client.t"; } from "./lhisp-oauth-client.t";
import logger from "lhisp-logger"; import logger from "lhisp-logger";
export class LhispOauthClient { export class LhispOauthClient<iAccessToken extends AccessToken = AccessToken> {
protected authUrl: string; protected authUrl: string;
protected apiUrl: string; protected apiUrl: string;
protected clientId: string; protected clientId: string;
@ -27,8 +27,10 @@ export class LhispOauthClient {
protected headers?: Headers; protected headers?: Headers;
protected grantType?: string; protected grantType?: string;
protected agent: https.Agent; protected agent: https.Agent;
protected accessToken?: AccessToken; protected accessToken?: iAccessToken;
protected refreshToken?: AccessToken; protected refreshToken?: iAccessToken;
protected tokenCreatedAt = 0;
protected tokenExpiresIn = 0;
protected sendAuthCredentialsOnRequestBody?: boolean; protected sendAuthCredentialsOnRequestBody?: boolean;
constructor(params: LhispOauthClientConstructorParams) { constructor(params: LhispOauthClientConstructorParams) {
@ -75,16 +77,16 @@ export class LhispOauthClient {
} }
} }
isTokenValid(token: AccessToken) { isTokenValid() {
if (!token) return false; if (!this.accessToken) return false;
if (!token.created_at) return false; if (!this.tokenCreatedAt) return false;
const timeDiff = (Date.now() - token.created_at) / 1000; const timeDiff = (Date.now() - this.tokenCreatedAt) / 1000;
return timeDiff < token.expires_in - 10; return timeDiff < this.tokenExpiresIn - 10;
} }
async getAccessToken(): Promise<AccessToken> { async getAccessToken(): Promise<iAccessToken> {
try { try {
if (this.accessToken && this.isTokenValid(this.accessToken)) { if (this.accessToken && this.isTokenValid()) {
return this.accessToken; return this.accessToken;
} }
@ -113,21 +115,18 @@ export class LhispOauthClient {
data: authRequestOpt.data, data: authRequestOpt.data,
contentType: this.authContentType, contentType: this.authContentType,
}); });
const response = await axios.request(authRequestOpt); const resp = await axios.request<iAccessToken>(authRequestOpt);
return this.buildAccessToken(response.data); this.accessToken = this.buildAccessToken(resp.data);
this.tokenCreatedAt = new Date().getTime();
return this.accessToken;
} catch (error) { } catch (error) {
logger.error({ message: "LhispOauthClient.getAccessToken", error }); logger.error({ message: "LhispOauthClient.getAccessToken", error });
throw error; throw error;
} }
} }
buildAccessToken(data: Omit<AccessToken, "created_at">): AccessToken { buildAccessToken(data: any) {
this.accessToken = { return data as iAccessToken;
...data,
created_at: Date.now(),
};
return this.accessToken;
} }
getAuthToken() { getAuthToken() {
@ -143,14 +142,10 @@ export class LhispOauthClient {
}: ExecutarRequestParams): Promise<ResponseType> { }: ExecutarRequestParams): Promise<ResponseType> {
try { try {
await this.getAccessToken(); await this.getAccessToken();
if (!this.accessToken?.token_type) {
console.log("## LHOAUTH2 NO TOKEN ?:", this.accessToken);
}
let headers = { let headers = {
"Content-Type": contentType, "Content-Type": contentType,
[this.tokenHeaderName]: this.getAuthToken(), [this.tokenHeaderName]: this.getAuthToken(),
// ...this.headers
}; };
const response = await axios.request<ResponseType>({ const response = await axios.request<ResponseType>({