@piggly/fastify-chassis
Version:
An ESM/CommonJS toolkit to help you to do common operations in your back-end applications with Fastify and NodeJS.
38 lines • 1.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasicAuthMiddleware = void 0;
const events_1 = require("../events/index.js");
const errors_1 = require("../errors/index.js");
const utils_1 = require("../utils/index.js");
/**
* BasicAuthMiddleware is a middleware that checks if the request
* is authenticated using Basic Authentication.
*
* If request is not authenticated, it will:
* - Publish UnauthorizedAccessEvent.
* - Return UnauthorizedError.
*
* @param {Object} expected - The expected username and password.
* @param {string} expected.username - The expected username.
* @param {string} expected.password - The expected password.
* @returns The middleware function.
* @since 1.0.0
* @author Caique Araujo <caique@piggly.com.br>
*/
const BasicAuthMiddleware = (expected) => (request, reply, done) => {
const auth = (0, utils_1.getBasicToken)(request.headers);
if (auth === undefined) {
events_1.UnauthorizedAccessEvent.publish(request);
done(new errors_1.UnauthorizedError());
return;
}
const { password, username } = auth;
if (username !== expected.username || password !== expected.password) {
events_1.UnauthorizedAccessEvent.publish(request);
done(new errors_1.UnauthorizedError());
return;
}
done();
};
exports.BasicAuthMiddleware = BasicAuthMiddleware;
//# sourceMappingURL=BasicAuthMiddleware.js.map