var session = require('cookie-session')({ secret: 'secret' }); 
### configure

Defines standard routes for the HTTP server

@param {object} options The object containing the custom settings
426857
function configure(app, servernode) {
    var rootDir, publicDir;
    var resourceManager;
    var basepath;

    rootDir = servernode.rootDir;
    publicDir = path.join(rootDir, 'public');
    basepath = servernode.basepath || '';
    resourceManager = servernode.resourceManager;

    app.set('views', path.resolve(rootDir, 'views'));
    app.set('view engine', 'jade');
    app.set('view options', {layout: false});


    if (process.env.NODE_ENV === 'development') {
        app.use(express.static(publicDir));
        app.use(errorHandler());
    }
    else {
        app.use(express.static(publicDir, { maxAge: 3600000 }));
    }

    app.disable('x-powered-by');
    app.enable("jsonp callback");

    app.use(cookieParser());
    // app.use(bodyParser());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    function sendFromPublic(type, req, res, headers) {
        var file, mimeType, charset, filePath;
        file = req.params[0];
        if (!file) return;

        // Build path in `public/`.
        file = path.join(type, file);

        // Build headers.
        if (!headers) {
            mimeType = mime.lookup(file);
            charset = mime.charsets.lookup(mimeType);
            headers = { 'Content-Type': mimeType };
            if (charset) headers.charset = charset;
        }

        // If it is not text, it was not cached.
        if (headers['Content-Type'].substring(0,4) !== 'text') {
            filePath = path.resolve(publicDir, file);
            res.sendFile(filePath);
            return;
        }

        // Already found in `public/` and cached.
        resourceManager.getFromPublic('/', file, function(cachedFile) {

            // File found in public (cached or loaded).
            if (cachedFile) {
                res.set(headers);
                res.status(200).send(cachedFile);
            }
            else {
                // Send 404.
                res.status(404).send('File not found.');
            }
        });
    }

    app.get(basepath + '/javascripts/*', function(req, res) {
        sendFromPublic('javascripts', req, res, {
            'Content-Type': 'text/javascript',
            'charset': 'utf-8'
        });
    });

    app.get(basepath + '/sounds/*', function(req, res) {
        sendFromPublic('sounds', req, res, {
            'Content-Type': 'sound/ogg'
        });
    });

    app.get(basepath + '/stylesheets/*', function(req, res) {
        sendFromPublic('stylesheets', req, res, {
            'Content-Type': 'text/css',
            'charset': 'utf-8'
        });
    });


    app.get(basepath + '/images/*', function(req, res) {
        sendFromPublic('images', req, res, {
            'Content-Type': 'image/png'
        });
    });

    app.get(basepath + '/pages/*', function(req, res) {
        sendFromPublic('pages', req, res, {
            'Content-Type': 'text/html',
            'charset': 'utf-8'
        });
    });

    app.get(basepath + '/lib/*', function(req, res) {
        sendFromPublic('lib', req, res);
    });

    app.get(basepath + '/', function(req, res, next) {
        var q, games = [];

        var gamesObj;
        var i, j;
        var colors;
        var name, card, color, filteredGames;

        if (servernode.defaultChannel) {
            next();
            return;
        }

        if (J.isEmpty(req.query)) {
            if (servernode.homePage === false ||
                servernode.homePage.enabled === false) {

                res.render('index_simple', {
                    title: 'Yay! nodeGame server is running.'
                });
            }
            else {
                colors = servernode.homePage.colors;
                gamesObj = servernode.info.games;
                listOfGames = J.keys(gamesObj);
                // Remove aliases.
                filteredGames = listOfGames.filter(function(name) {
                    return (!gamesObj[name].errored &&
                            (!gamesObj[name].alias ||
                             gamesObj[name].alias.indexOf(name) === -1));
                });
                if (J.isArray(servernode.homePage.cardsOrder)) {
                    filteredGames =
                        servernode.homePage.cardsOrder.filter(function(name) {
                            if (filteredGames.indexOf(name) !== -1) return true;
                            servernode.logger.error('homePage.cardsOrder ' +
                                                    'game not found: ' + name);
                        });
                }
                else {
                    filteredGames.sort();
                }
                i = 0;
                for (j = 0; j < filteredGames.length; j++) {
                    name = filteredGames[j];
                    if (i >= colors.length) i = 0;
                    color = colors[i];
                    // Mixout name and description from package.json
                    // if not in card, or if no card is defined.
                    card = J.mixout(gamesObj[name].info.card || {}, {
                        name: name.charAt(0).toUpperCase() + name.slice(1),
                        description: gamesObj[name].info.description
                    });
                    games.push({
                        name: card.name,
                        color: color,
                        url: card.url,
                        description: card.description,
                        publication: card.publication,
                        wiki: card.wiki,
                        icon: card.icon
                    });
                    i++;
                }
                res.render('homepage', {
                    title: servernode.homePage.title,
                    games: games,
                    nodeGameCard: servernode.homePage.nodeGameCard,
                    footerContent: servernode.homePage.footerContent,
                    logo: servernode.homePage.logo
                });
            }

            return;
        }

        if (servernode.enableInfoQuery) {

            q = req.query.q;
            if (!q) {
                res.status(400).send('Query must start with q=XXX');
                return;
            }

            switch(q) {
            case 'info':
                //console.log(servernode.info);
                res.status(200).send(servernode.info);
                break;

            case 'channels':
                //console.log(servernode.info);
                res.status(200).send(servernode.info.channels);
                break;

            case 'games':
                //console.log(servernode.info);
                res.status(200).send(servernode.info.games);
                break;
            default:
                res.status(400).send('Unknown query received.');
            }
        }
        else {
            res.status(403).end();
        }
    });

    return true;
}
217707
protected function setOptions($options)
	{
		// Set name
		if (isset($options['name']))
		{
			session_name(md5($options['name']));
		}

		// Set id
		if (isset($options['id']))
		{
			session_id($options['id']);
		}

		// Set expire time
		if (isset($options['expire']))
		{
			$this->expire = $options['expire'];
		}

		// Get security options
		if (isset($options['security']))
		{
			$this->security = explode(',', $options['security']);
		}

		if (isset($options['force_ssl']))
		{
			$this->force_ssl = (bool) $options['force_ssl'];
		}

		if (isset($options['cookie_domain']))
		{
			$this->cookie_domain = (string) $options['cookie_domain'];
		}

		if (isset($options['cookie_path']))
		{
			$this->cookie_path = (string) $options['cookie_path'];
		}

		// Sync the session maxlifetime
		ini_set('session.gc_maxlifetime', $this->expire);

		return true;
	}
969029
function (options) {
    var ignore = options.ignore || [],
        csrf = csurf(options),
        always = {OPTIONS: 1, GET: 1, HEAD: 1};

    return function (req, res, next) {
      if (always[req.method]) {
        return csrf(req, res, next);
      } else {
        var url = parse(req.url);
        var skipCSRF = false;
        ignore.forEach(function(matcher) {
          if (typeof matcher === 'string') {
            if (matcher === url.pathname) {
              skipCSRF = true;
            }
          } else {
            // regular expression matcher
            if (url.pathname.match(matcher)) {
              skipCSRF = true;
            }
          }
        });

        if (skipCSRF) {
          next();
        } else {
          return csrf(req, res, next);
        }
      }
    };
  }
708955
function(options) {
  if (typeof options !== 'object') {
    options = {};
  }
  this._options = options = _.defaults(options, {
    trustedProxies: ['127.0.0.1'],
    clickjacking: 'deny',
    noMimeSniffing: true,
    log: console.log,
    maxInputSize: 1024 * 1024
  });

  this._app = connect();

  this._app.use(function(req, res, next) {
    // Set body to stream if posting data not yet processed by the bodyparser.
    if (['GET', 'HEAD'].indexOf(req.method) < 0 && typeof req.headers['content-type'] === 'string') {
      req.body = new Readable();
      req.body.wrap(req);
      // Parse the boundary for multipart data.
      var boundary = req.headers['content-type'].match(/^multipart\/.+?(?:; boundary=(?:(?:"(.+)")|(?:([^\s]+))))$/i);
      req.multipartBoundary = boundary ? boundary[1] || boundary[2] : null;
    }
    next();
  });
  this._app.use(bodyParser.urlencoded({extended: false}));
  this._app.use(bodyParser.json({limit: options.maxInputSize}));
  this._app.use(bodyParser.text({type: 'text/*', limit: this._options.maxInputSize}));
  this._app.use(cookieParser());
  this._app.use(compression());

  this.phases = [
    {name: 'initialize', concurrent: true, error: false, errorStatus: 500},
    {name: 'authentication', concurrent: false, error: false, errorStatus: 401},
    {name: 'authorisation', concurrent: false, error: false, errorStatus: 403},
    {name: 'prevalidation', concurrent: true, error: false, errorStatus: 400},
    {name: 'preprocess', concurrent: false, error: false, errorStatus: 500},
    {name: 'postvalidation', concurrent: true, error: false, errorStatus: 400},
    {name: 'process', concurrent: false, error: false, errorStatus: 500},
    {name: 'postprocess', concurrent: false, error: false, errorStatus: 500},
    {name: '_send', concurrent: false, error: false},
    {name: 'after', concurrent: true, error: false},
    {name: 'error', concurrent: false, error: true, errorStatus: 500},
    {name: '_senderror', concurrent: false, error: true},
    {name: 'aftererror', concurrent: true, error: true}
  ];
  this.addRegisterFunctions(this);

  this._types = {
    'alpha': '[a-z]+',
    'alphanum': '[a-z0-9]+',
    'bool': '(?:1|0|true|false)',
    'float': '\\-?[0-9\\.]+',
    'int': '[1-9][0-9]*',
    'path': '.+?',
    'signed': '\\-?[0-9]+',
    'string': '[^\\/]+',
    'unsigned': '[0-9]+',
    'uuid': '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
  };

  this._send(sendHandler);
  this.error(errorHandler);
  this._senderror(sendHandler);

  var log = this._options.log;
  if (typeof log === 'function') {
    this.after(function() { logHandler.apply(this, [log]); });
    this.aftererror(function() { logHandler.apply(this, [log]); });
  }
}
1275860
function createSession(config, cb) {
  checkOpts(config, cb)

  cb = utils.callOnce(cb)

  var url = config.url
  var key = config.key

  config = {
    url: url,
    key: key
  }

  session.createSession(config, cb)
}
748130
function Config(options) {
  var useConfig;

  options = options || {};

  this.cache = {};
  this.parser = options.parser;

  this.useNplintrc = (options.useNplintrc !== false);
  this.useNplintignore = (options.useNplintignore !== false);

  useConfig = options.configFile;
  this.options = options;

  if (useConfig) {
    if (isResolvable(useConfig) || isResolvable('nplint-config-' + useConfig) || useConfig.charAt(0) === '@') {
      this.useSpecificConfig = loadConfig(useConfig);
    } else {
      this.useSpecificConfig = loadConfig(path.resolve(process.cwd(), useConfig));
    }
  }
}
362484
function shouldSetCookie(req) {
      // cannot set cookie without a session ID
      if (typeof req.sessionID !== 'string') {
        return false;
      }

      return cookieId !== req.sessionID
        ? saveUninitializedSession || isModified(req.session)
        : rollingSessions || req.session.cookie.expires != null && isModified(req.session);
    }
1353707
@Override
    void authenticate(Map<String, Object> options) {
        final String current = (String) options.get(AbstractReplicatorConfiguration.REPLICATOR_OPTION_COOKIES);
        final StringBuffer cookieStr = current != null ? new StringBuffer(current) : new StringBuffer();

        if (cookieStr.length() > 0) { cookieStr.append("; "); }
        cookieStr.append(String.format(Locale.ENGLISH, "%s=%s", cookieName, sessionID));

        options.put(AbstractReplicatorConfiguration.REPLICATOR_OPTION_COOKIES, cookieStr.toString());
    }
157767
function auth(app, config) {
  /* Ensure authorizer */
  if (is.not.function(config.authorizer)) {
    throw new Error(ERR_AUTHORIZER);
  }

  /* Check debug type */
  if (is.function(config.debug)) {
    debug = config.debug;
  } else if (config.debug) {
    debug = console.log.bind(console);
  }

  /* Set the authorized property in 'req.session' */
  app.use((req, res, next) => {
    req.session.authorized = config.authorizer(req);
    next();
  });

  /* Set authorization rules for each route */
  config.routes.forEach((route) => {
    route = normalize(route);

    var router = app.route(route.path);

    if (is.array(route.method) && route.method.length) {
      route.method.forEach((method) => {
        logAssignment(method, route.path, route.allows);
        router[method](generate(route.allows), authorize);
      });
    } else if (is.string(route.method)) {
      logAssignment(route.method, route.path, route.allows);
      router[route.method](generate(route.allows), authorize);
    } else {
      logAssignment(ALL, route.path, route.allows);
      router.all(generate(route.allows), authorize);
    }
  });
}
1044230
def set_cookie(self, cookie):
		'''
		
		'''

		# Function path: Network.setCookie
		# Domain: Network
		# Method name: setCookie
		# WARNING: This function is marked 'Experimental'!
		# Parameters:
		#         Required arguments:
		#                 'url' (type: string) -> The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie.
		#                 'name' (type: string) -> The name of the cookie.
		#                 'value' (type: string) -> The value of the cookie.
		#         Optional arguments:
		#                 'domain' (type: string) -> If omitted, the cookie becomes a host-only cookie.
		#                 'path' (type: string) -> Defaults to the path portion of the url parameter.
		#                 'secure' (type: boolean) -> Defaults ot false.
		#                 'httpOnly' (type: boolean) -> Defaults to false.
		#                 'sameSite' (type: CookieSameSite) -> Defaults to browser default behavior.
		#                 'expirationDate' (type: Timestamp) -> If omitted, the cookie becomes a session cookie.
		# Returns:
		#         'success' (type: boolean) -> True if successfully set cookie.

		# Description: Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.

		assert isinstance(cookie, http.cookiejar.Cookie), 'The value passed to `set_cookie` must be an instance of http.cookiejar.Cookie().' + \
			' Passed: %s ("%s").' % (type(cookie), cookie)

		# Yeah, the cookielib stores this attribute as a string, despite it containing a
		# boolean value. No idea why.
		is_http_only = str(cookie.get_nonstandard_attr('httponly', 'False')).lower() == "true"


		# I'm unclear what the "url" field is actually for. A cookie only needs the domain and
		# path component to be fully defined. Considering the API apparently allows the domain and
		# path parameters to be unset, I think it forms a partially redundant, with some
		# strange interactions with mode-changing between host-only and more general
		# cookies depending on what's set where.
		# Anyways, given we need a URL for the API to work properly, we produce a fake
		# host url by building it out of the relevant cookie properties.
		fake_url = urllib.parse.urlunsplit((
				"http" if is_http_only else "https",  # Scheme
				cookie.domain,                        # netloc
				cookie.path,                          # path
				'',                                   # query
				'',                                   # fragment
			))

		params = {
				'url'      : fake_url,

				'name'     : cookie.name,
				'value'    : cookie.value if cookie.value else "",
				'domain'   : cookie.domain,
				'path'     : cookie.path,
				'secure'   : cookie.secure,
				'expires'  : float(cookie.expires) if cookie.expires else float(2**32),

				'httpOnly' : is_http_only,

				# The "sameSite" flag appears to be a chromium-only extension for controlling
				# cookie sending in non-first-party contexts. See:
				# https://bugs.chromium.org/p/chromium/issues/detail?id=459154
				# Anyways, we just use the default here, whatever that is.
				# sameSite       = cookie.xxx
			}

		ret = self.Network_setCookie(**params)

		return ret
253850
function logIn(config, location, options) {
    return Q.Promise(function (resolve, reject) {
      if (isLoggedIn) {
        setLocation(location, options).then(resolve);
        return;
      }
      api.init(config.username, config.password, locWrap(location), config.provider, function (err) {
        if (err) {
          return reject(err);
        }
        isLoggedIn = true;
        resolve();
      });
    });
  }
804010
function configureApp(trinte, callback) {
    var app = trinte.app;
    var root = trinte.root;

    envConf(app, express);

    app.use(multiparty({
        uploadDir: config.parser.uploadDir,
        keepExtensions: config.parser.keepExtensions,
        encoding: config.parser.encoding
    }));
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({extended: true}));
    // parse application/json
    app.use(bodyParser.json());
    // parse application/vnd.api+json as json
    app.use(bodyParser.json({type: 'application/vnd.api+json'}));
    app.use(methodOverride('X-HTTP-Method'));              // Microsoft
    app.use(methodOverride('X-HTTP-Method-Override'));     // Google/GData
    app.use(methodOverride('X-Method-Override'));          // IBM
    app.use(methodOverride('_method')); 	               // simulate DELETE and PUT
    app.use(methodOverride(function (req) {
        if (req.body && typeof req.body === 'object' && '_method' in req.body) {
            // look in urlencoded POST bodies and delete it
            var method = req.body._method;
            delete req.body._method;
            return method;
        }
    }));
    // Accepts json response
    app.use(function (req, res, next) {
        if (req.accepts('json') !== undefined) {
            req.params.format = 'json';
        }
        next();
    });
    app.use(cookieParser(config.session.secret));
    session(app, express);
    // Accepts json response
    app.use(function (req, res, next) {
        if (req.query.language !== undefined || req.query.lang !== undefined) {
            if (req.session) {
                req.session.language = req.query.language || req.query.lang;
            }
        }
        if (req.session && !req.session.language) {
            req.session.language = config.language;
        }
        next();
    });
    // Before router to enable dynamic routing
    app.use(express.static(root + '/public'));
    // Setup ejs views as default, with .ejs as the extension
    app.set('port', process.env.PORT || config.port);
    app.set('views', root + '/app/views');
    app.engine('ejs', engine);
    app.set('view engine', 'ejs');
    app.set('view options', {
        complexNames: true
    });
    app.use(helper.init(utils));
    app.use(utils.XMLResponse());
    app.use(utils.RSSResponse());
    app.use(utils.ErrorResponse());
    app.use(utils.fixCSRF());
    app.use(flash());
    app.use(locales.translator());
    middleware(app, express);

    // Initialize routes params
    require(root + '/config/params')(utils, app);
    callback(app);
}
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.");
  }
}
1211609
function initWebServer(settings) {

    let server = {
        app:       null,
        server:    null,
        io:        null,
        settings:  settings
    };
    adapter.subscribeForeignObjects('system.config');

    settings.ttl = parseInt(settings.ttl, 10) || 3600;
    if (!settings.whiteListEnabled && settings.whiteListSettings) delete settings.whiteListSettings;

    settings.defaultUser = settings.defaultUser || 'system.user.admin';
    if (!settings.defaultUser.match(/^system\.user\./)) settings.defaultUser = 'system.user.' + settings.defaultUser;

    if (settings.port) {
        if (settings.secure) {
            if (!settings.certificates) {
                return null;
            }
        }
        server.app = express();

        server.app.disable('x-powered-by');
        // enable use of i-frames together with HTTPS
        server.app.get('/*', (req, res, next) => {
            res.header('X-Frame-Options' , 'SAMEORIGIN');
            next(); // http://expressjs.com/guide.html#passing-route control
        });

        if (settings.auth) {

            initAuth(server, settings);

            let autoLogonOrRedirectToLogin = (req, res, next, redirect) => {
                if (!settings.whiteListSettings) {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else
					if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
                        const parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						// if request for web/lib, ignore it, because no redirect information
						if (parts[0] === 'lib') return res.status(200).send('');
						return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
				adapter.log.silly('whiteListIp ' + whiteListIp);
                if (!whiteListIp || settings.whiteListSettings[whiteListIp].user === 'auth') {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
						let parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						if (parts[0] === 'lib') return res.status(200).send('');
                        return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
					return next(err);
                });
            };

            server.app.post('/login', (req, res, next) => {
                let redirect = '/';
                let parts;
                if (req.body.origin) {
                    parts = req.body.origin.split('=');
                    if (parts[1]) redirect = decodeURIComponent(parts[1]);
                }
                if (req.body && req.body.username && settings.addUserName && redirect.indexOf('?') === -1) {
                    parts = redirect.split('#');
                    parts[0] += '?' + req.body.username;
                    redirect = parts.join('#');
                }
                passport.authenticate('local', {
                    successRedirect: redirect,
                    failureRedirect: '/login/index.html' + req.body.origin + (req.body.origin ? '&error' : '?error'),
                    failureFlash: 'Invalid username or password.'
                })(req, res, next);
            });

            server.app.get('/logout', (req, res) => {
                req.logout();
                res.redirect('/login/index.html');
            });

            // route middleware to make sure a user is logged in
            server.app.use((req, res, next) => {
				// if cache.manifest got back not 200 it makes an error
                if (req.isAuthenticated() ||
                    /web\.\d+\/login-bg\.png(\?.*)?$/.test(req.originalUrl) ||
                    /cache\.manifest(\?.*)?$/.test(req.originalUrl) ||
                    /^\/login\//.test(req.originalUrl) ||
                    /\.ico(\?.*)?$/.test(req.originalUrl)
                ) {
                    return next();
                } else {
                    autoLogonOrRedirectToLogin(req, res, next, '/login/index.html?href=' + encodeURIComponent(req.originalUrl));
                }
            });
        } else {
            server.app.get('/login', (req, res) => {
                res.redirect('/');
            });
            server.app.get('/logout', (req, res) => {
                res.redirect('/');
            });

            if (settings.whiteListEnabled) {
                initAuth(server, settings);
                server.app.use((req, res, next) => {
                    let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                    let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
                    adapter.log.silly('whiteListIp ' + whiteListIp);
                    if (whiteListIp) {
                       req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
                            return next(err);
                        });
                    } else {
                        req.logIn(settings.defaultUser, err => {
                            return next(err);
                        });
                    }
                });
            }
        }

        // Init read from states
        server.app.get('/state/*', (req, res) => {
            try {
                const fileName = req.url.split('/', 3)[2].split('?', 2);
                adapter.getForeignObject(fileName[0], (err, obj) => {
                    let contentType = 'text/plain';
                    if (obj && obj.common.type === 'file')  {
                        contentType = mime.lookup(fileName[0]);
                    }
                    adapter.getBinaryState(fileName[0], {user: req.user ? 'system.user.' + req.user : settings.defaultUser}, (err, obj) => {
                        if (!err && obj !== null && obj !== undefined) {
                            if (obj && typeof obj === 'object' && obj.val !== undefined && obj.ack !== undefined) {
                                res.set('Content-Type', 'application/json');
                            } else {
                                res.set('Content-Type', contentType || 'text/plain');
                            }
                            res.status(200).send(obj);
                        } else {
                            res.status(404).send('404 Not found. File ' + fileName[0] + ' not found');
                        }
                    });
                });
            } catch (e) {
                res.status(500).send('500. Error' + e);
            }
        });

        server.app.get('*/_socket/info.js', (req, res) => {
            res.set('Content-Type', 'application/javascript');
            res.status(200).send(getInfoJs(settings));
        });

        // Enable CORS
        if (settings.socketio) {
            server.app.use((req, res, next) => {
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');

                // intercept OPTIONS method
                if ('OPTIONS' === req.method) {
                    res.status(200).send(200);
                } else {
                    next();
                }
            });
        }

        let appOptions = {};
        if (settings.cache) appOptions.maxAge = 30758400000;

        server.server = LE.createServer(server.app, settings, settings.certificates, settings.leConfig, adapter.log);
        server.server.__server = server;
    } else {
        adapter.log.error('port missing');
        adapter.terminate ? adapter.terminate(1): process.exit(1);
    }

    if (server.server) {
        settings.port = parseInt(settings.port, 10);
        adapter.getPort(settings.port, port => {
            port = parseInt(port, 10);
            if (port !== settings.port && !settings.findNextPort) {
                adapter.log.error('port ' + settings.port + ' already in use');
                adapter.terminate ? adapter.terminate(1): process.exit(1);
            }
            server.server.listen(port, (!settings.bind || settings.bind === '0.0.0.0') ? undefined : settings.bind || undefined);
            adapter.log.info('http' + (settings.secure ? 's' : '') + ' server listening on port ' + port);
        });
    }

    // activate extensions
    for (let e in extensions) {
        if (!extensions.hasOwnProperty(e)) continue;
        try {
            // for debug purposes try to load file in current directory "/lib/file.js" (elsewise node.js cannot debug it)
            let parts = extensions[e].path.split('/');
            parts.shift();
            let extAPI;
            if (fs.existsSync(__dirname + '/' + parts.join('/'))) {
                extAPI = require(__dirname + '/' + parts.join('/'));
            } else {
                extAPI = require(utils.appName + '.' + extensions[e].path);
            }

            extensions[e].obj = new extAPI(server.server, {secure: settings.secure, port: settings.port}, adapter, extensions[e].config, server.app);
            adapter.log.info('Connect extension "' + extensions[e].path + '"');
        } catch (err) {
            adapter.log.error('Cannot start extension "' + e + '": ' + err);
        }
    }

    // Activate integrated simple API
    if (settings.simpleapi) {
        let SimpleAPI = require(utils.appName + '.simple-api/lib/simpleapi.js');

        server.api = new SimpleAPI(server.server, {secure: settings.secure, port: settings.port}, adapter);
    }

    // Activate integrated socket
    if (ownSocket) {
        let IOSocket = require(utils.appName + '.socketio/lib/socket.js');
        let socketSettings = JSON.parse(JSON.stringify(settings));
        // Authentication checked by server itself
        socketSettings.auth             = settings.auth;
        socketSettings.secret           = secret;
        socketSettings.store            = store;
        socketSettings.ttl              = settings.ttl || 3600;
        socketSettings.forceWebSockets  = settings.forceWebSockets || false;
        server.io = new IOSocket(server.server, socketSettings, adapter);
    }

    if (server.app) {
        // deliver web files from objectDB
        server.app.use('/', (req, res) => {

            let url = decodeURI(req.url);
            // remove all ../
            // important: Linux does not normalize "\" but fs.readFile accepts it as '/'
            url = path.normalize(url.replace(/\\/g, '/')).replace(/\\/g, '/');
            // remove '////' at start and let only one
            if (url[0] === '/' && url[1] === '/') {
                let i = 2;
                while (url[i] === '/') i++;
                url = url.substring(i - 1);
            }
            if ((url[0] === '.' && url[1] === '.') || (url[0] === '/' && url[1] === '.' && url[2] === '.')) {
                res.status(404).send('Not found');
                return;
            }

            if (server.api && server.api.checkRequest(url)) {
                server.api.restApi(req, res);
                return;
            }

            if (url === '/' || url === '/index.html') {
                getListOfAllAdapters((err, data) => {
                    if (err) {
                        res.status(500).send('500. Error' + e);
                    } else {
                        res
                            .set('Content-Type', 'text/html')
                            .status(200)
                            .send(data);
                    }
                });
                return;
            }

            // add index.html
            url = url.replace(/\/($|\?|#)/, '/index.html$1');

            if (url.match(/^\/adapter\//)) {
                // add .admin to adapter name
                url = url.replace(/^\/adapter\/([a-zA-Z0-9-_]+)\//, '/$1.admin/');
            }

            if (url.match(/^\/lib\//)) {
                url = '/' + adapter.name + url;
            }
            if (url.match(/^\/admin\//)) {
                url = '/' + adapter.name + url;
            }
            url = url.split('/');
            // Skip first /
            url.shift();
            // Get ID
            let id = url.shift();
            let versionPrefix = url[0];
            url = url.join('/');
            let pos = url.indexOf('?');
            let noFileCache;
            if (pos !== -1) {
                url = url.substring(0, pos);
                // disable file cache if request like /vis/files/picture.png?noCache
                noFileCache = true;
            }

            // get adapter name
            if (webByVersion[id]) {
                if (!versionPrefix || !versionPrefix.match(/^\d+\.\d+.\d+$/)) {
                    // redirect to version
                    res.set('location', '/' + id + '/' + webByVersion[id] + '/' + url);
                    res.status(301).send();
                    return;
                }
            }

            if (settings.cache && cache[id + '/' + url] && !noFileCache) {
                res.contentType(cache[id + '/' + url].mimeType);
                res.status(200).send(cache[id + '/' + url].buffer);
            } else {
                if (id === 'login' && url === 'index.html') {
                    loginPage = loginPage || prepareLoginTemplate();
                    let buffer = loginPage;

                    if (buffer === null || buffer === undefined) {
                        res.contentType('text/html');
                        res.status(200).send('File ' + url + ' not found', 404);
                    } else {
                        // Store file in cache
                        if (settings.cache) {
                            cache[id + '/' + url] = {buffer: buffer.toString(), mimeType: 'text/html'};
                        }
                        res.contentType('text/html');
                        res.status(200).send(buffer.toString());
                    }
                } else {
                    // special solution for socket.io
                    if (socketIoFile !== false && url.match(/\/socket\.io\.js(\?.*)?$/)) {
                        if (socketIoFile) {
                            res.contentType('text/javascript');
                            res.status(200).send(socketIoFile);
                            return
                        } else {
                            try {
                                const dir = require.resolve('socket.io-client');
                                const fileDir = path.join(path.dirname(dir), '../dist/');
                                if (fs.existsSync(fileDir + 'socket.io.min.js')) {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.min.js');
                                } else {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.js');
                                }
                            } catch (e) {
                                socketIoFile = false;
                            }
                            if (socketIoFile) {
                                res.contentType('text/javascript');
                                res.status(200).send(socketIoFile);
                                return
                            }
                        }
                    }
                    
                    adapter.readFile(id, webByVersion[id] ? url.substring(versionPrefix.length + 1) : url , {user: req.user ? 'system.user.' + req.user : settings.defaultUser, noFileCache: noFileCache}, (err, buffer, mimeType) => {
                        if (buffer === null || buffer === undefined || err) {
                            res.contentType('text/html');
                            res.status(404).send('File ' + url + ' not found: ' + err);
                        } else {
                            mimeType = mimeType || mime.lookup(url) || 'text/javascript';

                            // Store file in cache
                            if (settings.cache) {
                                cache[id + '/' + url] = {
                                    buffer: buffer,
                                    mimeType: mimeType
                                };
                            }

                            res.contentType(mimeType);
                            res.status(200).send(buffer);
                        }
                    });
                }
            }
        });
    }

    if (server.server) {
        return server;
    } else {
        return null;
    }
}
877349
function parseCookies(req, res, next) {
		var self = this;
		var cookieHeader = req.headers.cookie;

		if (cookieHeader) {
			req.cookies = cookie.parse(cookieHeader);
		} else {
			req.cookies = {};
		}

		/**
		 * Add a cookie to our response.  Uses a Set-Cookie header
		 * per cookie added.
		 * 
		 * @param {String} key  - Cookie name
		 * @param {String} val  - Cookie value
		 * @param {[type]} opts - Options object can contain path, secure, 
		 *     expires, domain, http
		 */
		res.setCookie = function setCookie(key, val, opts) {
			var HEADER = "Set-Cookie";

			if (res.header(HEADER)) {
				var curCookies = res.header(HEADER);

				if (!(curCookies instanceof Array)) {
					curCookies = [curCookies];
				}

				curCookies.push(cookie.serialize(key, val, opts));

				res.setHeader(HEADER, curCookies);

			} else {

				res.setHeader(HEADER, cookie.serialize(key, val, opts));

			}
		};

		res.clearCookie = function clearCookie (key, opts) {
			var options = merge({
				expires: new Date(1)
			}, opts);

			res.setCookie(key, '', options)
		}

		next();

	}
534345
function(http, options) {
  if (!http || http === 'undefined') {
    http = require('http');
  }

  this.url = require('url');
  this.http = http;
  this.options = options;
}
220703
function NodeSession(config, encrypter) {
    var defaults = {
        'driver': 'file',
        'lifetime': 300000, // five minutes
        'expireOnClose': false,
        'files': process.cwd()+'/sessions',
        'connection': false,
        'table': 'sessions',
        'lottery': [2, 100],
        'cookie': 'node_session',
        'path': '/',
        'domain': null,
        'secure': false,
        'httpOnly': true,
        'encrypt': false
    };

    /**
     * The Session configuration
     *
     * @type {Object}
     * @private
     */
    this.__config = _.merge(defaults, config);

    if(this.__config.trustProxy && !this.__config.trustProxyFn) {
        this.__config.trustProxyFn = util.compileTrust(this.__config.trustProxy)
    }

    /**
     * The session manager instance
     * @type {SessionManager}
     * @private
     */
    this.__manager = new SessionManager(this.__config, encrypter);

    if (!this.__config.secret) {
        throw new Error('secret option required for sessions');
    }
}