UNPKG

@senacor/azure-function-middleware

Version:

Middleware for azure functions to handle authentication, authorization, error handling and logging

37 lines (36 loc) 2.32 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../error"); const defaultHeaderValidation = (headers) => !!headers.get('x-ms-client-principal-id'); const defaultErrorResponseBody = 'No sophisticated credentials provided'; exports.default = (opts) => { var _a, _b, _c; const validateUsingHeaderFn = (_a = opts === null || opts === void 0 ? void 0 : opts.validateUsingHeaderFn) !== null && _a !== void 0 ? _a : defaultHeaderValidation; const errorResponseBody = (_b = opts === null || opts === void 0 ? void 0 : opts.errorResponseBody) !== null && _b !== void 0 ? _b : defaultErrorResponseBody; const skipIfResultIsFaulty = (_c = opts === null || opts === void 0 ? void 0 : opts.skipIfResultIsFaulty) !== null && _c !== void 0 ? _c : true; return (req, context, result) => __awaiter(void 0, void 0, void 0, function* () { if (skipIfResultIsFaulty && result.$failed) { context.info('Skipping header-authentication because the result is faulty.'); return; } context.info('Executing header authentication.'); const validationResult = yield validateUsingHeaderFn(req.headers); if (validationResult) { context.info('Header authentication was successful.'); return; } else { context.info('Header authentication was NOT successful.'); throw new error_1.ApplicationError('Authentication error', 403, errorResponseBody !== null && errorResponseBody !== void 0 ? errorResponseBody : 'No sophisticated credentials provided'); } }); };