-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathexercise-micro-compose.js
52 lines (41 loc) · 1.4 KB
/
exercise-micro-compose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const micro = require('micro');
const {sendError, createError} = micro;
const compose = (...fns) => (...args) =>
fns.reduceRight((acc, curr) => curr(acc), ...args);
const responseText = `
Hello authenticated micro!
Run this with node example-4-api-key-auth.js
## Test requests
Try the following:
- curl http://localhost:3000 -H 'Authorization: ApiKey api-key-1' -I which should 200</li>
- curl http://localhost:3000 -H 'Authorization: ApiKey bad-key' -I which should 401</li>
- curl http://localhost:3000 -H 'Authorization: Bearer bearer-token' -I which should 401</li>
- curl http://localhost:3000 -I which should 401
`;
const handler = () => responseText;
const ALLOWED_API_KEYS = new Set(['api-key-1', 'key-2-for-api']);
const authenticate = fn => async (req, res) => {
const {authorization} = req.headers;
if (authorization && authorization.startsWith('ApiKey')) {
const apiKey = authorization.replace('ApiKey', '').trim();
if (ALLOWED_API_KEYS.has(apiKey)) {
return fn(req, res);
}
}
return sendError(req, res, createError(401, `Unauthorized: ${responseText}`));
};
const timer = fn => async (req, res) => {
console.time('request');
const value = await fn(req, res);
console.timeEnd('request');
return value;
};
const server = compose(
micro,
timer,
authenticate,
handler
)();
server.listen(3000, () => {
console.log('Listening on http://localhost:3000');
});