Check the secure cookie and set login information appropriately
960860
public static function loginSecureCookie($session_object=null) {
        global $CFG, $PDOX;
        $pieces = false;
        $id = false;

        // Only do this if we are not already logged in...
        if ( self::wrapped_session_get($session_object,'id') || !isset($_COOKIE[$CFG->cookiename]) ||
             !isset($CFG->cookiepad) || $CFG->cookiepad === false) {
            return;
        }

        $ct = $_COOKIE[$CFG->cookiename];
        // error_log("Cookie: $ct \n");
        $pieces = SecureCookie::extract($ct);
        if ( $pieces === false || count($pieces) != 3) {
            error_log('Decrypt fail:'.$ct);
            SecureCookie::delete();
            return;
        }

        // print_r($pieces); die();

        // Convert to an integer and check valid
        $user_id = is_numeric($pieces[0])? $pieces[0] + 0 : 0;
        $userEmail = $pieces[1];
        $context_id = is_numeric($pieces[2]) ? $pieces[2] + 0 : 0;
        if ( $user_id < 1 || $context_id < 1 ) {
            $user_id = false;
            error_log('Decrypt bad ID:'.$ct);
            error_log(\Tsugi\UI\Output::safe_var_dump($pieces));
            SecureCookie::delete();
            return;
        }

        // The profile table might not even exist yet.
        // See also login.php line 339 (ish)
        $sql = "SELECT P.profile_id AS profile_id,
                U.user_id AS user_id, U.user_key AS user_key,
                U.displayname AS displayname, U.email AS email, U.image AS user_image,
                P.displayname AS p_displayname, P.email AS p_email, P.image AS p_user_image,
                role, C.context_key, C.context_id AS context_id,
                C.title AS context_title, C.title AS resource_title,
                K.key_id, K.key_key, K.secret, K.new_secret,
                NULL AS nonce
                FROM {$CFG->dbprefix}profile AS P
                LEFT JOIN {$CFG->dbprefix}lti_user AS U
                ON P.profile_id = U.profile_id AND user_sha256 = profile_sha256 AND
                    P.key_id = U.key_id
                LEFT JOIN {$CFG->dbprefix}lti_key AS K
                    ON U.key_id = K.key_id
                LEFT JOIN {$CFG->dbprefix}lti_context AS C
                    ON U.key_id = C.key_id
                LEFT JOIN {$CFG->dbprefix}lti_membership AS M
                    ON U.user_id = M.user_id AND C.context_id = M.context_id
                WHERE P.email = :EMAIL AND U.email = :EMAIL
                    AND U.user_id = :UID AND C.context_id = :CID LIMIT 1";

        $stmt = $PDOX->queryReturnError($sql,
            array('EMAIL' => $userEmail, ":UID" => $user_id, ":CID" => $context_id)
        );

        // print_r($stmt); die();
        if ( $stmt->success === false ) return;

        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        // print_r($row); die();
        if ( $row === false ) {
            error_log("Unable to load user_id=$user_id EMAIL=$userEmail");
            SecureCookie::delete();
            return;
        }

        // Coalesce from profile to user where there is missing data
        if ( strlen($row['user_image']) < 1 ) $row['user_image'] = $row['p_user_image'];
        if ( strlen($row['email']) < 1 ) $row['email'] = $row['p_email'];
        if ( strlen($row['displayname']) < 1 ) $row['displayname'] = $row['p_displayname'];
        unset($row['p_user_image']);
        unset($row['p_email']);
        unset($row['p_displayname']);

        self::wrapped_session_put($session_object,'id',$row['user_id']);
        self::wrapped_session_put($session_object,'email',$row['email']);
        self::wrapped_session_put($session_object,'displayname',$row['displayname']);
        self::wrapped_session_put($session_object,'profile_id',$row['profile_id']);
        self::wrapped_session_put($session_object,'user_key',$row['user_key']);
        self::wrapped_session_put($session_object,'avatar',$row['user_image']);
        if ( isset($row['key_key']) ) {
            self::wrapped_session_put($session_object,'oauth_consumer_key',$row['key_key']);
        }
        if ( $row['role'] !== null ) {
            self::wrapped_session_put($session_object,'context_key',$row['context_key']);
            self::wrapped_session_put($session_object,'context_id',$row['context_id']);
        }

        if ( isset($row['secret']) ) {
            $row['secret'] = self::encrypt_secret($row['secret']);
            self::wrapped_session_put($session_object,'secret', $row['secret']);
        }
        if ( isset($row['new_secret']) ) {
            $row['new_secret'] = self::encrypt_secret($row['new_secret']);
        }

        // Emulate a session launch
        self::wrapped_session_put($session_object,'lti',$row);

        self::noteLoggedIn($row);

        error_log('Autologin:'.$row['user_id'].','.$row['displayname'].','.
            $row['email'].','.$row['profile_id']);

    }
