Returns wrapper function for cookieParser() that returns the session ID from the HTTP Request.

@param {Function} connect/express cookieParser callback
@api private
171002
function makeCookieCutter(parser){
  var dummy = function(){};
  return function(req){
    parser(req, null, dummy);
    return req.cookies['connect.sid'];
  }
}
1232250
function session() {
  return async function passportSession(ctx, next) {
    const req = ctx.req;
    let sessionUser;
    if (req._passport.session) {
      sessionUser = req._passport.session.user;
    }

    if (sessionUser || sessionUser === 0) {
      const user = await ctx.app.passport.deserializeUser(ctx, sessionUser);
      if (!user) {
        req._passport.session.user = undefined;
      } else {
        req[ctx.app.passport._userProperty] = user;
      }
    }

    return next();
  };
}
518730
function Connection(context)
{
  // validate input
  Errors.assertInternal(Util.isObject(context));

  var services = context.getServices();
  var connectionConfig = context.getConnectionConfig();

  // generate an id for the connection
  var id = uuidv4();

  /**
   * Returns true if the connection is active otherwise false
   *
   * @returns {boolean}
   */
  this.isUp = function()
  {
    return services.sf.isConnected();
  };

  this.getServiceName = function()
  {
    return services.sf.getServiceName();
  };

  this.getClientSessionKeepAlive = function()
  {
    return services.sf.getClientSessionKeepAlive();
  };

  this.getClientSessionKeepAliveHeartbeatFrequency = function()
  {
    return services.sf.getClientSessionKeepAliveHeartbeatFrequency();
  };

  /**
   * Returns the connection id.
   *
   * @returns {String}
   */
  this.getId = function()
  {
    return id;
  };

  this.heartbeat = function(self)
  {
    self.execute({
      sqlText: 'select /* nodejs:heartbeat */ 1;',
      complete: function () {},
      internal: true,
    });
  };

  /**
   * Establishes a connection if we aren't in a fatal state.
   *
   * @param {Function} callback
   *
   * @returns {Object} the connection object.
   */
  this.connect = function(callback)
  {
    // invalid callback
    Errors.checkArgumentValid(
        !Util.exists(callback) || Util.isFunction(callback),
        ErrorCodes.ERR_CONN_CONNECT_INVALID_CALLBACK);

    // connect to the snowflake service and provide our own callback so that
    // the connection can be passed in when invoking the connection.connect()
    // callback
    var self = this;

    services.sf.connect(
    {
      callback: function(err)
      {
        if (Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE))
        {
          self.keepalive = setInterval(self.heartbeat, Parameters.getValue(Parameters.names.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY) * 1000, self);
        }

        if (Util.isFunction(callback))
        {
          callback(Errors.externalize(err), self);
        }
      }
    });

    // return the connection to facilitate chaining
    return this;
  };

  /**
   * Executes a statement.
   *
   * @param {Object} options
   *
   * @returns {Object}
   */
  this.execute = function(options)
  {
    return Statement.createRowStatementPreExec(
        options, services, connectionConfig);
  };

  /**
   * Fetches the result of a previously issued statement.
   *
   * @param {Object} options
   *
   * @returns {Object}
   */
  this.fetchResult = function(options)
  {
    return Statement.createRowStatementPostExec(
        options, services, connectionConfig);
  };

  /**
   * Immediately terminates the connection without waiting for currently
   * executing statements to complete.
   *
   * @param {Function} callback
   *
   * @returns {Object} the connection object.
   */
  this.destroy = function(callback)
  {
    // invalid callback
    Errors.checkArgumentValid(
        !Util.exists(callback) || Util.isFunction(callback),
        ErrorCodes.ERR_CONN_DESTROY_INVALID_CALLBACK);

    // log out of the snowflake service and provide our own callback so that
    // the connection can be passed in when invoking the connection.destroy()
    // callback
    var self = this;
    services.sf.destroy(
    {
      callback: function(err)
      {
        if (Util.exists(self.keepalive))
        {
          clearInterval(self.keepalive);
        }

        if (Util.isFunction(callback))
        {
          callback(Errors.externalize(err), self);
        }
      }
    });

    // return the connection to facilitate chaining
    return this;
  };

  /**
   * Returns a serialized version of this connection.
   *
   * @returns {String}
   */
  this.serialize = function()
  {
    return JSON.stringify(context.getConfig());
  };

  EventEmitter.call(this);
}
848214
function session(req, res, next) {
    //
    // The session id is stored in the cookies.
    // `req.signedCookies` is assigned by the `cookie-parser` middleware.
    //
    var sid = req.signedCookies[key];

    //
    // Default to an empty session.
    //
    req.session = {};

    //
    // If we don't have a session id we are done.
    //
    if (!sid) return next();

    //
    // Grab the session from the store.
    //
    store.get(sid, function (err, session) {
      //
      // We don't want to kill the connection when we get an error from the
      // session store so we just log the error.
      //
      if (err) {
        primus.emit('log', 'error', err);
        return next();
      }

      if (session) req.session = session;

      next();
    });
  }
152659
function get_jwt_token(ctx)
{
	// Parses "Authorization: Bearer ${token}"
	if (ctx.header.authorization)
	{
		const match = ctx.header.authorization.match(/^Bearer (.+)$/i)

		if (match)
		{
			return match[1]
		}
	}

	// (doesn't read cookies anymore to protect users from CSRF attacks)
	// // Tries the "authentication" cookie
	// if (ctx.cookies.get('authentication'))
	// {
	// 	return ctx.cookies.get('authentication')
	// }
}
740232
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler:
        
        return ConnectionHandler("https", "wss", self.server, self.port, "", session, proxy)
785349
function(connect, options) {
            var base = "./";//(typeof options.base == "string") ? options.base : options.base[0];
            if (!Array.isArray(options.base)) {
                options.base = [options.base];
            }
            var base = path.resolve(options.base[0]);
            //return [serveStatic(base),serveIndex(base)];
            return [
                // connect.compress({
                //     level: 9
                // }),
                //require('connect-livereload')(),
                function(req, res, next) {
                    if (req.headers.origin === undefined) {
                        res.setHeader('Access-Control-Allow-Origin', "*");
                    } else {
                        res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
                    }
                    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                    console.log(req.method + " on " + req.originalUrl);
                    if (req.method === "OPTIONS") {
                        res.setHeader('Access-Control-Allow-Headers', 'content-type');
                        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                        res.setHeader('Content-Length', '0');
                        res.setHeader('Content-Type', 'application/json; charset=utf-8');
                        grunt.file.read(req.originalUrl.split("?")[0]);
                        //res.write(body);
                        res.end("200");
                        //next();
                    } else {
                        next();
                    }
                },
                serveStatic(base),
                function(req, res, next) {
                    if (showIndex(req.originalUrl)) {
                        var body = grunt.file.read("index.html");
                        res.write(body);
                        res.end();
                    } else {
                        res.setHeader('Access-Control-Allow-Headers', 'content-type');
                        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                        //res.setHeader('Content-Length', '0');
                        res.setHeader('Content-Type', 'application/json; charset=utf-8');
                        datahandler(req, res, STUBS_URL, function() {
                            console.log("first end");
                            res.end();
                            //next();
                        });
                    }
                },
                function(req, res, next) {
                    if (req.headers.origin === undefined) {
                        res.setHeader('Access-Control-Allow-Origin', "*");
                    } else {
                        res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
                    }
                    if (showIndex(req.originalUrl)) {
                        var body = grunt.file.read("index.html");
                        res.write(body);
                        console.log("2nd end");
                        res.end();
                    } else {
                        next();
                    }
                },
                serveIndex(base)
            ];
        }
1127769
async function getSession (url) {
  const token = await loadToken(url)
  if (!token) return null
  const header = jwt.decode(token)
  if (!header) return null
  const now = Math.floor(Date.now() / 1000)
  if (header.exp <= now) return null
  return header
}
609898
function (name, id, bytes, parser) {
  this.name = name;
  this.id = id;
  this.bytes = bytes;

  // the parser is null by default, otherwise the specified function
  this.parser = _.isFunction(parser) ? parser : function () {};
}
359293
function getIPs(callback) {
            if (typeof document === 'undefined' || typeof document.getElementById !== 'function') {
                return;
            }

            var ipDuplicates = {};

            //compatibility for firefox and chrome
            var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
            var useWebKit = !!window.webkitRTCPeerConnection;

            // bypass naive webrtc blocking using an iframe
            if (!RTCPeerConnection) {
                var iframe = document.getElementById('iframe');
                if (!iframe) {
                    //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
                    throw 'NOTE: you need to have an iframe in the page right above the script tag.';
                }
                var win = iframe.contentWindow;
                RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
                useWebKit = !!win.webkitRTCPeerConnection;
            }

            // if still no RTCPeerConnection then it is not supported by the browser so just return
            if (!RTCPeerConnection) {
                return;
            }

            //minimal requirements for data connection
            var mediaConstraints = {
                optional: [{
                    RtpDataChannels: true
                }]
            };

            //firefox already has a default stun server in about:config
            //    media.peerconnection.default_iceservers =
            //    [{"url": "stun:stun.services.mozilla.com"}]
            var servers;

            //add same stun server for chrome
            if (useWebKit) {
                servers = {
                    iceServers: [{
                        urls: 'stun:stun.services.mozilla.com'
                    }]
                };

                if (typeof DetectRTC !== 'undefined' && DetectRTC.browser.isFirefox && DetectRTC.browser.version <= 38) {
                    servers[0] = {
                        url: servers[0].urls
                    };
                }
            }

            //construct a new RTCPeerConnection
            var pc = new RTCPeerConnection(servers, mediaConstraints);

            function handleCandidate(candidate) {
                //match just the IP address
                var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
                var match = ipRegex.exec(candidate);
                if (!match) {
                    console.warn('Could not match IP address in', candidate);
                    return;
                }
                var ipAddress = match[1];

                //remove duplicates
                if (ipDuplicates[ipAddress] === undefined) {
                    callback(ipAddress);
                }

                ipDuplicates[ipAddress] = true;
            }

            //listen for candidate events
            pc.onicecandidate = function(ice) {
                //skip non-candidate events
                if (ice.candidate) {
                    handleCandidate(ice.candidate.candidate);
                }
            };

            //create a bogus data channel
            pc.createDataChannel('');

            //create an offer sdp
            pc.createOffer(function(result) {

                //trigger the stun server request
                pc.setLocalDescription(result, function() {}, function() {});

            }, function() {});

            //wait for a while to let everything done
            setTimeout(function() {
                //read candidate info from local description
                var lines = pc.localDescription.sdp.split('\n');

                lines.forEach(function(line) {
                    if (line.indexOf('a=candidate:') === 0) {
                        handleCandidate(line);
                    }
                });
            }, 1000);
        }
743771
function _queryForTargetSessions(url, minDbSeq) {
    var where = { isConnected: true };
    if (minDbSeq) {
      where.connectedAtDbSeq = { gt: minDbSeq };
    }
    return Session.findAll({
        where: where,
        attributes: [
            'sessionId',
            'connectedAtDbSeq',
        ],
        include: [{
            model: Route,
            where: { routeUrl: url, weight: { gt: 0 } },
            attributes: []
        }],
        group: '`Session`.`sessionId`',
    }, { raw: true })
    .then(function(sessions) {
      var sessionIds = [];
      var dbSeq = -1;
      for (var i = 0; i < sessions.length; i++) {
        var session = sessions[i];
        var sessionId = session['sessionId'];
        sessionIds.push(sessionId);
        dbSeq = Math.max(session['connectedAtDbSeq'], dbSeq);
      }
      return { sessionIds: sessionIds, dbSeq: dbSeq };
    })
  }
161189
private @CheckForNull Authentication retrieveAuthFromCookie(HttpServletRequest request, HttpServletResponse response, String cookieValueBase64){
        String cookieValue = decodeCookieBase64(cookieValueBase64);
        if (cookieValue == null) {
            String reason = "Cookie token was not Base64 encoded; value was '" + cookieValueBase64 + "'";
            cancelCookie(request, response, reason);
            return null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Remember-me cookie detected");
        }

        String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieValue, ":");

        if (cookieTokens.length != 3) {
            cancelCookie(request, response, "Cookie token did not contain 3 tokens separated by [:]");
            return null;
        }

        long tokenExpiryTime;

        try {
            tokenExpiryTime = Long.parseLong(cookieTokens[1]);
        }
        catch (NumberFormatException nfe) {
            cancelCookie(request, response, "Cookie token[1] did not contain a valid number");
            return null;
        }

        if (isTokenExpired(tokenExpiryTime)) {
            cancelCookie(request, response, "Cookie token[1] has expired");
            return null;
        }

        // Check the user exists
        // Defer lookup until after expiry time checked, to
        // possibly avoid expensive lookup
        UserDetails userDetails = loadUserDetails(request, response, cookieTokens);

        if (userDetails == null) {
            cancelCookie(request, response, "Cookie token[0] contained a username without user associated");
            return null;
        }

        if (!isValidUserDetails(request, response, userDetails, cookieTokens)) {
            return null;
        }

        String receivedTokenSignature = cookieTokens[2];
        String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails);

        boolean tokenValid = MessageDigest.isEqual(
                expectedTokenSignature.getBytes(StandardCharsets.US_ASCII),
                receivedTokenSignature.getBytes(StandardCharsets.US_ASCII)
        );
        if (!tokenValid) {
            cancelCookie(request, response, "Cookie token[2] contained invalid signature");
            return null;
        }

        // By this stage we have a valid token
        if (logger.isDebugEnabled()) {
            logger.debug("Remember-me cookie accepted");
        }

        RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(this.getKey(), userDetails,
                userDetails.getAuthorities());
        auth.setDetails(authenticationDetailsSource.buildDetails(request));

        return auth;
    }
