Skip to content

Commit

Permalink
chore: run prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
tiwarishubham635 committed Nov 20, 2024
1 parent d8a038e commit f0c0a51
Show file tree
Hide file tree
Showing 17 changed files with 320 additions and 305 deletions.
12 changes: 6 additions & 6 deletions src/auth_strategy/AuthStrategy.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export default abstract class AuthStrategy {
private authType: string;
protected constructor(authType: string) {
this.authType = authType;
}
abstract getAuthString(): Promise<string>;
abstract requiresAuthentication(): boolean;
private authType: string;
protected constructor(authType: string) {
this.authType = authType;
}
abstract getAuthString(): Promise<string>;
abstract requiresAuthentication(): boolean;
}
32 changes: 16 additions & 16 deletions src/auth_strategy/BasicAuthStrategy.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import AuthStrategy from "./AuthStrategy";

export default class BasicAuthStrategy extends AuthStrategy {
private username: string;
private password: string;
private username: string;
private password: string;

constructor(username: string, password: string) {
super("basic");
this.username = username;
this.password = password;
}
constructor(username: string, password: string) {
super("basic");
this.username = username;
this.password = password;
}

getAuthString(): Promise<string> {
const auth = Buffer.from(this.username + ":" + this.password).toString(
"base64"
);
return Promise.resolve(`Basic ${auth}`);
}
getAuthString(): Promise<string> {
const auth = Buffer.from(this.username + ":" + this.password).toString(
"base64"
);
return Promise.resolve(`Basic ${auth}`);
}

requiresAuthentication(): boolean {
return true;
}
requiresAuthentication(): boolean {
return true;
}
}
18 changes: 9 additions & 9 deletions src/auth_strategy/NoAuthStrategy.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import AuthStrategy from "./AuthStrategy";

export default class NoAuthStrategy extends AuthStrategy {
constructor() {
super("noauth");
}
constructor() {
super("noauth");
}

getAuthString(): Promise<string> {
return Promise.resolve("");
}
getAuthString(): Promise<string> {
return Promise.resolve("");
}

requiresAuthentication(): boolean {
return false;
}
requiresAuthentication(): boolean {
return false;
}
}
101 changes: 52 additions & 49 deletions src/auth_strategy/TokenAuthStrategy.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,67 @@
import AuthStrategy from "./AuthStrategy";
import TokenManager from "../http/bearer_token/TokenManager";
import jwt, { JwtPayload } from 'jsonwebtoken';
import jwt, { JwtPayload } from "jsonwebtoken";

