@confluentinc/schemaregistry
Version:
Node.js client for Confluent Schema Registry
67 lines (66 loc) • 2.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports._OAuthClientBuilder = exports._OAuthClient = void 0;
const simple_oauth2_1 = require("simple-oauth2");
const abstract_oauth_client_1 = require("./abstract-oauth-client");
const TOKEN_EXPIRATION_THRESHOLD_SECONDS = 30 * 60; // 30 minutes
class OAuthClientBuilder extends abstract_oauth_client_1._AbstractBearerTokenProviderBuilder {
constructor(bearerAuthCredentials) {
super(bearerAuthCredentials);
}
validate() {
super.validate();
const missingField = OAuthClientBuilder.requiredFields.find(field => !(field in this.bearerAuthCredentials));
if (missingField) {
throw new Error(`OAuth credential '${missingField}' not provided`);
}
}
build(maxRetries, retriesWaitMs, retriesMaxWaitMs) {
this.validate();
return new OAuthClient(this.bearerAuthCredentials, maxRetries, retriesWaitMs, retriesMaxWaitMs);
}
}
exports._OAuthClientBuilder = OAuthClientBuilder;
OAuthClientBuilder.requiredFields = [
'clientId',
'clientSecret',
'issuerEndpointUrl',
'scope'
];
class OAuthClient extends abstract_oauth_client_1._AbstractOAuthClient {
constructor(bearerAuthCredentials, maxRetries, retriesWaitMs, retriesMaxWaitMs) {
super(bearerAuthCredentials, maxRetries, retriesWaitMs, retriesMaxWaitMs);
const tokenEndpoint = new URL(bearerAuthCredentials.issuerEndpointUrl);
const clientConfig = {
client: {
id: bearerAuthCredentials.clientId,
secret: bearerAuthCredentials.clientSecret,
},
auth: {
tokenHost: tokenEndpoint.origin,
tokenPath: tokenEndpoint.pathname
},
options: {
credentialsEncodingMode: 'loose'
}
};
this.tokenParams = { scope: bearerAuthCredentials.scope };
this.client = new simple_oauth2_1.ClientCredentials(clientConfig);
}
async fetchToken() {
this.tokenObject = await this.client.getToken(this.tokenParams);
return this.getAccessTokenString();
}
tokenExpired() {
return this.tokenObject === undefined ||
this.tokenObject.expired(TOKEN_EXPIRATION_THRESHOLD_SECONDS);
}
getAccessTokenString() {
const accessToken = this.tokenObject?.token?.['access_token'];
if (typeof accessToken !== 'string') {
throw new Error('Access token is not available');
}
return accessToken;
}
}
exports._OAuthClient = OAuthClient;