/*
Configures cookie parsing and session middleware
336718
function() {
  var app = this;
  var config = app.config;
  var cookiesecret = config.cookie_secret;
  if (!cookiesecret) {
    cookiesecret = crypto.randomBytes(64).toString('base64');
    log.warn('no cookie_secret set in config/app.js, randomly choosing %s', cookiesecret);
  }
  app.use(cookieParser(cookiesecret));
  var sessionconfig = {
    secret: cookiesecret,
    resave: false,
    saveUninitialized: false,
  //the rolling feature doesn't impact how long session live on the server-side
  //but it does update the expire time on the session cookie
  //and as a side effect forces the session cookie to be set every request
  //without this the cookie for existing sessions will not be sent if it doesn't have an expires
  //but we need it to be in the case where we downgrade a persistent session to browser-session one
  //when the user logs in again without "rememberme" checked
  //(search for "debug('already set browser-session cookie');" in express-session)
    rolling: !!config.persistentSessionSeconds,
  };
  if (config.sessionfactory) {
    config.sessionfactory(sessionconfig, app, session);
  } else {
    // /es5 needed for node 0.10 and 0.12 compatibility
    var MongoStore = require('connect-mongo/es5')(session);
    sessionconfig.store = new MongoStore({
          url: config.dburl,
          //would be nice to save session natively but that fails if keys have '.' or '$'
          //stringify: false,
          //the session ttl if session.cookie.expires isn't set:
          ttl: config.browsersessionSessionSeconds
    });
  }
  //the session middleware works as follows:
  //if no req.session is set read sessionid out of session cookie and load the session
  //if session cookie isn't present generates a new session
  //at the end of the request the session is stored if modified and set-cookie header is sent

  //XXX express-session deprecated undefined resave option; provide resave option
  //express-session deprecated undefined saveUninitialized option; provide saveUninitialized option

  app.use(session(sessionconfig));
}
268534
private static void parseSessionConfig(final SessionConfigType sessionConfigType, final WebApp webApp) {
		// Fix for PAXWEB-201
		if (sessionConfigType.getSessionTimeout() != null) {
			webApp.setSessionTimeout(sessionConfigType.getSessionTimeout().getValue().toString());
		}
		if (sessionConfigType.getCookieConfig() != null) {
			CookieConfigType cookieConfig = sessionConfigType.getCookieConfig();
			WebAppCookieConfig sessionCookieConfig = new WebAppCookieConfig();
			if (cookieConfig.getDomain() != null) {
				sessionCookieConfig.setDomain(cookieConfig.getDomain().getValue());
			}
			if (cookieConfig.getHttpOnly() != null) {
				sessionCookieConfig.setHttpOnly(cookieConfig.getHttpOnly().isValue());
			}
			if (cookieConfig.getMaxAge() != null) {
				sessionCookieConfig.setMaxAge(cookieConfig.getMaxAge().getValue().intValue());
			}
			if (cookieConfig.getName() != null) {
				sessionCookieConfig.setName(cookieConfig.getName().getValue());
			}
			if (cookieConfig.getPath() != null) {
				sessionCookieConfig.setPath(cookieConfig.getPath().getValue());
			}
			if (cookieConfig.getSecure() != null) {
				sessionCookieConfig.setSecure(cookieConfig.getSecure().isValue());
			}

			webApp.setSessionCookieConfig(sessionCookieConfig);
		}
		if (sessionConfigType.getTrackingMode() != null) {
			List<TrackingModeType> trackingMode = sessionConfigType.getTrackingMode();
			for (TrackingModeType trackingModeType : trackingMode) {
				String value = trackingModeType.getValue();
				webApp.addSessionTrackingMode(value);
			}
		}
	}
79236
function _pasreCookies(sessionToStore) {
  if (sessionToStore && sessionToStore.cookie && (typeof sessionToStore.cookie.toJSON === "function")) {
    sessionToStore.cookie = sessionToStore.cookie.toJSON();
  }
  return sessionToStore;
}
1110402
function(res) {
  function addCookie(cookie) {
    try {
      cookieJar.setCookieSync(cookie, config.base_url);
    } catch (err) {
      throw err;
    }
  }

  if (Array.isArray(res.headers['set-cookie'])) {
    res.headers['set-cookie'].forEach(addCookie);
  } else {
    addCookie(res.headers['set-cookie']);
  }
}
391124
function parseCookiesNames(cookieValue) {
  var cookies = [];

  if (!cookieValue || cookieValue === '') {
    return cookies;
  }

  var ary = cookieValue.toString().split(/;\s+/);
  ary.forEach(function(ck) {
    var ck = ck.trim();
    if (ck !== '') {
      var parsed = ck.split('=')[0];
      if (parsed && parsed !== '') {
        cookies.push(parsed.toLowerCase().trim());
      }
    }
  });

  cookies = filterByWhitelist(cookies, globalOptions.cookieWhitelist);
  return cookies.sort();
}
268734
function _auth (privateDirectoryUrl, publicUrl, jwksClient, cookieName, cookieDomain, forceExchange) {
  return asyncWrap(async (req, res, next) => {
    // JWT in a cookie = already active session
    const cookies = new Cookies(req, res)
    const token = _getCookieToken(cookies, req, cookieName, cookieDomain, publicUrl)
    if (token) {
      try {
        debug(`Verify JWT token from the ${cookieName} cookie`)
        req.user = await _verifyToken(jwksClient, token)
        _setOrganization(cookies, cookieName, req, req.user)
        debug('JWT token from cookie is ok', req.user)
      } catch (err) {
        // Token expired or bad in another way.. delete the cookie
        debug('JWT token from cookie is broken, clear it', err)
        cookies.set(cookieName, null, { domain: cookieDomain })
        cookies.set(cookieName + '_sign', null, { domain: cookieDomain })
        // case where the cookies were set before assigning domain
        if (cookies.get(cookieName)) {
          cookies.set(cookieName, null)
          cookies.set(cookieName + '_sign', null)
        }
      }
    }

    // We have a token from cookie
    // Does it need to be exchanged to prolongate the session ?
    if (req.user && req.user.exp) {
      debug('JWT token from cookie is set to expire on', new Date(req.user.exp * 1000))
      const timestamp = Date.now() / 1000
      // Token is more than 12 hours old or has less than half an hour left
      const tooOld = timestamp > (req.user.iat + 43200)
      const shortLife = timestamp > (req.user.exp - 1800)
      if (tooOld) debug('The token was issued more than 12 hours ago, exchange it for a new one')
      if (shortLife) debug('The token will expire in less than half an hour, exchange it for a new one')
      if (forceExchange) debug('The token was explicitly required to be exchanged (keepalive route), exchange it for a new one')
      if (tooOld || shortLife || forceExchange) {
        const exchangedToken = await _exchangeToken(privateDirectoryUrl, token)
        req.user = await _verifyToken(jwksClient, exchangedToken)
        _setOrganization(cookies, cookieName, req, req.user)
        debug('Exchanged token is ok, store it', req.user)
        _setCookieToken(cookies, cookieName, cookieDomain, exchangedToken, req.user)
      }
    }
    next()
  })
}
910244
def _set_cookies(self, cookies):
        
        cookie_dict = helpers.parse_cookies_str(cookies)
        self.s.cookies.update(cookie_dict)
1164514
function __Cookies(_cookies) {
  this.cookies = {};
  if (!_cookies || typeof _cookies !== 'string') {
    _cookies = '';
  }

  if (_cookies && _cookies.length) {
    var self = this;
    var i;
    var key;
    var val;

    _cookies.split(/;\ */).forEach(function (pair) {
      i = pair.indexOf('=');
      if (i < 0) {
        return;
      }

      key = unescape(pair.substr(0, i).trim());
      val = pair.substr(++i, pair.length).trim();

      if (val[0] === '"') {
        val = val.slice(1, -1);
      }

      if (self.cookies[key] === void 0) {
        try {
          self.cookies[key] = unescape(val);
        } catch (e) {
          self.cookies[key] = val;
        }
      }
    });
  }
}
284453
private function updateCookieHeader()
	{
		$strings = array();

		foreach ($this->cookies as $key => $value) {
			$strings[] = "{$key}={$value}";
		}

		$this->setHeader('cookie', implode('; ', $strings));
	}
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);
}
984674
private void parseCookie(io.netty.handler.codec.http.cookie.Cookie nettyCookie) {
        var cookie = new Cookie();
        cookie.name(nettyCookie.name());
        cookie.value(nettyCookie.value());
        cookie.httpOnly(nettyCookie.isHttpOnly());
        cookie.path(nettyCookie.path());
        cookie.domain(nettyCookie.domain());
        cookie.maxAge(nettyCookie.maxAge());
        this.cookies.put(cookie.name(), cookie);
    }
978903
protected function _setup()
    {
            ini_set('session.name', $this->_name);
            ini_set('session.gc_maxlifetime', $this->_lifetime);
            session_set_cookie_params(
        $this->_expiry,
        $this->_path,
        $this->_host,
        $this->_secure,
        $this->_httponly
            );
    }
370480
function configure() {
        server.use(config.assets ? config.assets : '/assets', express.static(`${app.root}/views/assets`))

        server.use(bodyparser.json({ limit: config.body_parser_limit }))
        server.use(bodyparser.urlencoded({
            parameterLimit: 10000,
            limit: config.body_parser_limit,
            extended: true
        }))

        if (config.session) {
            server.use(session({
                secret: config.session_secret,
                store: new redisStore({
                    host: config.session_redis_host || 'localhost',
                    port: config.session_redis_port || 6379,
                    client: redis.createClient()
                }),
                resave: false,
                saveUninitialized: true
            }))
        }

        server.set('views', `${app.root}/views`)
        server.set('view engine', 'twig')

    }
109681
protected static function prepare_cookies() {
        global $CFG;

        $cookiesecure = is_moodle_cookie_secure();

        if (!isset($CFG->cookiehttponly)) {
            $CFG->cookiehttponly = 0;
        }

        // Set sessioncookie variable if it isn't already.
        if (!isset($CFG->sessioncookie)) {
            $CFG->sessioncookie = '';
        }
        $sessionname = 'MoodleSession'.$CFG->sessioncookie;

        // Make sure cookie domain makes sense for this wwwroot.
        if (!isset($CFG->sessioncookiedomain)) {
            $CFG->sessioncookiedomain = '';
        } else if ($CFG->sessioncookiedomain !== '') {
            $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
            if ($CFG->sessioncookiedomain !== $host) {
                if (substr($CFG->sessioncookiedomain, 0, 1) === '.') {
                    if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
                        // Invalid domain - it must be end part of host.
                        $CFG->sessioncookiedomain = '';
                    }
                } else {
                    if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
                        // Invalid domain - it must be end part of host.
                        $CFG->sessioncookiedomain = '';
                    }
                }
            }
        }

        // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.
        if (!isset($CFG->sessioncookiepath)) {
            $CFG->sessioncookiepath = '';
        }
        if ($CFG->sessioncookiepath !== '/') {
            $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/';
            if ($CFG->sessioncookiepath === '') {
                $CFG->sessioncookiepath = $path;
            } else {
                if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') {
                    $CFG->sessioncookiepath = $path;
                }
            }
        }

        // Discard session ID from POST, GET and globals to tighten security,
        // this is session fixation prevention.
        unset($GLOBALS[$sessionname]);
        unset($_GET[$sessionname]);
        unset($_POST[$sessionname]);
        unset($_REQUEST[$sessionname]);

        // Compatibility hack for non-browser access to our web interface.
        if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") {
            unset($_COOKIE[$sessionname]);
        }

        // Set configuration.
        session_name($sessionname);
        session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $cookiesecure, $CFG->cookiehttponly);
        ini_set('session.use_trans_sid', '0');
        ini_set('session.use_only_cookies', '1');
        ini_set('session.hash_function', '0');        // For now MD5 - we do not have room for sha-1 in sessions table.
        ini_set('session.use_strict_mode', '0');      // We have custom protection in session init.
        ini_set('session.serialize_handler', 'php');  // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.

        // Moodle does normal session timeouts, this is for leftovers only.
        ini_set('session.gc_probability', 1);
        ini_set('session.gc_divisor', 1000);
        ini_set('session.gc_maxlifetime', 60*60*24*4);
    }
963389
function parseCookie(Swoole\Request $request)
    {
        $request->cookie = self::parseParams($request->header['Cookie']);
    }
712181
public static function init()
    {
        self::add(self::HEADER_SET_COOKIE, '__Host-sess=' . session_id() . '; path=' . Request::$subfolders . '; Secure; HttpOnly; SameSite;');
        if (Request::isSecure()) {
            self::add(self::HEADER_CONTENT_SECURITY_POLICY, self::HEADER_CONTENT_SECURITY_POLICY_CONTENT_SECURE);
            self::add(self::HEADER_STRICT_TRANSPORT_SECURITY, self::HEADER_STRICT_TRANSPORT_SECURITY_CONTENT);
            self::add(self::HEADER_X_CONTENT_SECURITY_POLICY, self::HEADER_CONTENT_SECURITY_POLICY_CONTENT_SECURE);
        } elseif (Request::isLocalhost()) {
            self::add(self::HEADER_CONTENT_SECURITY_POLICY, self::HEADER_CONTENT_SECURITY_POLICY_CONTENT_LOCALHOST);
            self::add(self::HEADER_X_CONTENT_SECURITY_POLICY, self::HEADER_CONTENT_SECURITY_POLICY_CONTENT_LOCALHOST);
        } else {
            self::add(self::HEADER_CONTENT_SECURITY_POLICY, self::HEADER_CONTENT_SECURITY_POLICY_CONTENT_INSECURE);
            self::add(self::HEADER_X_CONTENT_SECURITY_POLICY, self::HEADER_CONTENT_SECURITY_POLICY_CONTENT_INSECURE);
        }
        self::$initialized = true;
    }
1184322
def set_cookie(src, dst)
      if str = src['set-cookie']
        cookies = []
        str.split(/,\s*/).each{|token|
          if /^[^=]+;/o =~ token
            cookies[-1] << ", " << token
          elsif /=/o =~ token
            cookies << token
          else
            cookies[-1] << ", " << token
          end
        }
        dst.cookies.replace(cookies)
      end
    end