Created
October 26, 2021 16:39
-
-
Save jjeanjacques10/6481d7d9391af7a466cca0957455e285 to your computer and use it in GitHub Desktop.
RefreshTokenHubspot.js
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 axios from 'axios'; | |
import NodeCache from 'node-cache'; | |
import querystring from 'qs'; | |
const accessTokenCache = new NodeCache({ deleteOnExpire: true }); | |
class AuthService { | |
constructor() { | |
this.CLIENT_ID = process.env.CLIENT_ID | |
this.CLIENT_SECRET = process.env.CLIENT_SECRET | |
this.REDIRECT_URI = process.env.REDIRECT_URI | |
this.refreshTokenStore = process.env.REFRESH_TOKEN | |
} | |
async exchangeForTokens(exchangeProof) { | |
try { | |
const responseBody = await axios.post('https://api.hubapi.com/oauth/v1/token', querystring.stringify(exchangeProof), { | |
headers: { | |
"Content-Type": "application/x-www-form-urlencoded" | |
} | |
}); | |
// Usually, this token data should be persisted in a database and associated with | |
// a user identity. | |
const tokens = responseBody.data; | |
this.refreshTokenStore = tokens.refresh_token; | |
process.env.REFRESH_TOKEN = this.refreshTokenStore; | |
accessTokenCache.set('token', tokens.access_token, Math.round(tokens.expires_in * 0.75)); | |
console.log(' > Received an access token and refresh token'); | |
return tokens.access_token; | |
} catch (e) { | |
console.error(` > Error exchanging ${exchangeProof.grant_type} for access token`); | |
console.log(e); | |
throw e; | |
} | |
}; | |
async refreshAccessToken() { | |
const refreshTokenProof = { | |
grant_type: 'refresh_token', | |
client_id: this.CLIENT_ID, | |
client_secret: this.CLIENT_SECRET, | |
refresh_token: this.refreshTokenStore | |
}; | |
return await this.exchangeForTokens(refreshTokenProof); | |
}; | |
async getAccessToken() { | |
// If the access token has expired, retrieve | |
// a new one using the refresh token | |
if (!accessTokenCache.get('token')) { | |
console.log('Refreshing expired access token'); | |
await this.refreshAccessToken(); | |
} | |
return accessTokenCache.get('token'); | |
}; | |
isAuthorized() { | |
return this.refreshTokenStore ? true : false; | |
}; | |
} | |
export default new AuthService(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment