From 03b6d5ababcb200a40bef6bc685cd0efa0ac6c6a Mon Sep 17 00:00:00 2001 From: Mantas Lapenas <> Date: Fri, 30 Sep 2022 17:20:24 +0300 Subject: [PATCH] New: Select OAuth grant type for authentication --- README.md | 20 +++++++++++++++++++- src/access-provider.ts | 5 +++-- src/models.ts | 6 ++++++ 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8565601..369bcb6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ This a node API wrapper for accessing the Trustpilot APIs. You can learn all abo ## Installation -This module is built using Typescript and Node.js `v8.10.x`. +This module is built using Typescript and Node.js `v12.21.x`. If you are not using version 4 of Node, you'll have to transpile the code down to ES5 yourself. @@ -65,6 +65,24 @@ async run() { } ``` +### Choose OAuth token grant type + +For service-to-service communication use 'client_credentials' grant type and API application key, secret combination to obtain an OAuth token. (Default grant type: password) + +```ts +import { TrustpilotApi } from "trustpilot"; + +async run() { + const client = await new TrustpilotApi({ + key: 'YOUR-API-KEY', + secret: 'YOUR-SECRET', + granttype: 'client_credentials' + }).authenticate(); + + // Use client +} +``` + ### Override API Base URL The Invitations API methods have a different base URL. To override it, simply pass the `baseUrl`. diff --git a/src/access-provider.ts b/src/access-provider.ts index 4de1c35..d9776ae 100644 --- a/src/access-provider.ts +++ b/src/access-provider.ts @@ -1,6 +1,6 @@ import * as rp from 'request-promise-native'; -import { ITrustpilotApiConfig } from './models'; +import { GrantType, ITrustpilotApiConfig } from './models'; export class AccessProvider { private apiAuthorization: any | undefined; @@ -26,12 +26,13 @@ export class AccessProvider { private createApiTokenRequest() { const defaultRequest = { form: { - grant_type: 'password', + grant_type: this.trustpilotApiConfig.grantType || GrantType.password, password: this.trustpilotApiConfig.password, username: this.trustpilotApiConfig.username, }, uri: '/v1/oauth/oauth-business-users-for-applications/accesstoken', }; + return (this.trustpilotApiConfig.tokenRequest) as typeof defaultRequest || defaultRequest; } diff --git a/src/models.ts b/src/models.ts index 6c99176..575c5ca 100644 --- a/src/models.ts +++ b/src/models.ts @@ -10,7 +10,13 @@ interface IConfig { password: string; tokenRequest: any; accessToken: string; + grantType: GrantType; defaultHeaders: IHeaders; } +export enum GrantType { + password = 'password', + client_credentials = 'client_credentials' +} + export interface ITrustpilotApiConfig extends Partial {}