UNPKG

@piggly/fastify-chassis

Version:

An ESM/CommonJS toolkit to help you to do common operations in your back-end applications with Fastify and NodeJS.

34 lines 1.26 kB
import { UnauthorizedAccessEvent } from '../events/index.js'; import { UnauthorizedError } from '../errors/index.js'; import { getBasicToken } from '../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> */ export const BasicAuthMiddleware = (expected) => (request, reply, done) => { const auth = getBasicToken(request.headers); if (auth === undefined) { UnauthorizedAccessEvent.publish(request); done(new UnauthorizedError()); return; } const { password, username } = auth; if (username !== expected.username || password !== expected.password) { UnauthorizedAccessEvent.publish(request); done(new UnauthorizedError()); return; } done(); }; //# sourceMappingURL=BasicAuthMiddleware.js.map