Skip to content

Instantly share code, notes, and snippets.

@alexstrat
Created April 18, 2017 10:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexstrat/4221e3132f90f5cd7e3635be9f4d1542 to your computer and use it in GitHub Desktop.
Save alexstrat/4221e3132f90f5cd7e3635be9f4d1542 to your computer and use it in GitHub Desktop.
Auth0: a way to renew a token for Management API in a long-running script
const ManagementClient = require('auth0').ManagementClient
const Auth0TokenManager = require('./TokenManager')
const tokenManager = new Auth0TokenManager({
domain: DOMAIN,
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET
})
tokenManager
.getToken()
.then(token => new ExtendedManagementClient({ domain: DOMAIN, token }))
.then(client => /* do your things */ )
const jsonwebtoken = require('jsonwebtoken')
const request = require('superagent')
const Promise = require('bluebird')
class Auth0TokenManager {
constructor (options) {
this.domain = options.domain
this.clientId = options.clientId
this.clientSecret = options.clientSecret
this._cachedToken = null
}
getToken () {
if (this.isCachedTokenValid()) {
return Promise.resolve(this._cachedToken)
} else {
return Promise.resolve(this.generateToken())
}
}
generateToken (noCache = false) {
console.log('Generate a new token')
const url = `https://${this.domain}/oauth/token`
return request
.post(url)
.send({
grant_type: 'client_credentials',
client_id: this.clientId,
client_secret: this.clientSecret,
audience: `https://${this.domain}/api/v2/`
})
.set('Accept', 'application/json')
.then(res => res.body.access_token)
.then(token => {
if (!noCache) this._cachedToken = token
return token
})
}
isCachedTokenValid () {
if (!this._cachedToken) return false
const payload = jsonwebtoken.decode(this._cachedToken)
const clockTimestamp = Math.floor(Date.now() / 1000)
if (clockTimestamp >= payload.exp) {
// expired
return false
}
return true
}
}
module.exports = Auth0TokenManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment