Created
January 25, 2019 16:05
-
-
Save smashercosmo/ce34e12634465a3c26eda4493e06b33d to your computer and use it in GitHub Desktop.
This file contains 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
const route = require('koa-route') | |
const http = require('http') | |
const https = require('https') | |
const got = require('got') | |
const { | |
UMBRA_APS_CLIENT_SECRET, | |
UMBRA_API_EXTERNALURL, | |
UMBRA_AUTH_URI, | |
} = process.env | |
function pipeRes(res, proxyRes) { | |
res.writeHead(proxyRes.statusCode, proxyRes.headers) | |
proxyRes.pipe(res) | |
} | |
function makeProxyRequest({ url, method, token, headers }) { | |
const { protocol, hostname: host, pathname: path, search, port } = new URL( | |
url, | |
) | |
const { request } = protocol === 'https:' ? https : http | |
const proxyReqOpts = { | |
host, | |
path: path + search, | |
port, | |
method, | |
headers: Object.assign({}, headers, { | |
authorization: `Bearer ${token}`, | |
host, | |
}), | |
} | |
return request(proxyReqOpts) | |
} | |
const api = route.all('/api/(.*)', ctx => { | |
ctx.respond = false | |
const { session = {}, res, url, method, headers } = ctx | |
const { access_token: token = '', refresh_token: rtoken = '' } = session | |
const proxyUrl = new URL( | |
UMBRA_API_EXTERNALURL + url.replace(/^\/api/, '/api/v1'), | |
) | |
const proxyReq = makeProxyRequest({ url: proxyUrl, method, headers, token }) | |
proxyReq.on('response', async proxyRes => { | |
if (proxyRes.statusCode === 403 && rtoken) { | |
try { | |
const { body: authData } = await got(`${UMBRA_AUTH_URI}/token`, { | |
method: 'POST', | |
json: true, | |
body: { | |
grant_type: 'refresh_token', | |
refresh_token: rtoken, | |
client_id: 'AdminPortalServer', | |
client_secret: UMBRA_APS_CLIENT_SECRET, | |
}, | |
}) | |
Object.assign(ctx.session, authData) | |
await ctx.session.manuallyCommit() | |
const proxyReq2 = makeProxyRequest({ | |
url: proxyUrl, | |
method, | |
headers, | |
token: authData.access_token, | |
}) | |
proxyReq2.on('response', proxyRes2 => { | |
pipeRes(res, proxyRes2) | |
}) | |
proxyReq2.end() | |
} catch (e) { | |
pipeRes(res, proxyRes) | |
} | |
} else { | |
pipeRes(res, proxyRes) | |
} | |
}) | |
proxyReq.end() | |
}) | |
module.exports.api = api |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment