Last active
December 11, 2024 15:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`, | |
}, | |
// Disable authentication, since the token was added manually. | |
disableAuthentication: true, | |
}); | |
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