UNPKG

@httpc/kit

Version:

httpc toolbox for building function-based API with minimal code and end-to-end type safety

47 lines (46 loc) 1.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BasicAuthenticationMiddleware = void 0; const server_1 = require("@httpc/server"); const di_1 = require("../di"); const context_1 = require("./context"); const services_1 = require("../services"); const logging_1 = require("../logging"); function BasicAuthenticationMiddleware(options) { const authenticate = options?.onAuthenticate || onAuthenticate; function hashToCredentials(hash) { let value; try { value = Buffer.from(hash, "base64").toString("utf8"); } catch (ex) { (0, logging_1.useLogger)().error("BasicAuthenticationMiddleware: Cannot parse authorization header", ex); return; } const [username, password] = value.split(":"); return { username, password, }; } return (0, server_1.PassthroughMiddleware)(async () => { const { request, user } = (0, server_1.useContext)(); if (!user) { const [schema, hash] = request.headers.authorization?.split(" ") || []; if (schema?.toUpperCase() === "BASIC") { const credentials = hashToCredentials(hash); if (!credentials || !credentials.username || !credentials.password) { throw new server_1.UnauthorizedError(); } (0, context_1.useAuthentication)(await authenticate(credentials) .catch((0, services_1.catchLogAndThrowUnauthorized)("BasicAuthenticationMiddleware"))); } } }); } exports.BasicAuthenticationMiddleware = BasicAuthenticationMiddleware; async function onAuthenticate(credentials) { const container = (0, di_1.useContainer)(); const auth = (0, di_1.RESOLVE)(container, "BasicAuthentication"); return await auth.authenticate(credentials); }