fix(ZendeskTrigger Node): Fix deprecated targets, replaced with webhooks (#3025)

* 🔨 fix for deprecated targets

*  Move crendentials injection to the credential file

Co-authored-by: ricardo <ricardoespinoza105@gmail.com>
This commit is contained in:
Michael Kret 2022-04-18 19:43:09 +03:00 committed by GitHub
parent 7fc8c53f8a
commit 794ad7c756
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 75 additions and 80 deletions

View file

@ -1,5 +1,8 @@
import { import {
ICredentialDataDecryptedObject,
ICredentialTestRequest,
ICredentialType, ICredentialType,
IHttpRequestOptions,
INodeProperties, INodeProperties,
} from 'n8n-workflow'; } from 'n8n-workflow';
@ -29,4 +32,17 @@ export class ZendeskApi implements ICredentialType {
default: '', default: '',
}, },
]; ];
async authenticate(credentials: ICredentialDataDecryptedObject, requestOptions: IHttpRequestOptions): Promise<IHttpRequestOptions> {
requestOptions.auth = {
username: `${credentials.email}/token`,
password: credentials.apiToken as string,
};
return requestOptions;
}
test: ICredentialTestRequest = {
request: {
baseURL: '=https://{{$credentials.subdomain}}.zendesk.com/api/v2',
url: '/ticket_fields.json',
},
};
} }

View file

@ -10,19 +10,27 @@ import {
} from 'n8n-core'; } from 'n8n-core';
import { import {
IDataObject, NodeApiError, NodeOperationError, IDataObject,
JsonObject,
NodeApiError,
} from 'n8n-workflow'; } from 'n8n-workflow';
export async function zendeskApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any export async function zendeskApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const authenticationMethod = this.getNodeParameter('authentication', 0); const authenticationMethod = this.getNodeParameter('authentication', 0);
let credentials;
if (authenticationMethod === 'apiToken') {
credentials = await this.getCredentials('zendeskApi') as { subdomain: string };
} else {
credentials = await this.getCredentials('zendeskOAuth2Api') as { subdomain: string };
}
let options: OptionsWithUri = { let options: OptionsWithUri = {
headers: {},
method, method,
qs, qs,
body, body,
//@ts-ignore uri: uri || getUri(resource, credentials.subdomain),
uri,
json: true, json: true,
qsStringifyOptions: { qsStringifyOptions: {
arrayFormat: 'brackets', arrayFormat: 'brackets',
@ -33,23 +41,13 @@ export async function zendeskApiRequest(this: IHookFunctions | IExecuteFunctions
if (Object.keys(options.body).length === 0) { if (Object.keys(options.body).length === 0) {
delete options.body; delete options.body;
} }
const credentialType = authenticationMethod === 'apiToken' ? 'zendeskApi' : 'zendeskOAuth2Api';
try { try {
if (authenticationMethod === 'apiToken') { return await this.helpers.requestWithAuthentication.call(this, credentialType, options);
const credentials = await this.getCredentials('zendeskApi');
const base64Key = Buffer.from(`${credentials.email}/token:${credentials.apiToken}`).toString('base64');
options.uri = uri || `https://${credentials.subdomain}.zendesk.com/api/v2${resource}.json`;
options.headers!['Authorization'] = `Basic ${base64Key}`;
return await this.helpers.request!(options);
} else {
const credentials = await this.getCredentials('zendeskOAuth2Api');
options.uri = uri || `https://${credentials.subdomain}.zendesk.com/api/v2${resource}.json`;
return await this.helpers.requestOAuth2!.call(this, 'zendeskOAuth2Api', options);
}
} catch(error) { } catch(error) {
throw new NodeApiError(this.getNode(), error); throw new NodeApiError(this.getNode(), error as JsonObject);
} }
} }
@ -89,3 +87,11 @@ export function validateJSON(json: string | undefined): any { // tslint:disable-
} }
return result; return result;
} }
function getUri(resource: string, subdomain: string) {
if (resource.includes('webhooks')) {
return `https://${subdomain}.zendesk.com/api/v2${resource}`;
} else {
return `https://${subdomain}.zendesk.com/api/v2${resource}.json`;
}
}

View file

