Created
July 11, 2017 18:56
-
-
Save vkarpov15/2d9a2654211c28488581f4ab10701de2 to your computer and use it in GitHub Desktop.
Consolidated API keys with express gateway
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 Keen = require('keen-js'); | |
const Mailgun = require('mailgun-js'); | |
const bodyParser = require('body-parser'); | |
const express = require('express'); | |
const app = express(); | |
app.use(bodyParser.json()); | |
const keys = { | |
// Top-level is the gateway's API keys, so user will send `token-1` to the | |
// gateway and get access to the underlying API keys without knowing what they | |
// are. | |
'token-1': { | |
keen: { | |
// Keys hidden so malicious users don't max out my KeenIO free tier :) | |
projectId: '...', | |
writeKey: '...' | |
}, | |
mailgun: { | |
apiKey: '...', | |
domain: '...' | |
} | |
}, | |
'token-2': { | |
keen: { | |
projectId: '...', | |
writeKey: '...' | |
}, | |
mailgun: { | |
apiKey: '...', | |
domain: '...' | |
} | |
} | |
}; | |
app.use(wrap(async function(req, res, next) { | |
if (!req.headers['authorization']) { | |
throw new Error('Must have auth header!'); | |
} | |
if (!keys[req.headers['authorization']]) { | |
throw new Error(`Invalid auth token ${req.headers['authorization']}`); | |
} | |
})); | |
app.use('/keen', keen()); | |
app.use('/mailgun', mailgun()); | |
app.listen(3000); | |
function keen() { | |
const router = express.Router(); | |
router.use(wrap(async function(req, res, next) { | |
req.client = new Keen(keys[req.headers['authorization']].keen); | |
})); | |
router.post('/track/:event', wrap(async function(req, res) { | |
await req.client.addEvent(req.params.event, req.body); | |
return { ok: 1 }; | |
})); | |
return router; | |
} | |
function mailgun() { | |
const router = express.Router(); | |
router.use(wrap(async function(req, res, next) { | |
req.client = new Mailgun(keys[req.headers['authorization']].mailgun); | |
})); | |
router.post('/send', wrap(async function(req, res) { | |
await req.client.messages().send(req.body); | |
return { ok: 1 }; | |
})); | |
return router; | |
} | |
function wrap(fn) { | |
return function(req, res, next) { | |
// Make sure to `.catch()` any errors and pass them along to the `next()` | |
// middleware in the chain, in this case the error handler. | |
fn(req). | |
then(returnVal => { | |
if (returnVal != null) { | |
return res.send(returnVal); | |
} | |
return next(); | |
}). | |
catch(next); | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment