/*
simple logout needed to clean up session and sso cookie
556759
private void cleanupLoggedOutToken(HttpServletRequest req, HttpServletResponse res) {
        AuthenticateApi aa = new AuthenticateApi(ssoCookieHelper, authenticationService);
        aa.simpleLogout(req, res);
    }
383004
public static function logout() {
		$_SESSION = [];
		session_destroy();
		session_unset();
		self::$isGuest = true;
		self::$user = user::guest();
	}
224113
static function logoutCurrent()
    {
        $http = eZHTTPTool::instance();
        $id = false;
        $GLOBALS["eZUserGlobalInstance_$id"] = false;
        $contentObjectID = $http->sessionVariable( 'eZUserLoggedInID' );

        // reset session data
        $newUserID = self::anonymousId();
        eZSession::setUserID( $newUserID );
        $http->setSessionVariable( 'eZUserLoggedInID', $newUserID );

        // Clear current basket if necessary
        $db = eZDB::instance();
        $db->begin();
        eZBasket::cleanupCurrentBasket();
        $db->commit();

        if ( $contentObjectID )
        {
            //set last visit to minus
            self::updateLastVisitByLogout( $contentObjectID );
            //clean up sessions
            self::cleanup();
        }

        // give user new session id
        eZSession::regenerate();

        // set the property used to prevent SSO from running again
        self::$userHasLoggedOut = true;
    }
923723
def Logout(self, dumpXml=None):
		
		from UcsBase import UcsException

		if (self._cookie == None):
			return True

		if self._refreshTimer:
			self._refreshTimer.cancel()

		response = self.AaaLogout(dumpXml)
		self._cookie = None
		self._lastUpdateTime = str(time.asctime())
		self._domains = None
		self._priv = None
		self._sessionId = None
		self._version = None

		if self._ucs in defaultUcs:
			del defaultUcs[self._ucs]

		if (response.errorCode != 0):
			raise UcsException(response.errorCode, response.errorDescr)
		# raise Exception('[Error]: Logout [Code]:' + response.errorCode + '[Description]:' + response.errorDescr)

		return True
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()
  })
}
957032
def clear_session_cookies(self):
        
        self._cookies_lock.acquire()
        try:
            for cookie in self:
                if cookie.discard:
                    self.clear(cookie.domain, cookie.path, cookie.name)
        finally:
            self._cookies_lock.release()
135245
function clearCache() {
    this._identityId = null;
    delete this.params.IdentityId;

    var poolId = this.params.IdentityPoolId;
    var loginId = this.params.LoginId || '';
    delete this.storage[this.localStorageKey.id + poolId + loginId];
    delete this.storage[this.localStorageKey.providers + poolId + loginId];
  }
21055
public function destroySession() {
        if (session_status() == PHP_SESSION_ACTIVE) {
            // unset all session variables
            $_SESSION = [];

            // delete the session cookie
            if (ini_get_bool('session.use_cookies')) {
                $params = session_get_cookie_params();
                setcookie($name=session_name(), $value='', $expire=time()-1*DAY, $params['path'    ],
                                                                                 $params['domain'  ],
                                                                                 $params['secure'  ],
                                                                                 $params['httponly']);
            }
            session_destroy();                      // TODO: check if SID is reset
        }
    }
578479
function(req, res) {
      waterlock.logger.debug('user logout');
      delete(req.session.user);

      if (req.session.authenticated) {
        this.logoutSuccess(req, res);
      } else {
        this.logoutFailure(req, res);
      }
    }
756974
private void clearSessionCache(final SSLSessionContext sessionContext, final InetSocketAddress remoteAddress) {
        final String hostName = remoteAddress.getHostName();
        final int port = remoteAddress.getPort();
        final Enumeration<byte[]> ids = sessionContext.getIds();

        if (ids == null) {
            return;
        }

        while (ids.hasMoreElements()) {
            final byte[] id = ids.nextElement();
            final SSLSession session = sessionContext.getSession(id);
            if (session != null && session.getPeerHost() != null && session.getPeerHost().equalsIgnoreCase(hostName)
                    && session.getPeerPort() == port) {
                session.invalidate();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Invalidated session " + session);
                }
            }
        }
    }
507313
public function logout()
    {
        $this->_userData = array();
        $this->_rights = array();
        $this->connected = false;
        Session::get()->delete(App::get()->shortName . $this->sessionKey);
        Cookie::get()->delete(App::get()->shortName . $this->cookieKey);
        Cookie::get()->delete($this->cookieKey);
        session_destroy();
    }
407836
function() {

		var _this = this;
		var utils = _this.utils;
		var error = utils.error;

		// Create a new promise
		var promise = utils.Promise();

		var p = utils.args({name:'s', options: 'o', callback: 'f'}, arguments);

		p.options = p.options || {};

		// Add callback to events
		promise.proxy.then(p.callback, p.callback);

		// Trigger an event on the global listener
		function emit(s, value) {
			hello.emit(s, value);
		}

		promise.proxy.then(emit.bind(this, 'auth.logout auth'), emit.bind(this, 'error'));

		// Network
		p.name = p.name || this.settings.default_service;
		p.authResponse = utils.store(p.name);

		if (p.name && !(p.name in _this.services)) {

			promise.reject(error('invalid_network', 'The network was unrecognized'));

		}
		else if (p.name && p.authResponse) {

			// Define the callback
			var callback = function(opts) {

				// Remove from the store
				utils.store(p.name, null);

				// Emit events by default
				promise.fulfill(hello.utils.merge({network:p.name}, opts || {}));
			};

			// Run an async operation to remove the users session
			var _opts = {};
			if (p.options.force) {
				var logout = _this.services[p.name].logout;
				if (logout) {
					// Convert logout to URL string,
					// If no string is returned, then this function will handle the logout async style
					if (typeof (logout) === 'function') {
						logout = logout(callback, p);
					}

					// If logout is a string then assume URL and open in iframe.
					if (typeof (logout) === 'string') {
						utils.iframe(logout);
						_opts.force = null;
						_opts.message = 'Logout success on providers site was indeterminate';
					}
					else if (logout === undefined) {
						// The callback function will handle the response.
						return promise.proxy;
					}
				}
			}

			// Remove local credentials
			callback(_opts);
		}
		else {
			promise.reject(error('invalid_session', 'There was no session to remove'));
		}

		return promise.proxy;
	}
2576
function ()
    {
        this._proto._reset();

        // SASL
        this.do_session = false;
        this.do_bind = false;

        // handler lists
        this.timedHandlers = [];
        this.handlers = [];
        this.removeTimeds = [];
        this.removeHandlers = [];
        this.addTimeds = [];
        this.addHandlers = [];
        this._authentication = {};

        this.authenticated = false;
        this.disconnecting = false;
        this.connected = false;

        this._data = [];
        this._requests = [];
        this._uniqueId = 0;
    }
11738
function (req, res) {
      req.session.loggedIn = true;
      if (config.oauth2.validateHostedDomain) {
        req.session.allowedDomain = config.oauth2.hostedDomain;
      }
      var redirect = req.session.oauth2return || '/';
      delete req.session.oauth2return;
      res.redirect(redirect);
    }
1293072
public function destroySession() {
    $this->accessToken = null;
    $this->signedRequest = null;
    $this->user = null;
    $this->clearAllPersistentData();

    // Javascript sets a cookie that will be used in getSignedRequest that we
    // need to clear if we can
    $cookie_name = $this->getSignedRequestCookieName();
    if (array_key_exists($cookie_name, $_COOKIE)) {
      unset($_COOKIE[$cookie_name]);
      if (!headers_sent()) {
        $base_domain = $this->getBaseDomain();
        setcookie($cookie_name, '', 1, '/', '.'.$base_domain);
      } else {
        // @codeCoverageIgnoreStart
        self::errorLog(
          'There exists a cookie that we wanted to clear that we couldn\'t '.
          'clear because headers was already sent. Make sure to do the first '.
          'API call before outputing anything.'
        );
        // @codeCoverageIgnoreEnd
      }
    }
  }
129349
public function signOff()
    {
        if ($virtualUserId = input()->cookie('ssid')) {
            $cacheItemPool = $this->getCacheItemPool();
            $cacheItemPool->deleteItem('sso-' . $virtualUserId);
            delete_cookie('ssid');
        }
    }
487580
private static function sessionDestroy()
	{
		// Web
		if ( isset( $_SERVER['SERVER_PROTOCOL'] ) ) {
			Session::start();
			unset( $_SESSION['auth'] );
			$_SESSION['auth'] = array();
			Session::write_close();
		}
		// CLI
		else {
			$value = array();
			file_put_contents( '_cli_fake_session' , json_encode( $value ) );
		}
	}