@ -76,7 +76,6 @@ export class Zendesk implements INodeType {
], ],
}, },
}, },
testedBy: 'zendeskSoftwareApiTest',
}, },
{ {
name: 'zendeskOAuth2Api', name: 'zendeskOAuth2Api',
@ -153,42 +152,6 @@ export class Zendesk implements INodeType {
}; };
methods = { methods = {
credentialTest: {
async zendeskSoftwareApiTest(this: ICredentialTestFunctions, credential: ICredentialsDecrypted): Promise<INodeCredentialTestResult> {
const credentials = credential.data;
const subdomain = credentials!.subdomain;
const email = credentials!.email;
const apiToken = credentials!.apiToken;
const base64Key = Buffer.from(`${email}/token:${apiToken}`).toString('base64');
const options: OptionsWithUri = {
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${base64Key}`,
},
method: 'GET',
uri: `https://${subdomain}.zendesk.com/api/v2/ticket_fields.json`,
qs: {
recent: 0,
},
json: true,
timeout: 5000,
};
try {
await this.helpers.request!(options);
} catch (error) {
return {
status: 'Error',
message: `Connection details not valid: ${error.message}`,
};
}
return {
status: 'OK',
message: 'Authentication successful!',
};
},
},
loadOptions: { loadOptions: {
// Get all the custom fields to display them to user so that he can // Get all the custom fields to display them to user so that he can
// select them easily // select them easily

View file

@ -246,11 +246,11 @@ export class ZendeskTrigger implements INodeType {
const webhookUrl = this.getNodeWebhookUrl('default') as string; const webhookUrl = this.getNodeWebhookUrl('default') as string;
const webhookData = this.getWorkflowStaticData('node'); const webhookData = this.getWorkflowStaticData('node');
const conditions = this.getNodeParameter('conditions') as IDataObject; const conditions = this.getNodeParameter('conditions') as IDataObject;
const conditionsAll = conditions.all as [IDataObject];
let endpoint = ''; let endpoint = '';
const resultAll = [], resultAny = []; const resultAll = [], resultAny = [];
const conditionsAll = conditions.all as [IDataObject];
if (conditionsAll) { if (conditionsAll) {
for (const conditionAll of conditionsAll) { for (const conditionAll of conditionsAll) {
const aux: IDataObject = {}; const aux: IDataObject = {};
@ -282,12 +282,12 @@ export class ZendeskTrigger implements INodeType {
} }
} }
// check if there is a target already created // get all webhooks
endpoint = `/targets`; // https://developer.zendesk.com/api-reference/event-connectors/webhooks/webhooks/#list-webhooks
const targets = await zendeskApiRequestAllItems.call(this, 'targets', 'GET', endpoint); const { webhooks } = await zendeskApiRequest.call(this, 'GET', '/webhooks');
for (const target of targets) { for (const webhook of webhooks) {
if (target.target_url === webhookUrl) { if (webhook.endpoint === webhookUrl) {
webhookData.targetId = target.id.toString(); webhookData.targetId = webhook.id;
break; break;
} }
} }
@ -299,6 +299,7 @@ export class ZendeskTrigger implements INodeType {
endpoint = `/triggers/active`; endpoint = `/triggers/active`;
const triggers = await zendeskApiRequestAllItems.call(this, 'triggers', 'GET', endpoint); const triggers = await zendeskApiRequestAllItems.call(this, 'triggers', 'GET', endpoint);
for (const trigger of triggers) { for (const trigger of triggers) {
const toDeleteTriggers = []; const toDeleteTriggers = [];
// this trigger belong to the current target // this trigger belong to the current target
@ -317,23 +318,26 @@ export class ZendeskTrigger implements INodeType {
const webhookUrl = this.getNodeWebhookUrl('default') as string; const webhookUrl = this.getNodeWebhookUrl('default') as string;
const webhookData = this.getWorkflowStaticData('node'); const webhookData = this.getWorkflowStaticData('node');
const service = this.getNodeParameter('service') as string; const service = this.getNodeParameter('service') as string;
if (service === 'support') { if (service === 'support') {
const message: IDataObject = {}; const message: IDataObject = {};
const resultAll = [], resultAny = []; const resultAll = [], resultAny = [];
const conditions = this.getNodeParameter('conditions') as IDataObject; const conditions = this.getNodeParameter('conditions') as IDataObject;
const options = this.getNodeParameter('options') as IDataObject; const options = this.getNodeParameter('options') as IDataObject;
if (Object.keys(conditions).length === 0) { if (Object.keys(conditions).length === 0) {
throw new NodeOperationError(this.getNode(), 'You must have at least one condition'); throw new NodeOperationError(this.getNode(), 'You must have at least one condition');
} }
if (options.fields) { if (options.fields) {
// @ts-ignore for (const field of options.fields as string[]) {
for (const field of options.fields) {
// @ts-ignore // @ts-ignore
message[field] = `{{${field}}}`; message[field] = `{{${field}}}`;
} }
} else { } else {
message['ticket.id'] = '{{ticket.id}}'; message['ticket.id'] = '{{ticket.id}}';
} }
const conditionsAll = conditions.all as [IDataObject]; const conditionsAll = conditions.all as [IDataObject];
if (conditionsAll) { if (conditionsAll) {
for (const conditionAll of conditionsAll) { for (const conditionAll of conditionsAll) {
@ -349,6 +353,7 @@ export class ZendeskTrigger implements INodeType {
resultAll.push(aux); resultAll.push(aux);
} }
} }
const conditionsAny = conditions.any as [IDataObject]; const conditionsAny = conditions.any as [IDataObject];
if (conditionsAny) { if (conditionsAny) {
for (const conditionAny of conditionsAny) { for (const conditionAny of conditionsAny) {
@ -364,30 +369,35 @@ export class ZendeskTrigger implements INodeType {
resultAny.push(aux); resultAny.push(aux);
} }
} }
const urlParts = urlParse(webhookUrl);
const urlParts = new URL(webhookUrl);
const bodyTrigger: IDataObject = { const bodyTrigger: IDataObject = {
trigger: { trigger: {
title: `n8n-webhook:${urlParts.path}`, title: `n8n-webhook:${urlParts.pathname}`,
conditions: { conditions: {
all: resultAll, all: resultAll,
any: resultAny, any: resultAny,
}, },
actions: [ actions: [
{ {
field: 'notification_target', field: 'notification_webhook',
value: [], value: [],
}, },
], ],
}, },
}; };
const bodyTarget: IDataObject = { const bodyTarget: IDataObject = {
target: { webhook: {
title: 'n8n webhook', name:'n8n webhook',
type: 'http_target', endpoint: webhookUrl,
target_url: webhookUrl, http_method:'POST',
method: 'POST', status:'active',
active: true, request_format:'json',
content_type: 'application/json', subscriptions: [
'conditional_ticket_events',
],
}, },
}; };
let target: IDataObject = {}; let target: IDataObject = {};
@ -397,14 +407,14 @@ export class ZendeskTrigger implements INodeType {
if (webhookData.targetId !== undefined) { if (webhookData.targetId !== undefined) {
target.id = webhookData.targetId; target.id = webhookData.targetId;
} else { } else {
target = await zendeskApiRequest.call(this, 'POST', '/targets', bodyTarget); // create a webhook
target = target.target as IDataObject; // https://developer.zendesk.com/api-reference/event-connectors/webhooks/webhooks/#create-or-clone-webhook
target = (await zendeskApiRequest.call(this, 'POST', '/webhooks', bodyTarget)).webhook as IDataObject;
} }
// @ts-ignore // @ts-ignore
bodyTrigger.trigger.actions[0].value = [target.id, JSON.stringify(message)]; bodyTrigger.trigger.actions[0].value = [target.id, JSON.stringify(message)];
//@ts-ignore
const { trigger } = await zendeskApiRequest.call(this, 'POST', '/triggers', bodyTrigger); const { trigger } = await zendeskApiRequest.call(this, 'POST', '/triggers', bodyTrigger);
webhookData.webhookId = trigger.id; webhookData.webhookId = trigger.id;
webhookData.targetId = target.id; webhookData.targetId = target.id;
@ -415,11 +425,11 @@ export class ZendeskTrigger implements INodeType {
const webhookData = this.getWorkflowStaticData('node'); const webhookData = this.getWorkflowStaticData('node');
try { try {
await zendeskApiRequest.call(this, 'DELETE', `/triggers/${webhookData.webhookId}`); await zendeskApiRequest.call(this, 'DELETE', `/triggers/${webhookData.webhookId}`);
await zendeskApiRequest.call(this, 'DELETE', `/targets/${webhookData.targetId}`); await zendeskApiRequest.call(this, 'DELETE', `/webhooks/${webhookData.targetId}`);
} catch(error) { } catch(error) {
return false; return false;
} }
delete webhookData.webhookId; delete webhookData.triggerId;
delete webhookData.targetId; delete webhookData.targetId;
return true; return true;
}, },