-
Notifications
You must be signed in to change notification settings - Fork 5
/
authPlugin.js
31 lines (27 loc) · 902 Bytes
/
authPlugin.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
const fp = require('fastify-plugin')
module.exports = fp(async (fastify, options) => {
fastify.decorateRequest('user', null);
fastify.decorateRequest('password', null);
fastify.addHook('preHandler', (request, reply, done) => {
const authRaw = request.headers.authorization;
if (authRaw) {
const encodedAuth = authRaw.split(' ').pop();
const buffer = Buffer.from(encodedAuth, "base64");
const [authMail, authPass] = buffer.toString("utf-8").split(':');
if (options.users.some((user) => user.mail === authMail && user.password === authPass)) {
request.user = authMail;
request.password = authPass;
} else {
return reply
.code(403)
.send(`Forbiden`);
}
} else {
return reply
.code(401)
.header("www-authenticate", "Basic")
.send(`Unauthorized`);
}
done();
});
})