UNPKG

@t-om/passport-headerapikey

Version:

Api key authentication strategy for Passport, which only handles headers (not body fields).

79 lines (78 loc) 3.09 kB
"use strict"; /** * Creator: Christian Hotz * Company: hydra newmedia GmbH * Date: 27.06.16 * * Copyright hydra newmedia GmbH */ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; exports.__esModule = true; exports.Strategy = void 0; var passport_strategy_1 = require("passport-strategy"); var BadRequestError_1 = require("./errors/BadRequestError"); ; var Strategy = /** @class */ (function (_super) { __extends(Strategy, _super); function Strategy(options, passReqToCallback, verify) { var _this = _super.call(this) || this; _this.options = options || { header: "X-Api-Key" }; if (!_this.options.header) _this.options.header = "X-Api-Key"; if (!_this.options.prefix) _this.options.prefix = ""; if (!_this.options.name) _this.options.name = "headerapikey"; _this.options.header = _this.options.header.toLowerCase(); _this.name = _this.options.name; _this.verify = verify; _this.passReqToCallback = passReqToCallback || false; return _this; } ; Strategy.prototype.authenticate = function (req) { var _this = this; var _a = this.options, header = _a.header, prefix = _a.prefix; var apiKey = req.headers[header]; if (!apiKey) return this.fail(new BadRequestError_1.BadRequestError("Missing API Key"), null); if (apiKey.startsWith(prefix)) apiKey = apiKey.replace(new RegExp('^' + prefix), ''); else return this.fail(new BadRequestError_1.BadRequestError("Invalid API Key prefix, " + header + " header should start with \"" + prefix + "\""), null); var verified = function (err, user, info) { if (err) return _this.error(err); if (!user) return _this.fail(info, null); _this.success(user, info); }; var optionalCallbackParams = []; if (this.passReqToCallback) optionalCallbackParams.push(req); this.verify.apply(this, __spreadArrays([apiKey, verified], optionalCallbackParams)); }; ; return Strategy; }(passport_strategy_1.Strategy)); exports.Strategy = Strategy; ;