@httpc/kit
Version:
httpc toolbox for building function-based API with minimal code and end-to-end type safety
30 lines (29 loc) • 1.32 kB
JavaScript
import { container } from "tsyringe";
import { PassthroughMiddleware, useContext } from "@httpc/server";
import { KEY, RESOLVE, useContainer } from "../di";
import { useAuthentication } from "./context";
import { catchLogAndThrowUnauthorized } from "../services";
export function AuthenticationBearerMiddleware(options) {
const authenticate = options?.onAuthenticate || onAuthenticate;
if (options?.jwtSecret && !container.isRegistered(KEY("ENV", "JWT_SECRET"), true)) {
container.registerInstance(KEY("ENV", "JWT_SECRET"), options.jwtSecret);
}
if (options?.onDecode) {
container.registerInstance(KEY("ENV", "JWT_DECODE"), options.onDecode);
}
return PassthroughMiddleware(async () => {
const { request, user } = useContext();
if (!user) {
const [schema, token] = request.headers.authorization?.split(" ") || [];
if (schema?.toUpperCase() === "BEARER") {
useAuthentication(await authenticate(token)
.catch(catchLogAndThrowUnauthorized("BearerMiddleware")));
}
}
});
}
async function onAuthenticate(token) {
const container = useContainer();
const auth = RESOLVE(container, "BearerAuthentication");
return await auth.authenticate(token);
}