589816
public void setCookie(String name, String value, String path, Date expirationDate, boolean secure, boolean httpOnly) {
        if (remote == null)
            throw new IllegalStateException("Cannot setCookie since remote == null");
        if (path == null || path.length() == 0)
            path = remote.getPath();
        Cookie.Builder builder = new Cookie.Builder();
        builder.name(name).value(value).domain(remote.getHost()).path(path);
        if (expirationDate != null)
            builder.expiresAt(expirationDate.getTime());
        List<Cookie> cookies = Collections.singletonList(builder.build());
        this.clientFactory.addCookies(cookies);
    }
1210195
public function setCookie($cookie_key, $cookie_value, $expire = null, $path = null, $domain = null, $secure = null, $httpOnly = null)
    {
        if ($this->isSingle()) {
            ResponseKit::setCookie($cookie_key, $cookie_value, $expire, $path, $domain, $secure, $httpOnly);
        }
    }
757080
def set_cookie(self, name: str, value: str, *,
                   expires: Optional[str]=None,
                   domain: Optional[str]=None,
                   max_age: Optional[Union[int, str]]=None,
                   path: str='/',
                   secure: Optional[str]=None,
                   httponly: Optional[str]=None,
                   version: Optional[str]=None) -> None:
        

        old = self._cookies.get(name)
        if old is not None and old.coded_value == '':
            # deleted cookie
            self._cookies.pop(name, None)

        self._cookies[name] = value
        c = self._cookies[name]

        if expires is not None:
            c['expires'] = expires
        elif c.get('expires') == 'Thu, 01 Jan 1970 00:00:00 GMT':
            del c['expires']

        if domain is not None:
            c['domain'] = domain

        if max_age is not None:
            c['max-age'] = str(max_age)
        elif 'max-age' in c:
            del c['max-age']

        c['path'] = path

        if secure is not None:
            c['secure'] = secure
        if httponly is not None:
            c['httponly'] = httponly
        if version is not None:
            c['version'] = version
1192130
function set_login_cookies($login, $key)
	{
		setcookie('eresus_login', $login, time()+2592000, $this->path);
		setcookie('eresus_key', $key, time()+2592000, $this->path);
	}
65770
private static function secure() {
	if (\alsvanzelf\fem\CLI) {
		return;
	}
	
	header_remove('X-Powered-By');
	
	ini_set('session.use_trans_sid',    0);
	ini_set('session.use_only_cookies', 1);
	ini_set('session.cookie_httponly',  1);
	ini_set('session.use_strict_mode',  1); // @note this is only effective from 5.5.2
	ini_set('session.entropy_file',     '/dev/urandom');
}
377460
def authenticate(self):
        """"""
        postdata = self.authentication_postdata
        jar = requests.cookies.cookielib.CookieJar()
        self.cookies = jar
        resp = self.get(self.authentication_base_url)
        authtok = _extract_authenticity_token(resp.content)
        if postdata is None:
            # This works for GitHub
            postdata = {"login": self.oauth2_username,
                        "password": self._oauth2_password,
                        "authenticity_token": authtok,
                        "commit": "Sign+in",
                        "utf8": u"\u2713",
                        }  # pylint: disable=bad-continuation
            self.authentication_postdata = postdata
        if self.authentication_session_url is None:
            # This is also for GitHub
            authentication_session_url = "https://github.com/session"
            self.authentication_session_url = authentication_session_url
        self.post(self.authentication_session_url, data=postdata)
1282573
def set_cookie(cookies, key, value='', max_age=None, expires=None, path='/',
               domain=None, secure=False, httponly=False):
    ''''''
    cookies[key] = value
    if expires is not None:
        if isinstance(expires, datetime):
            now = (expires.now(expires.tzinfo) if expires.tzinfo else
                   expires.utcnow())
            delta = expires - now
            # Add one second so the date matches exactly (a fraction of
            # time gets lost between converting to a timedelta and
            # then the date string).
            delta = delta + timedelta(seconds=1)
            # Just set max_age - the max_age logic will set expires.
            expires = None
            max_age = max(0, delta.days * 86400 + delta.seconds)
        else:
            cookies[key]['expires'] = expires
    if max_age is not None:
        cookies[key]['max-age'] = max_age
        # IE requires expires, so set it if hasn't been already.
        if not expires:
            cookies[key]['expires'] = http_date(time.time() + max_age)
    if path is not None:
        cookies[key]['path'] = path
    if domain is not None:
        cookies[key]['domain'] = domain
    if secure:
        cookies[key]['secure'] = True
    if httponly:
        cookies[key]['httponly'] = True
931609
private function cookieLogin()
    {
        $read = new Read();
        $prazoTokenExpira = date('Y-m-d H:i:s', strtotime("-2 months", strtotime(date("Y-m-d H:i:s"))));
        $read->exeRead("usuarios", "WHERE token = :to", "to={$_COOKIE['token']}");

        if ($read->getResult() && $read->getResult()[0]['status'] === 1 && $read->getResult()[0]['token_expira'] > $prazoTokenExpira) {
            $login = new Login();
            $login->setLogin(["user" => $read->getResult()[0]['nome'], "password" => $read->getResult()[0]['password']]);
        } else {
            new Logout();
        }
    }
138621
def login(self):
        
        resp = super(CookieSession, self).request(
            'POST',
            self._session_url,
            data={'name': self._username, 'password': self._password},
        )
        resp.raise_for_status()
128101
def safe_login
      if not Masq::Engine.config.masq.include? 'protect_phishing' or Masq::Engine.config.masq['protect_phishing']
        render :layout => false
      else
        redirect_to login_url
      end
    end
921175
public function login()
	{
		// extra lines for passing curl options to other routines, like ambrasubs payment processor
		// we are using the super global $_SESSION to pass data in $_SESSION[$var]
		if (isset($this->options['usesessvar'])) {
			$var = 'curl_options';
			if(!array_key_exists($var, $_SESSION)) $_SESSION[$var] = '';
			$_SESSION[$var] = $this->options;
			$GLOBALS[$var] = &$_SESSION[$var];
		}
		// end extra lines
		$overridearr = array();

		// find out if we have a SSL enabled website
		if (strpos($this->options['post_url'], 'https://') === false) {
			$ssl_string = 'http://';
		} else {
			$ssl_string = 'https://';
		}

		// check if curl extension is loaded
		if (!isset($this->options['post_url']) || !isset($this->options['formid'])) {
			$this->status['error'][] = static::_('CURL_FATAL');
		} else {
			if (!extension_loaded('curl')) {
				$this->status['error'][] = static::_('CURL_NOTINSTALLED');
			} else {
				$this->status['debug'][] = static::_('CURL_POST_URL_1') . ' ' . $this->options['post_url'];
				$remotedata = $this->ReadPage(true);
				if (empty($this->status['error'])) {
					$this->status['debug'][] = static::_('CURL_PHASE_1');
					$this->setCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
					//find out if we have the form with the name/id specified
					$parser = new HtmlFormParser($remotedata);
					$result = $parser->parseForms();
					$frmcount = count($result);
					$myfrm = -1;
					$i = 0;
                    // HJW changed 12 january 2013 to accommodate from identifiers changing every
                    // new access to the page containing the form. Like logonform123 , loginform a2s
                    // etc.

                    do {
                        if (isset($result[$i]['form_data']['name'])) {
                            if (strpos(strtolower($result[$i]['form_data']['name']),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
                        if (isset($result[$i]['form_data']['id'])) {
                            if (strpos(strtolower($result[$i]['form_data']['id']),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
	                    /** HJW 14-7-2014
	                      * we really should use the action field if there is no name field and no id field,
	                      * otherwise we may trigger a false match too easily
	                      * (eg match login with www.mydomain.com/login/index.php)
	                     */
                        if (isset($result[$i]['form_data']['action']) && !isset($result[$i]['form_data']['id']) && !isset($result[$i]['form_data']['name'])) {
                            if (strpos(strtolower(htmlspecialchars_decode($result[$i]['form_data']['action'])),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
                        $i +=1;
                    } while ($i<$frmcount);

					if ($myfrm == -1) {
						$helpthem = '';
						if ($frmcount >0) {
							$i = 0;
							$helpthem = 'I found';
							do {
								if (isset($result[$i]['form_data']['id'])) {
									$helpthem = $helpthem . ' -- Name=' . $result[$i]['form_data']['name'] . ' &ID=' . $result[$i]['form_data']['id'];
								}
								$i +=1;
							} while ($i<$frmcount);
						}
						$this->status['debug'][] = static::_('CURL_NO_LOGINFORM') . ' ' . $helpthem;
					} else {
						$this->status['debug'][] = static::_('CURL_VALID_FORM');


						// by now we have the specified  login/logout form, lets get the data needed to login/logout
						// we went to all this trouble to get to the hidden input entries.
						// The stuff is there to enhance security and is, yes, hidden
						$form_action = htmlspecialchars_decode($result[$myfrm]['form_data']['action']);
						$elements_keys = array_keys($result[$myfrm]['form_elements']);
						$elements_values = array_values($result[$myfrm]['form_elements']);
						$elements_count  = count($result[$myfrm]['form_elements']);

						// override keys/values from hidden inputs
						// the $override is an array of keys/values that override existing keys/values

						if (empty($this->options['logout'])) {

							if ($this->options['override']) {
								$lines = explode(',', $this->options['override']);
								foreach ($lines as $line) {
									$cinfo = explode('=', $line);
									$overridearr[$cinfo[0]]['value'] = $cinfo[1];
									$overridearr[$cinfo[0]]['type'] = 'hidden';
								}
								$newhidden = array_merge($result[$myfrm]['form_elements'], $overridearr);
								$elements_keys = array_keys($newhidden);
								$elements_values = array_values($newhidden);
								$elements_count  = count($newhidden);
							}
						}
						// now construct the action parameter

						// we have 4 possible options:
						// case 0 Form action is without http.. and relpath = 0 , special case
						// case 1 Form action is without http.. and relpath = 1 , just construct the action
						// case 2 form_action is a full url, eg http..... and relpath = 0 This is easy, we do nothing at all
						// case 3 form_action is a full url, eg http..... and relpath = 1 special case

						$rel = (int)($this->options['relpath']);
						//      if (substr($form_action, 0, strlen($ssl_string))== $ssl_string) $hashttp = 2; else $hashttp = 0;
						if (substr($form_action, 0, strlen('http')) == 'http') {
							$hashttp = 2;
						} else {
							$hashttp = 0;
						}

						switch($rel+$hashttp) {
							case 0:
								//add a / in front of form_action
								if (substr($form_action, 0, 1) != '/') {
									$form_action = '/' . $form_action;
								}
								// we need to correct various situations like
								// relative url from basedir, relative url from post dir etc
								$tmpurl   = static::parseUrl($this->options['post_url']);
								$pathinfo1  = pathinfo($form_action);
								$pathinfo = pathinfo($tmpurl[6]);
								//$this->status['debug'][] = 'post_url   : ' . print_r($this->options['post_url'], true);
								//$this->status['debug'][] = 'tmpurl     : ' . print_r($tmpurl, true);
								//$this->status['debug'][] = 'form_action: ' . print_r($form_action, true);
								//$this->status['debug'][] = 'pathinfo1  : ' . print_r($pathinfo1, true);
								//$this->status['debug'][] = 'pathinfo   : ' . print_r($pathinfo, true);
								if ($pathinfo['dirname'] == $pathinfo1['dirname']) {
									$pathinfo['dirname'] = '';
								} //prevent double directory

								// replace windows DIRECTORY_SEPARATOR bt unix DIRECTORY_SEPARATOR
								$pathinfo['dirname'] = str_replace("\\", '/', $pathinfo['dirname']);
								// get rid of the trailing /  in dir
								rtrim($pathinfo['dirname'], '/');
								$port = !empty($tmpurl[5]) ? ':' . $tmpurl[5] : '';
								$form_action = $ssl_string . $tmpurl[4] . $port . $pathinfo['dirname'] . $form_action;
								//$this->status['debug'][] = 'form_action_final: ' . print_r($form_action, true);
								break;
							case 1:
								//add a / in front of form_action
								if (substr($form_action, 0, 1) != '/') {
									$form_action = '/' . $form_action;
								}
								$this->options['post_url'] = rtrim($this->options['post_url'], '/');
								$form_action = $this->options['post_url'] . $form_action;
								break;
							case 2:
								//do nothing at all
								break;
							case 3:
								// reserved, maybe something pops up, then we use this
								break;
						}

						$input_username_name = '';
						$input_password_name = '';
						if (empty($this->options['logout'])) {
							for ($i = 0; $i <= $elements_count-1; $i++) {
								if ($this->options['input_username_id']) {
									if (strtolower($elements_keys[$i]) == strtolower($this->options['input_username_id'])) {
										$input_username_name = $elements_keys[$i];
										break;
									}
								}
								if ($input_username_name == '') {
									if (strpos(strtolower($elements_keys[$i]), 'user') !== false) {
										$input_username_name = $elements_keys[$i];
									}
									if (strpos(strtolower($elements_keys[$i]), 'name') !== false) {
										$input_username_name = $elements_keys[$i];
									}
								}
							}


							if ($input_username_name == '') {
								$this->status['error'][] = static::_('CURL_NO_NAMEFIELD');
								return $this->status;
							}

							for ($i = 0; $i <= $elements_count-1; $i++) {
								if ($this->options['input_password_id']) {
									if (strtolower($elements_keys[$i]) == strtolower($this->options['input_password_id'])) {
										$input_password_name = $elements_keys[$i];
										break;
									}
								}
								if (strpos(strtolower($elements_keys[$i]), 'pass') !== false) {
									$input_password_name = $elements_keys[$i];
								}
							}

							if ($input_password_name == '') {
								$this->status['error'][] = static::_('CURL_NO_PASSWORDFIELD');
								return $this->status;
							}
							$this->status['debug'][] = static::_('CURL_VALID_USERNAME');
						}
						// we now set the submit parameters. These are:
						// all form_elements name=value combinations with value != '' and type hidden
						$strParameters = '';
						if ($this->options['hidden']) {
							for ($i = 0; $i <= $elements_count-1; $i++) {
								if (($elements_values[$i] ['value'] != '') && ($elements_values[$i]['type'] == 'hidden')) {
									$strParameters .= '&' . $elements_keys[$i] . '=' . urlencode($elements_values[$i]['value']);
								}
							}
						}

						// code for buttons submitted by Daniel Baur
						if ($this->options['buttons']) {
							if (isset($result[$myfrm] ['buttons'][0]['type'])) {
								if ($result[$myfrm] ['buttons'][0]['type'] == 'submit') {
									if ($result[$myfrm]['buttons'][0]['name']) {
										$strParameters .= '&' . $result[$myfrm]['buttons'][0]['name'] . '=' . urlencode($result[$myfrm]['buttons'][0]['value']);
									} else {
										$strParameters .= '&' . 'submit=' . urlencode($result[$myfrm]['buttons'][0]['value']);
									}
								}
							}
						}

						// extra post parameter to avoid endless loop when more then one jFusion is installed
						if (isset($this->options['jnodeid'])) {
							$strParameters .= '&jnodeid=' . urlencode($this->options['jnodeid']);
						}

						// extra post parameter to signal a host calling
						if (isset($this->options['jhost'])) {
							$strParameters .= '&jhost=true';
						}

						if (empty($this->options['logout'])) {
							$post_params = $input_username_name . '=' . urlencode($this->options['username']) . '&' . $input_password_name . '=' . urlencode($this->options['password']);
							$post_params_debug = $input_username_name . '=' . urlencode($this->options['username']) . '&' . $input_password_name . '=xxxxxx';
							$this->status['debug'][] = static::_('CURL_STARTING_LOGIN') . ' ' . $form_action . ' parameters= ' . $post_params_debug . $strParameters;
						} else {
							$post_params = '';
							$this->status['debug'][] = static::_('CURL_STARTING_LOGOUT') . ' ' . $form_action . ' parameters= ' . $strParameters;
						}

						// finally submit the login/logout form:
						if ($this->options['integrationtype'] == 1) {
							$this->ch = curl_init();
							$ip = $_SERVER['REMOTE_ADDR'];
							curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('REMOTE_ADDR: ' . $ip, 'X_FORWARDED_FOR: ' . $ip));
							curl_setopt($this->ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
							curl_setopt($this->ch, CURLOPT_REFERER, '');
							curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
							curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->options['verifyhost']);
							curl_setopt($this->ch, CURLOPT_FAILONERROR, 1);
							curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, array($this, 'readHeader'));
							if (empty($this->options['brute_force'])) {
								curl_setopt($this->ch, CURLOPT_COOKIE, $this->buildCookie());
							}
							curl_setopt($this->ch, CURLOPT_VERBOSE, $this->options['debug']); // Display communication with server
						}
						curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0);
						curl_setopt($this->ch, CURLOPT_URL, $form_action);
						curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
						curl_setopt($this->ch, CURLOPT_POST, 1);
						curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_params . $strParameters);
						if (!empty($this->options['httpauth'])) {
							curl_setopt($this->ch, CURLOPT_USERPWD, $this->options['httpauth_username'] . ':' . $this->options['httpauth_password']);
							curl_setopt($this->ch, CURLOPT_HTTPAUTH, $this->options['httpauth']);
						}

						$remotedata = curl_exec($this->ch);
						if ($this->options['debug']) {
							$this->status['cURL']['data'][] = $remotedata;
							$this->status['debug'][] = 'CURL_INFO: ' . print_r(curl_getinfo($this->ch), true);
						}
						if (curl_error($this->ch)) {
							$this->status['error'][] = static::_('CURL_ERROR_MSG') . ': ' . curl_error($this->ch);
						} else {
							//we have to set the cookies now

							if (empty($this->options['logout'])) {
								$this->status['debug'][] = static::_('CURL_LOGIN_FINISHED');
								$this->setCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
							} else {
								$this->status['debug'][] = static::_('CURL_LOGOUT_FINISHED');
								$this->deleteCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
							}
						}
						curl_close($this->ch);
					}
				}
			}
		}
		return $this->status;
	}
395514
def request_sid_cookie(self, username, password):
        """"""
        log.debug("Requesting SID cookie")
        target_url = self._login_url + '?usr={0}&pwd={1}&persist=y'.format(
            username, password
        )
        cookie = urlopen(target_url).read()
        return cookie
926024
def set_cookie(self, key, value, expiration='Infinity', path='/', domain='', secure=False):
        

        secure = 'true' if secure else 'false'
        self.app_instance.execute_javascript("""
            var sKey = "%(sKey)s";
            var sValue = "%(sValue)s";
            var vEnd = eval("%(vEnd)s");
            var sPath = "%(sPath)s"; 
            var sDomain = "%(sDomain)s"; 
            var bSecure = %(bSecure)s;
            if( (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) == false ){
                var sExpires = "";
                if (vEnd) {
                    switch (vEnd.constructor) {
                        case Number:
                            sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
                        break;
                        case String:
                            sExpires = "; expires=" + vEnd;
                        break;
                        case Date:
                            sExpires = "; expires=" + vEnd.toUTCString();
                        break;
                    }
                }
                document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
            }
            """%{'sKey': key, 'sValue': value, 'vEnd': expiration, 'sPath': path, 'sDomain': domain, 'bSecure': secure})
1333207
def process_login(context, request):
    """"""
    username = request.json['username']
    password = request.json['password']

    # Do the password validation.
    user = context.authenticate(username, password)
    if not user:
        @request.after
        def adjust_status(response):
            response.status = 401
        return {
            'status': 'error',
            'error': {
                'code': 401,
                'message': 'Invalid Username / Password'
            }
        }

    @request.after
    def remember(response):
        """Remember the identity of the user logged in."""
        # We pass the extra info to the identity object.
        response.headers.add('Access-Control-Expose-Headers', 'Authorization')
        identity = user.identity
        request.app.remember_identity(response, request, identity)

    return {
        'status': 'success'
    }
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()
  })
}
980901
def set_cookie(self, cookie):
        """"""
        c = self._cookies
        self._cookies_lock.acquire()
        try:
            if cookie.domain not in c: c[cookie.domain] = {}
            c2 = c[cookie.domain]
            if cookie.path not in c2: c2[cookie.path] = {}
            c3 = c2[cookie.path]
            c3[cookie.name] = cookie
        finally:
            self._cookies_lock.release()