Skip to content

Instantly share code, notes, and snippets.

@erickoledadevrel
Created March 6, 2024 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erickoledadevrel/e4a8ede4987013fcb7f18afd67633f64 to your computer and use it in GitHub Desktop.
Save erickoledadevrel/e4a8ede4987013fcb7f18afd67633f64 to your computer and use it in GitHub Desktop.
Using the password grant to connect to the Zendesk API in a Coda Pack
import * as coda from "@codahq/packs-sdk";
export const pack = coda.newPack();
const ClientId = "...";
const ClientSecret = "...";
pack.addNetworkDomain("zendesk.com");
pack.setUserAuthentication({
type: coda.AuthenticationType.Custom,
params: [
{
name: "username",
description: "Username",
},
{
name: "password",
description: "Password",
}
],
requiresEndpointUrl: true
});
pack.addFormula({
name: "UserName",
description: "Gets the name of the authenticated user.",
parameters: [],
resultType: coda.ValueType.String,
execute: async function (args, context) {
// Use the Custom auth parameters to obtain an access token.
let accessToken = await getAccessToken(context);
// Make the API request using the access token.
let response = await context.fetcher.fetch({
method: "GET",
url: "/api/v2/users/me",
headers: {
// Manually add the Authorization header.
Authorization: `Bearer ${accessToken}`,
},
});
let user = response.body.user;
return user.name;
},
});
async function getAccessToken(context: coda.ExecutionContext) {
let invocationToken = context.invocationToken;
let payload = {
grant_type: "password",
client_id: ClientId,
client_secret: ClientSecret,
scope: "read",
// Pass the username and password using the Custom auth placeholder syntax.
username: `{{username-${invocationToken}}}`,
password: `{{password-${invocationToken}}}`,
};
let response = await context.fetcher.fetch({
method: "POST",
url: "/oauth/tokens",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
let data = response.body;
return data.access_token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment