Skip to content

Commit

Permalink
Merge pull request #232 from dikoga/forrester
Browse files Browse the repository at this point in the history
Forrester
  • Loading branch information
shushen authored Jun 5, 2020
2 parents d97099a + 6dfdc03 commit 3cadc63
Show file tree
Hide file tree
Showing 5 changed files with 226 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "rules-templates",
"version": "0.10.1",
"version": "0.10.2",
"description": "Auth0 Rules Repository",
"main": "./rules",
"scripts": {
Expand Down
10 changes: 10 additions & 0 deletions rules.json
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,16 @@
"description": "<p>This rule shows how to post the variables sent to your Rule a custom webhook in an ASP.NET WebApi application. This is useful for situations where you want to enrich the User's profile with your internal ID before the JsonWebToken is created, or if you want to seamlessly register new users.</p>\n<p>In this example, we're going to get the internal UserId for your app, then persist it to the Auth0 UserProfile so we only have to make this request the first time a new user signs in.</p>\n<p>Within the snippet, the \"secretToken\" is a simple way to ensure that the communication is coming from Auth0. Just configure a random string for the Rule, and then check for that string in your WebApi request.</p>\n<p>In your WebApi code, complete whatever operations are necessary, then call <code>return Json(new { customId = USERSCUSTOMID });</code> to return the required JSON to the Rule.</p>\n<blockquote>\n <p>Note: Be sure to change the URL for the request to your website and controller, and make sure the controller is decorated with the <code>[HttpPost]</code> attribute.</p>\n</blockquote>\n<p>Contributed by Robert McLaws, AdvancedREI.com</p>",
"code": "function aspnetWebApi(user, context, callback) {\n const request = require('request');\n\n user.app_metadata = user.app_metadata || {};\n if (user.app_metadata.customId) {\n console.log('Found ID!');\n return callback(null, user, context);\n }\n\n // You should make your requests over SSL to protect your app secrets.\n request.post({\n url: 'https://yourwebsite.com/auth0',\n json: {\n user: user,\n context: context,\n secretToken: configuration.YOURWEBSITE_SECRET_TOKEN,\n },\n timeout: 15000\n }, (err, response, body) => {\n if (err) return callback(new Error(err));\n\n user.app_metadata.customId = body.customId;\n context.idToken['https://example.com/custom_id'] = body.customId;\n\n auth0.users.updateAppMetadata(user.user_id, user.app_metadata)\n .then(function(){\n callback(null, user, context);\n })\n .catch(function(err){\n callback(err);\n });\n });\n}"
},
{
"id": "create-new-contact-add-to-contact-list-hubspot",
"title": "Add New Contact to HubSpot for Marketing",
"overview": "Add New Contact to HubSpot then add to a List for marketing",
"categories": [
"webhook"
],
"description": "<p>This rule will add a New Contact to HubSpot if they don't already exist, and then add that Contact to a List for marketing.</p>\n<p>This is useful for cases where you want to enroll new users in an email list related to your application.\nYou will need to set two values HUBSPOT<em>API</em>KEY and HUBSPOT<em>NEW</em>MEMBER<em>LIST</em>ID\nFor more details about the Rules configuration settings, see here https://auth0.com/docs/rules/guides/configuration\nFor more information about Hubspot API keys see here https://knowledge.hubspot.com/integrations/how-do-i-get-my-hubspot-api-key\nUse 1 as the value for HUBSPOT<em>NEW</em>MEMBER<em>LIST</em>ID for the default list in Hubspot. Otherwise, you can see the ID of any list in HubSpot visiting it, and looking at the URL. It will have this format https://app.hubspot.com/contacts/:portalId/lists/:listId where :listId is the value you want.</p>",
"code": "function createNewContactAndAddToContactListHubSpot(user, context, callback) {\n const request = require('request');\n user.app_metadata = user.app_metadata || {};\n\n //Populate the variables below with appropriate values\n const apiKey = configuration.HUBSPOT_API_KEY; // For more information about HubSpot API keys https://knowledge.hubspot.com/integrations/how-do-i-get-my-hubspot-api-key\n const newMemberListId = configuration.HUBSPOT_NEW_MEMBER_LIST_ID; //Use 1 for default list, otherwise You can see the ID of any list in HubSpot visiting it and looking at the URL. It will have this format https://app.hubspot.com/contacts/:portalId/lists/:listId\n\n //************** CREATE A NEW CONTACT IN HUBSPOT **********************/\n const contactData = JSON.stringify({\n \"properties\": [\n {\n \"property\": \"email\",\n \"value\": user.email\n },\n {\n \"property\": \"firstname\",\n \"value\": user.given_name || \"\"\n },\n {\n \"property\": \"lastname\",\n \"value\": user.family_name || \"\"\n }\n ]\n });\n\n const contactOptions = {\n url: 'https://api.hubapi.com/contacts/v1/contact/?hapikey=' + apiKey,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: contactData\n };\n request(contactOptions, function (err, response, body) {\n if (err || (response.statusCode !== 200 && response.statusCode !== 409)) {\n console.log('NOTIFY YOUR MONITOR APPLICATION OF AN ERROR ADDING A NEW CONTACT');\n user.app_metadata.hubSpotContactCreated = false;\n } else {\n console.log('[NEW CONTACT] HANDLE ANY POSSIBLE INFORMATION YOU MIGHT WANT TO STORE IN THE USERS PROFILE');\n const newContactId = JSON.parse(body).vid;\n user.app_metadata.hubSpotContactCreated = true;\n user.app_metadata.hubSpotContactId = newContactId;\n\n //************** ADD NEW CONTACT TO AN EXISTING E-MAIL LIST IN HUBSPOT **********************/\n const subscribeData = JSON.stringify({ \"vids\": [newContactId] });\n //************** NOTE THIS USES LIST NUMBER AND HUBSPOT API KEY THE URL BELOW **********************/\n const subscribeOptions = {\n url: 'https://api.hubapi.com/contacts/v1/lists/' + newMemberListId + '/add?hapikey=' + apiKey,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: subscribeData\n };\n\n request(subscribeOptions, function (err, response, body) {\n if (err || (response.statusCode !== 200 && response.statusCode !== 409)) {\n console.log('NOTIFY YOUR MONITOR APPLICATION OF AN ERROR ON ADDING CONTACT TO A EMAIL LIST');\n console.log(err);\n user.app_metadata.hubSpotContactAddedToList = false;\n } else {\n user.app_metadata.hubSpotContactAddedToList = true;\n console.log('[EMAIL LIST] HANDLE ANY POSSIBLE INFORMATION YOU MIGHT WANT TO STORE IN THE USERS PROFILE');\n }\n\n auth0.users.updateAppMetadata(user.user_id, user.app_metadata);\n });\n }\n auth0.users.updateAppMetadata(user.user_id, user.app_metadata);\n });\n\n return callback(null, user, context);\n}"
},
{
"id": "creates-lead-salesforce",
"title": "Creates a new Lead in Salesforce on First Login",
Expand Down
89 changes: 89 additions & 0 deletions src/rules/create-new-contact-add-to-contact-list-hubspot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* @title Add New Contact to HubSpot for Marketing
* @overview Add New Contact to HubSpot then add to a List for marketing
* @gallery true
* @category webhook
*
* This rule will add a New Contact to HubSpot if they don't already exist, and then add that Contact to a List for marketing.
*
* This is useful for cases where you want to enroll new users in an email list related to your application.
* You will need to set two values HUBSPOT_API_KEY and HUBSPOT_NEW_MEMBER_LIST_ID
* For more details about the Rules configuration settings, see here https://auth0.com/docs/rules/guides/configuration
* For more information about Hubspot API keys see here https://knowledge.hubspot.com/integrations/how-do-i-get-my-hubspot-api-key
* Use 1 as the value for HUBSPOT_NEW_MEMBER_LIST_ID for the default list in Hubspot. Otherwise, you can see the ID of any list in HubSpot visiting it, and looking at the URL. It will have this format https://app.hubspot.com/contacts/:portalId/lists/:listId where :listId is the value you want.
*/

function createNewContactAndAddToContactListHubSpot(user, context, callback) {
const request = require('request');
user.app_metadata = user.app_metadata || {};

//Populate the variables below with appropriate values
const apiKey = configuration.HUBSPOT_API_KEY; // For more information about HubSpot API keys https://knowledge.hubspot.com/integrations/how-do-i-get-my-hubspot-api-key
const newMemberListId = configuration.HUBSPOT_NEW_MEMBER_LIST_ID; //Use 1 for default list, otherwise You can see the ID of any list in HubSpot visiting it and looking at the URL. It will have this format https://app.hubspot.com/contacts/:portalId/lists/:listId

//************** CREATE A NEW CONTACT IN HUBSPOT **********************/
const contactData = JSON.stringify({
"properties": [
{
"property": "email",
"value": user.email
},
{
"property": "firstname",
"value": user.given_name || ""
},
{
"property": "lastname",
"value": user.family_name || ""
}
]
});

const contactOptions = {
url: 'https://api.hubapi.com/contacts/v1/contact/?hapikey=' + apiKey,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: contactData
};
request(contactOptions, function (err, response, body) {
if (err || (response.statusCode !== 200 && response.statusCode !== 409)) {
console.log('NOTIFY YOUR MONITOR APPLICATION OF AN ERROR ADDING A NEW CONTACT');
user.app_metadata.hubSpotContactCreated = false;
} else {
console.log('[NEW CONTACT] HANDLE ANY POSSIBLE INFORMATION YOU MIGHT WANT TO STORE IN THE USERS PROFILE');
const newContactId = JSON.parse(body).vid;
user.app_metadata.hubSpotContactCreated = true;
user.app_metadata.hubSpotContactId = newContactId;

//************** ADD NEW CONTACT TO AN EXISTING E-MAIL LIST IN HUBSPOT **********************/
const subscribeData = JSON.stringify({ "vids": [newContactId] });
//************** NOTE THIS USES LIST NUMBER AND HUBSPOT API KEY THE URL BELOW **********************/
const subscribeOptions = {
url: 'https://api.hubapi.com/contacts/v1/lists/' + newMemberListId + '/add?hapikey=' + apiKey,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: subscribeData
};

request(subscribeOptions, function (err, response, body) {
if (err || (response.statusCode !== 200 && response.statusCode !== 409)) {
console.log('NOTIFY YOUR MONITOR APPLICATION OF AN ERROR ON ADDING CONTACT TO A EMAIL LIST');
console.log(err);
user.app_metadata.hubSpotContactAddedToList = false;
} else {
user.app_metadata.hubSpotContactAddedToList = true;
console.log('[EMAIL LIST] HANDLE ANY POSSIBLE INFORMATION YOU MIGHT WANT TO STORE IN THE USERS PROFILE');
}

auth0.users.updateAppMetadata(user.user_id, user.app_metadata);
});
}
auth0.users.updateAppMetadata(user.user_id, user.app_metadata);
});

return callback(null, user, context);
}
125 changes: 125 additions & 0 deletions test/rules/create-new-contact-add-to-contact-list-hubspot.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
'use strict';

const loadRule = require('../utils/load-rule');
const ContextBuilder = require('../utils/contextBuilder');
const UserBuilder = require('../utils/userBuilder');

const ruleName = 'create-new-contact-add-to-contact-list-hubspot';
describe(ruleName + ' - sunny path', () => {
let rule;
let context;
let user;
let globals;
let stubs = {};

const newHubSpotContactId = 123;

beforeEach(() => {
globals = {
auth0: {
users: {
updateAppMetadata: jest.fn()
}
},
configuration: {
HUBSPOT_API_KEY: 'API_KEY',
HUBSPOT_NEW_MEMBER_LIST_ID: '1',
}
};

stubs['request'] = jest.fn().mockImplementationOnce((obj, cb) => {
cb(null, { statusCode: 200 }, JSON.stringify({ vid: newHubSpotContactId }));
})
.mockImplementationOnce((obj, cb) => {
cb(null, { statusCode: 200 }, {
"updated": [
newHubSpotContactId
],
"discarded": [],
"invalidVids": [],
"invalidEmails": []
});
});

user = new UserBuilder().build();
user.given_name = "Given";
user.family_name = "Family";

context = new ContextBuilder().build();
rule = loadRule(ruleName, globals, stubs);
});

it('should create a hubspot contact, add to a contact list and set app metadata', (done) => {
rule(user, context, () => { });

// First POST is to get the access token
const newTokenPostOptions = stubs.request.mock.calls[0][0];
const newTokenPostBody = JSON.parse(newTokenPostOptions.body);
expect(newTokenPostOptions.url).toBe('https://api.hubapi.com/contacts/v1/contact/?hapikey=' + globals.configuration.HUBSPOT_API_KEY);
expect(newTokenPostBody.properties[0].value).toBe(user.email);
expect(newTokenPostBody.properties[1].value).toBe(user.given_name);
expect(newTokenPostBody.properties[2].value).toBe(user.family_name);

// Second POST is to create the lead
const addContactToListPostOptions = stubs.request.mock.calls[1][0];
const addContactToListPostBody = JSON.parse(addContactToListPostOptions.body);
expect(addContactToListPostOptions.url).toBe('https://api.hubapi.com/contacts/v1/lists/' + globals.configuration.HUBSPOT_NEW_MEMBER_LIST_ID + '/add?hapikey=' + globals.configuration.HUBSPOT_API_KEY);
expect(addContactToListPostBody.vids[0]).toBe(newHubSpotContactId);

const updateAppMetadataCall = globals.auth0.users.updateAppMetadata.mock.calls[0];
expect(updateAppMetadataCall[0]).toBe(user.user_id);
expect(updateAppMetadataCall[1].hubSpotContactCreated).toBe(true);
expect(updateAppMetadataCall[1].hubSpotContactId).toBe(newHubSpotContactId);
expect(updateAppMetadataCall[1].hubSpotContactAddedToList).toBe(true);

done();
});

describe('fail to create a contact', () => {
beforeEach(() => {

stubs['request'] = jest.fn().mockImplementationOnce((obj, cb) => {
cb(null, { statusCode: 500 }, null);
})
.mockImplementationOnce((obj, cb) => {
cb(null, { statusCode: 500 }, null);
});
});

it('should fail create a hubspot contact', (done) => {
rule(user, context, () => { });

const updateAppMetadataCall = globals.auth0.users.updateAppMetadata.mock.calls[0];
expect(updateAppMetadataCall[0]).toBe(user.user_id);
expect(updateAppMetadataCall[1].hubSpotContactCreated).toBe(false);

done();
});
});


describe('fail to add the contact to a list', () => {
beforeEach(() => {

stubs['request'] = jest.fn().mockImplementationOnce((obj, cb) => {
cb(null, { statusCode: 200 }, JSON.stringify({ vid: newHubSpotContactId }));
})
.mockImplementationOnce((obj, cb) => {
cb(null, { statusCode: 500 }, null);
});
});

it('should fail create a hubspot contact', (done) => {
rule(user, context, () => { });

const updateAppMetadataCall = globals.auth0.users.updateAppMetadata.mock.calls[0];
expect(updateAppMetadataCall[0]).toBe(user.user_id);
expect(updateAppMetadataCall[1].hubSpotContactCreated).toBe(true);
expect(updateAppMetadataCall[1].hubSpotContactId).toBe(newHubSpotContactId);
expect(updateAppMetadataCall[1].hubSpotContactAddedToList).toBe(false);

done();
});
});
});

0 comments on commit 3cadc63

Please sign in to comment.