Skip to content

Instantly share code, notes, and snippets.

@swilliams
Created June 25, 2017 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swilliams/6a9aa1855a52860a2ac9f9bcff4e5433 to your computer and use it in GitHub Desktop.
Save swilliams/6a9aa1855a52860a2ac9f9bcff4e5433 to your computer and use it in GitHub Desktop.
A bell provider for Harvest
import axios from 'axios';
import Bell from 'bell';
import Boom from 'boom';
import Joi from 'joi';
const harvestProvider = (options) => {
const validated = Joi.validate(options, Joi.object({
domain: Joi.string()
.hostname()
.required(),
}));
// TODO: bail if validation fails
const settings = validated.value;
const harvestURL = `https://${settings.domain}.harvestapp.com/oauth2`;
const harvestUserURL = `https://${settings.domain}.harvestapp.com/account/who_am_i`;
return {
protocol: 'oauth2',
useParamsAuth: true,
auth: harvestURL + '/authorize',
token: harvestURL + '/token',
profile(credentials, params, get, callback) {
// The user fetch URL requires Content-Type and Accept headers, but the auth and token URLs do not, so we need a custom 'getter' here, hence axios.
axios.get(harvestUserURL, {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${credentials.token}`,
},
}).then((response) => {
const account = response.data.user;
credentials.profile = {
token: credentials.token,
id: account.id,
email: account.email,
firstName: account.first_name,
lastName: account.last_name,
avatar: account.avatar_url,
admin: account.admin,
raw: account,
};
return callback();
})
.catch((err) => {
return Boom.internal(`Failed obtaining harvest user profile`, err);
});
},
};
};
// Add it to the Bell providers
Bell.providers.harvest = harvestProvider;
// Register the provider for use in a Hapi app
const cookiePassword = process.env.AUTH_COOKIE_PASSWORD;
const harvestId = process.env.HARVEST_CLIENT_ID;
const harvestSecret = process.env.HARVEST_SECRET;
server.auth.strategy('harvest', 'bell', {
provider: 'harvest',
password: cookiePassword,
clientId: harvestId,
clientSecret: harvestSecret,
isSecure: false, // for local dev, set it to `true` for prod
config: {
domain: 'my-company-domain',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment