All files / spirit-common/lib/middleware proxy.js

100% Statements 22/22
90% Branches 9/10
100% Functions 5/5
100% Lines 21/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                  1x 7x 7x 3x 10x 10x   10x   10x         1x 4x 4x 3x 3x             3x       1x 7x 7x 7x 4x     7x 7x    
"use strict";
 
/*
 * Middleware for handling Forwarded and X-Forwarded-For
 * headers, currently it sets the request.ip to be the value
 * set by the above headers, Forwarded has priority if both exist
 *
 */
 
var forwarded = function forwarded(request) {
  var f = request.headers["forwarded"];
  if (f) {
    return f.split(";").reduce(function (o, kv) {
      var t = kv.split("=");
      Eif (!o[t[0]]) {
        // if key doesn't already exist
        o[t[0]] = t[1].split(",")[0];
      }
      return o;
    }, {});
  }
};
 
var x_forwarded = function x_forwarded(request) {
  var f = request.headers["x-forwarded-for"];
  if (f) {
    var v = f.split(",");
    var r = {
      for: v[0]
      //by: v[1],
      //proto: "http"
    };
    //const proto = request.headers["x-forwarded-proto"]
    //if (proto) r.proto = proto
    return r;
  }
};
 
module.exports = function (handler) {
  return function (request) {
    var v = forwarded(request);
    if (v === undefined) {
      v = x_forwarded(request);
    }
 
    if (v !== undefined) request.ip = v.for;
    return handler(request);
  };
};