This repository has been archived by the owner on Oct 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
77 lines (57 loc) · 1.77 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
var Boom = require('boom');
const unauthorizedMessageText = 'The correct API Key was not provided by the client';
function loadApiKeysFromEnvironmentVariables() {
var keys = [];
var curr;
while (curr = process.env['API_KEY_' + (keys.length + 1)]) {
keys.push(curr);
}
return keys;
}
function createFetchUserApiKey() {
return function fetchUserSuppliedUserApiKey(request) {
return request.headers["api-key"] || request.query["api-key"];
}
}
function createDefaultShouldApplyApiKeyFiltering() {
return function shouldApplyApiKeyFiltering(request) {
var tags = request.route.settings.tags;
return tags && tags.indexOf('api') >= 0;
}
}
function createInterceptor(options) {
var secrets = (options && options.secrets) || loadApiKeysFromEnvironmentVariables();
var fetchUserSuppliedSecret = options.fetchUserApiKey || createFetchUserApiKey();
var shouldApplyFilter = options.shouldApplyApiFilter || createDefaultShouldApplyApiKeyFiltering();
return function (request, reply) {
if (!shouldApplyFilter(request)) {
return reply.continue();
}
var isLocalHost = request.info.hostname.toLowerCase() === 'localhost';
if (isLocalHost && (!secrets || !secrets.length)) {
return reply.continue();
}
var apiKey = fetchUserSuppliedSecret(request);
if (secrets && secrets.indexOf(apiKey) >= 0) {
return reply.continue();
}
return reply(Boom.unauthorized(unauthorizedMessageText));
}
}
const plugin = {
register: function (server, options, next) {
server.ext('onPreAuth', createInterceptor(options));
next();
}
};
plugin.register.attributes = {
name: "hapi-api-secret-key",
version: '1.1.0'
};
module.exports = {
plugin,
messages: {
unauthorized: unauthorizedMessageText
}
};