wkr-util
Version:
Utility library for wkr project.
59 lines (49 loc) • 1.69 kB
JavaScript
import fetch from 'node-fetch'
import urlJoin from 'url-join'
import jwt from 'jsonwebtoken'
import {get} from '@cullylarson/f'
import {retry, memoizePUntil} from '@cullylarson/p'
import {nowStamp, responseData} from './'
import ResponseError from './errors/ResponseError'
const AppAuth = (authApiUrl, appId, appSecret) => {
const twoMinutes = 120
// if there is less than 2 minutes left on the JWT, then it should be renewed
const shouldRenew = tokenInfo => {
return !tokenInfo || !tokenInfo.exp || (tokenInfo.exp - nowStamp()) <= twoMinutes
}
const tokenInfoFromToken = token => {
const decoded = jwt.decode(token)
return {
token,
exp: get(['header', 'exp'], undefined, decoded),
}
}
const getTokenInfo = memoizePUntil(shouldRenew, retry(3, () => {
const query = {
id: appId,
secret: appSecret,
}
return fetch(urlJoin(authApiUrl, '/api/v1/application/authenticate'), {
method: 'post',
body: JSON.stringify(query),
headers: {
'Content-Type': 'application/json',
},
})
.then(responseData)
.then(({response, data}) => {
if(!response.ok) {
throw new ResponseError(response.status, data, `Failed to get token. Got status: ${response.status}`)
}
return data.token
})
.then(tokenInfoFromToken)
}))
return {
getToken: () => {
return getTokenInfo()
.then(tokenInfo => tokenInfo.token)
},
}
}
export default AppAuth