/
index.js
executable file
·85 lines (57 loc) · 2.52 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
78
79
80
81
82
83
84
85
'use strict';
const Boom = require('@hapi/boom');
const Hoek = require('@hapi/hoek');
const internals = {};
exports.plugin = {
pkg: require('../package.json'),
requirements: {
hapi: '>=20.0.0'
},
register(server, options) {
server.auth.scheme('basic', internals.implementation);
}
};
internals.implementation = function (server, options) {
Hoek.assert(options, 'Missing basic auth strategy options');
Hoek.assert(typeof options.validate === 'function', 'options.validate must be a valid function in basic scheme');
const settings = Hoek.clone(options);
const scheme = {
authenticate: async function (request, h) {
const authorization = request.headers.authorization;
if (!authorization) {
throw Boom.unauthorized(null, 'Basic', settings.unauthorizedAttributes);
}
const parts = authorization.split(/\s+/);
if (parts[0].toLowerCase() !== 'basic') {
throw Boom.unauthorized(null, 'Basic', settings.unauthorizedAttributes);
}
if (parts.length !== 2) {
throw Boom.badRequest('Bad HTTP authentication header format', 'Basic');
}
const credentialsPart = Buffer.from(parts[1], 'base64').toString();
const sep = credentialsPart.indexOf(':');
if (sep === -1) {
throw Boom.badRequest('Bad header internal syntax', 'Basic');
}
const username = credentialsPart.slice(0, sep);
const password = credentialsPart.slice(sep + 1);
if (!username &&
!settings.allowEmptyUsername) {
throw Boom.unauthorized('HTTP authentication header missing username', 'Basic', settings.unauthorizedAttributes);
}
const { isValid, credentials, response } = await settings.validate(request, username, password, h);
if (response !== undefined) {
return h.response(response).takeover();
}
if (!isValid) {
return h.unauthenticated(Boom.unauthorized('Bad username or password', 'Basic', settings.unauthorizedAttributes), credentials ? { credentials } : null);
}
if (!credentials ||
typeof credentials !== 'object') {
throw Boom.badImplementation('Bad credentials object received for Basic auth validation');
}
return h.authenticated({ credentials });
}
};
return scheme;
};