export default class TokenAuthStrategy extends AuthStrategy {
private token: string;
private tokenManager: TokenManager;
private token: string;
private tokenManager: TokenManager;

constructor(tokenManager: TokenManager) {
super("token");
this.token = "";
this.tokenManager = tokenManager;
}
constructor(tokenManager: TokenManager) {
super("token");
this.token = "";
this.tokenManager = tokenManager;
}

async getAuthString(): Promise<string> {
return this.fetchToken().then(token => {
this.token = token;
return `Bearer ${this.token}`;
}).catch(
error => {
throw new Error(`Failed to fetch access token: ${error}`);
}
);
}
async getAuthString(): Promise<string> {
return this.fetchToken()
.then((token) => {
this.token = token;
return `Bearer ${this.token}`;
})
.catch((error) => {
throw new Error(`Failed to fetch access token: ${error}`);
});
}

requiresAuthentication(): boolean {
return true;
}
requiresAuthentication(): boolean {
return true;
}

async fetchToken(): Promise<string> {
if (this.token == null || this.token.length === 0 || this.isTokenExpired(this.token)) {
return this.tokenManager.fetchToken();
}
return this.token;
async fetchToken(): Promise<string> {
if (
this.token == null ||
this.token.length === 0 ||
this.isTokenExpired(this.token)
) {
return this.tokenManager.fetchToken();
}
return this.token;
}

/**
* Function to check if the token is expired with a buffer of 30 seconds.
* @param token - The JWT token as a string.
* @returns Boolean indicating if the token is expired.
*/
isTokenExpired(token: string): boolean {
try {
// Decode the token without verifying the signature, as we only want to read the expiration for this check
const decoded = jwt.decode(token) as JwtPayload;
/**
* Function to check if the token is expired with a buffer of 30 seconds.
* @param token - The JWT token as a string.
* @returns Boolean indicating if the token is expired.
*/
isTokenExpired(token: string): boolean {
try {
// Decode the token without verifying the signature, as we only want to read the expiration for this check
const decoded = jwt.decode(token) as JwtPayload;

if (!decoded || !decoded.exp) {
// If the token doesn't have an expiration, consider it expired
return true;
}
if (!decoded || !decoded.exp) {
// If the token doesn't have an expiration, consider it expired
return true;
}

const expiresAt = decoded.exp * 1000;
const bufferMilliseconds = 30 * 1000;
const bufferExpiresAt = expiresAt - bufferMilliseconds;
const expiresAt = decoded.exp * 1000;
const bufferMilliseconds = 30 * 1000;
const bufferExpiresAt = expiresAt - bufferMilliseconds;

// Return true if the current time is after the expiration time with buffer
return Date.now() > bufferExpiresAt;
} catch (error) {
// If there's an error decoding the token, consider it expired
return true;
}
// Return true if the current time is after the expiration time with buffer
return Date.now() > bufferExpiresAt;
} catch (error) {
// If there's an error decoding the token, consider it expired
return true;
}

}
}
37 changes: 19 additions & 18 deletions src/base/BaseTwilio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,19 @@ namespace Twilio {
constructor(username?: string, password?: string, opts?: ClientOpts) {
this.setOpts(opts);
this.username =
username ??
this.env?.TWILIO_ACCOUNT_SID ??
process.env.TWILIO_ACCOUNT_SID ??
(() => {
throw new Error("username is required");
})();
username ??
this.env?.TWILIO_ACCOUNT_SID ??
process.env.TWILIO_ACCOUNT_SID ??
(() => {
throw new Error("username is required");
})();
this.password =
password ??
this.env?.TWILIO_AUTH_TOKEN ??
process.env.TWILIO_AUTH_TOKEN ??
(() => {
throw new Error("password is required");
})();
password ??
this.env?.TWILIO_AUTH_TOKEN ??
process.env.TWILIO_AUTH_TOKEN ??
(() => {
throw new Error("password is required");
})();
this.accountSid = "";
this.setAccountSid(this.opts?.accountSid || this.username);
this.invalidateOAuth();
Expand Down Expand Up @@ -161,8 +161,8 @@ namespace Twilio {

if (this.accountSid && !this.accountSid?.startsWith("AC")) {
const apiKeyMsg = this.accountSid?.startsWith("SK")
? ". The given SID indicates an API Key which requires the accountSid to be passed as an additional option"
: "";
? ". The given SID indicates an API Key which requires the accountSid to be passed as an additional option"
: "";

throw new Error("accountSid must start with AC" + apiKeyMsg);
}
Expand All @@ -175,12 +175,12 @@ namespace Twilio {
}

invalidateBasicAuth() {
this.username = undefined;
this.password = undefined;
this.username = undefined;
this.password = undefined;
}

invalidateOAuth() {
this.credentialProvider = undefined;
this.credentialProvider = undefined;
}

get httpClient() {
Expand Down Expand Up @@ -225,7 +225,8 @@ namespace Twilio {

const username = opts.username || this.username;
const password = opts.password || this.password;
const authStrategy = opts.authStrategy || this.credentialProvider?.toAuthStrategy();
const authStrategy =
opts.authStrategy || this.credentialProvider?.toAuthStrategy();

const headers = opts.headers || {};

Expand Down
11 changes: 7 additions & 4 deletions src/base/RequestClient.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import {HttpMethod} from "../interfaces";
import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from "axios";
import { HttpMethod } from "../interfaces";
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import * as fs from "fs";
import HttpsProxyAgent from "https-proxy-agent";
import qs from "qs";
import * as https from "https";
import Response from "../http/response";
import Request, {Headers, RequestOptions as LastRequestOptions,} from "../http/request";
import Request, {
Headers,
RequestOptions as LastRequestOptions,
} from "../http/request";
import AuthStrategy from "../auth_strategy/AuthStrategy";

const DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded";
Expand Down Expand Up @@ -179,7 +182,7 @@ class RequestClient {
"base64"
);
headers.Authorization = "Basic " + auth;
} else if(opts.authStrategy) {
} else if (opts.authStrategy) {
headers.Authorization = await opts.authStrategy.getAuthString();
}

Expand Down
86 changes: 44 additions & 42 deletions src/credential_provider/ClientCredentialProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,60 +5,62 @@ import ApiTokenManager from "../http/bearer_token/ApiTokenManager";
import TokenAuthStrategy from "../auth_strategy/TokenAuthStrategy";

class ClientCredentialProvider extends CredentialProvider {
grantType: string;
clientId: string;
clientSecret: string;
tokenManager: TokenManager | null;
grantType: string;
clientId: string;
clientSecret: string;
tokenManager: TokenManager | null;

constructor() {
super("client-credentials");
this.grantType = "client_credentials";
this.clientId = "";
this.clientSecret = "";
this.tokenManager = null;
}
constructor() {
super("client-credentials");
this.grantType = "client_credentials";
this.clientId = "";
this.clientSecret = "";
this.tokenManager = null;
}

public toAuthStrategy(): AuthStrategy {
if (this.tokenManager == null) {
this.tokenManager = new ApiTokenManager({
grantType: this.grantType,
clientId: this.clientId,
clientSecret: this.clientSecret,
});
}
return new TokenAuthStrategy(this.tokenManager);
public toAuthStrategy(): AuthStrategy {
if (this.tokenManager == null) {
this.tokenManager = new ApiTokenManager({
grantType: this.grantType,
clientId: this.clientId,
clientSecret: this.clientSecret,
});
}
return new TokenAuthStrategy(this.tokenManager);
}
}

namespace ClientCredentialProvider {
export class ClientCredentialProviderBuilder {
private readonly instance: ClientCredentialProvider;
export class ClientCredentialProviderBuilder {
private readonly instance: ClientCredentialProvider;

constructor() {
this.instance = new ClientCredentialProvider();
}
constructor() {
this.instance = new ClientCredentialProvider();
}

public setClientId(clientId: string): ClientCredentialProviderBuilder {
this.instance.clientId = clientId;
return this;
}
public setClientId(clientId: string): ClientCredentialProviderBuilder {
this.instance.clientId = clientId;
return this;
}

public setClientSecret(clientSecret: string): ClientCredentialProviderBuilder {
this.instance.clientSecret = clientSecret;
return this;
}
public setClientSecret(
clientSecret: string
): ClientCredentialProviderBuilder {
this.instance.clientSecret = clientSecret;
return this;
}

public setTokenManager(tokenManager: TokenManager): ClientCredentialProviderBuilder {
this.instance.tokenManager = tokenManager;
return this;
}
public setTokenManager(
tokenManager: TokenManager
): ClientCredentialProviderBuilder {
this.instance.tokenManager = tokenManager;
return this;
}

public build(): ClientCredentialProvider {
return this.instance;
}
public build(): ClientCredentialProvider {
return this.instance;
}
}
}

export = ClientCredentialProvider;


Loading

0 comments on commit f0c0a51

Please sign in to comment.