UNPKG

@intuitionrobotics/thunderstorm

Version:
61 lines 2.33 kB
import {} from "express"; import { parse } from "url"; import {} from "./HttpServer.js"; import { ApiResponse } from "./server-api.js"; import { HttpMethod } from "../../../shared/types.js"; import {} from "../../utils/types.js"; /** * Build a `requireAuth(...scopes)` middleware from a consumer auth validator. * * export const requireAuth = makeRequireAuth((req, scopes, res) => * AccountModule.validateSession(req, scopes, headerSink(res))); * * The returned middleware populates `req.account` and works both per-route * (`router.post("/x", requireAuth("admin"), handler(fn))`) and at router-group * level (`router.use(requireAuth())`). */ export function makeRequireAuth(validator) { return (...scopes) => (req, res, next) => { Promise.resolve() .then(() => validator(req, scopes, res)) .then(account => { req.account = account; next(); }) .catch(next); }; } /** * Adapt a raw Express `res` to the `ApiResponse` a legacy `ServerApi_Middleware` * expects. ApiResponse is now a thin res-backed helper, so this hands the gate a * real, fully-functional one (setHeader/setHeaders for JWT refresh, redirect for * SAML, json/text/… all delegate to `res`). */ export const headerSink = (res) => new ApiResponse(res); /** * Wrap a legacy `ServerApi_Middleware` `(request, data, response, scopes) => ctx` * as Express middleware — so existing authz/proxy gates run at the route site * without rewriting their logic (no fresh security review). Any returned context * object is merged onto `req` (e.g. `req.account`); rejections flow to the * app-level terminal error handler via `next(err)`. * * router.post("/x", useMiddleware(RemoteProxy.Middleware), handler(fn)); */ export const useMiddleware = (mw, ...scopes) => (req, res, next) => { const data = { method: req.method.toLowerCase(), originalUrl: req.originalUrl, headers: req.headers, url: req.url, query: parse(req.url, true).query, body: req.body }; Promise.resolve(mw(req, data, headerSink(res), scopes)) .then(ctx => { if (ctx && typeof ctx === "object") Object.assign(req, ctx); next(); }) .catch(next); }; //# sourceMappingURL=requireAuth.js.map