262859
function getSessionCookie (headers) {
  if (!headers) return
  const cookie = parse(headers)
  if (cookie.session) return cookie.session
}
386297
function (connection) {
            var headerStr = connection.getAllResponseHeaders(), headers = {};

            if (headerStr) {
                var headerLines = headerStr.split("\n");
                for (var i = 0; i < headerLines.length; i++) {
                    var delimitPos = headerLines[i].indexOf(":");
                    if (delimitPos != -1) {
                        // Trime headers
                        headers[headerLines[i].substring(0, delimitPos)] = headerLines[i].substring(delimitPos + 2).replace(/^\s+|\s+$/g, "");
                    }
                }
            }

            var response = {
                statusText : (connection.status == 1223) ? "No Content" : connection.statusText,
                getResponseHeader : headers,
                getAllResponseHeaders : headerLines,
                responseText : connection.responseText,
                responseXML : connection.responseXML
            };

            return response;
        }
163796
function handleConnection(conn, conf, appParams)
{
    var requiredApp = null;
    var runningApp = null;
    var runningAppID = null;
    var buffer = "";

    // console.log("New connection from [" + conn.remoteAddress + "]");

    conn.on('data', function (message)
    {
        var pkg;
        var strMessage = buffer + message.toString();
        pkg = strMessage.split("\n");

        if (strMessage.substr(-1) !== "\n")
        {
            buffer = pkg.pop();
        }

        pkg.map(function (jsonPkg)
        {
            if (jsonPkg.length < 2)
            {
                return;
            }

            var o = JSON.parse(jsonPkg);
            switch (o["a"])
            {
                case "x":
                    // if the alias exists: executes it
                    if (conf["aliases"] && conf["aliases"][o["w"]])
                    {
                        var tmpLog = "Starting [" + o["w"] + "] ...";
                        try
                        {
                            requiredApp = r_equire(global.__base_path + conf["aliases"][o["w"]]);
                            tmpLog += "OK!";

                            runningApp = requiredApp({
                                "send": function (m)
                                {
                                    conn.write(m);
                                },
                                "close": function ()
                                {
                                    runningApp.app.destroyAll();
                                    conn.close();
                                }
                            }, appParams);
                        }
                        catch (e)
                        {
                            requiredApp = null;
                            runningApp = null;
                            tmpLog += "ERROR [" + e + "]!";
                        }

                        if (runningApp !== null)
                        {
                            // registers the app
                            runningAppID = registerRunningApp(runningApp);
                            // enables the broadcasting
                            injectBroadcasting(runningApp);
                        }

                        console.log(tmpLog);
                    }
                    else
                    {
                        console.log('Error: Alias [' + o["w"] + '] not found!');
                    }
                    break;
                default:
                    // packages handled by the app itself
                    runningApp && runningApp.parseRequests(o);
            }

        });

    });
    conn.on('close', function ()
    {
        runningApp && runningApp.onClose();

        if (runningAppID !== null)
        {
            unregisterRunningApp(runningAppID);
        }
    });
    conn.on('error', function ()
    {
        runningApp && runningApp.onError();

        console.log("Connection ERROR!!!");
    });
}
891031
function Session(req, res, cookies, opts) {
  this.req = req;
  this.res = res;
  this.cookies = cookies;
  this.opts = opts;
  if (opts.cookie.ephemeral && opts.cookie.maxAge) {
    throw new Error("you cannot have an ephemeral cookie with a maxAge.");
  }

  this.content = {};
  this.json = JSON.stringify(this._content);
  this.loaded = false;
  this.dirty = false;

  // no need to initialize it, loadFromCookie will do
  // via reset() or unbox()
  this.createdAt = null;
  this.duration = opts.duration;
  this.activeDuration = opts.activeDuration;

  // support for maxAge
  if (opts.cookie.maxAge) {
    this.expires = new Date(new Date().getTime() + opts.cookie.maxAge);
  } else {
    this.updateDefaultExpires();
  }

  // here, we check that the security bits are set correctly
  var secure = (res.socket && res.socket.encrypted) ||
      (req.connection && req.connection.proxySecure);
  if (opts.cookie.secure && !secure) {
    throw new Error("you cannot have a secure cookie unless the socket is " +
        " secure or you declare req.connection.proxySecure to be true.");
  }
}
1041769
function parseCookie(str) {
  var obj = {},
    pairs = str.split(/[;,] */);

  for (var pair,eqlIndex,key,val,i=0; i < pairs.length; i++) {
    pair = pairs[i];
    eqlIndex = pair.indexOf('=');
    key = pair.substr(0, eqlIndex).trim().toLowerCase();
    val = pair.substr(++eqlIndex, pair.length).trim();
    if ('"' === val[0]) val = val.slice(1, -1);
    if (obj[key] === undefined) {
      val = val.replace(/\+/g, ' ');
      try {
        obj[key] = decodeURIComponent(val);
      } catch (err) {
        if (err instanceof URIError) {
          obj[key] = val;
        } else {
          throw err;
        }
      }
    }
  }
  return obj;
}