Skip to content

Instantly share code, notes, and snippets.

@balazsorban44
Created February 23, 2021 21:28
Show Gist options
  • Save balazsorban44/badea7e350637bc9b42bae4b36ced1e8 to your computer and use it in GitHub Desktop.
Save balazsorban44/badea7e350637bc9b42bae4b36ced1e8 to your computer and use it in GitHub Desktop.
import NodeCache from "node-cache"
const cache = new NodeCache()
/**
* Retrieves an access_token from an OAuth Provider for building purposes,
* using client_credentials (client secret) authorization type.
*/
export default async function getBuildToken(){
try {
const cachedAccessToken = cache.get("access_token")
// Try returning the cached token
if (cachedAccessToken) {
return cachedAccessToken
}
/**
* If no access token was present in the cache, fetch a new one
* @see https://tools.ietf.org/html/rfc6749#section-4.4.3
*/
const {access_token, expires_in} = await getServerSideAccessToken()
// Update the cache with a time-to-live
cache.set("access_token", access_token, expires_in)
return access_token
} catch (error) {
console.error(error)
throw new Error("Could not get access_token")
}
}
async function getServerSideAccessToken() {
const response = await fetch("https://oauth-provider.com/connect/token", {
body: new URLSearchParams({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
grant_type: "client_credentials",
scope: "",
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "post",
})
if (response.ok) {
return response.json()
}
throw new Error("Failed getting an access_token")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment