Refresh session's OAuth 2.0 credentials if they are stale.
430500
def refresh_oauth_credential(self):
        """"""
        credential = self.session.oauth2credential

        if credential.is_stale():
            refresh_session = refresh_access_token(credential)
            self.session = refresh_session
930836
def auth_expired(self):
        
        if self._auth and self._expires:
            now_with_skew = time.time() + AUTH_TOKEN_CLOCK_SKEW_MAX
            return now_with_skew > self._expires
        return True
479509
def authenticate(self):
        '''
        
        '''
        if "username" in self.options and "password" in self.options:
            self.login_oauth2(
                self.options["username"],
                self.options["password"],
                self.options.get('mfa_code'))
        elif "access_token" in self.options:
            if "refresh_token" in self.options:
                self.access_token = self.options["access_token"]
                self.refresh_token = self.options["refresh_token"]
                self.__set_account_info()
        else:
            self.authenticated = False
        return self.authenticated
193567
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    req.authClient = new googleapis.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET);
    req.authClient.credentials = req.session.googleCredentials;
    return next();
  }
  res.redirect('/');
}
617244
private void cleanupStaleClients() {
    LocalTime cleanupTime = LocalTime.now();
    LOG.debug("Starting cleanup authentication registry at {}", cleanupTime);
    // Get a list of stale clients under read lock.
    List<UUID> staleChannels = new ArrayList<>();
    for (Map.Entry<UUID, AuthenticatedChannelInfo> clientEntry : mChannels.entrySet()) {
      LocalTime lat = clientEntry.getValue().getLastAccessTime();
      if (lat.plusSeconds(mCleanupIntervalMs / 1000).isBefore(cleanupTime)) {
        staleChannels.add(clientEntry.getKey());
      }
    }

    // Unregister stale clients.
    LOG.debug("Found {} stale channels for cleanup.", staleChannels.size());
    for (UUID clientId : staleChannels) {
      unregisterChannel(clientId);
    }
    LOG.debug("Finished state channel cleanup at {}", LocalTime.now());
  }
187015
def _requires_refresh_token(self):
        
        expires_on = datetime.datetime.strptime(
            self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ')
        refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
        return expires_on < refresh
287472
def _do_refresh_session(self):
        """"""
        if self._session and self._last_session_refresh + self._loop_wait > time.time():
            return False

        if self._session:
            try:
                self._client.session.renew(self._session)
            except NotFound:
                self._session = None
        ret = not self._session
        if ret:
            try:
                self._session = self._client.session.create(name=self._scope + '-' + self._name,
                                                            checks=self.__session_checks,
                                                            lock_delay=0.001, behavior='delete')
            except InvalidSessionTTL:
                logger.exception('session.create')
                self.adjust_ttl()
                raise

        self._last_session_refresh = time.time()
        return ret
740859
def attempt_reauthorization(blink):
    """"""
    _LOGGER.info("Auth token expired, attempting reauthorization.")
    headers = blink.get_auth_token(is_retry=True)
    return headers
798294
def _refresh(self, **kwargs):
        """"""
        requests_params = self._handle_requests_params(kwargs)
        refresh_session = self._meta_data['bigip']._meta_data['icr_session']

        if self._meta_data['uri'].endswith('/stats/'):
            # Slicing off the trailing slash here for Stats enpoints because
            # iWorkflow doesn't consider those `stats` URLs valid if they
            # include the trailing slash.
            #
            # Other than that, functionality does not change
            uri = self._meta_data['uri'][0:-1]
        else:
            uri = self._meta_data['uri']

        response = refresh_session.get(uri, **requests_params)
        self._local_update(response.json())
95896
protected static function authenticate() :void {
		// if we did not authenticate before
		if(!self::$_account) {
			// search for an enabled account with that session key and a non expired session
			$account = \Models\Accounts::getFirstEnabledWithNonExpiredSession(
				// the session key
				Cook::get(Config::get('security', 'cookie'))
			);
			// if the cookie session key doesn't match any existing account session, we deny access
			$account ?: 
				self::refuse(
					'Your session is no longer valid', 
					403, true);
			// if the stored key and dynamically generated mismatch, we deny access
			$account->hasMatchingDynamicKey() ?: 
				self::refuse(
					'Your signature has changed since your last visit, please log-in again', 
					403, true);
			// if account has expired, we deny access
			!$account->hasItsValidityExpired() ?:
				self::refuse(
					"Your account has expired, it was valid until {$account->get('account_expiration_date')}", 
					403, true);
			// update our credentials
			self::$_account = $account;
			// set access as granted
			self::$_granted = true;
		}	
	}
770936
def flush(self):
        
        if 'dbcl2' not in self.cookies:
            return
        r = self.req(API_ACCOUNT_HOME)
        if RE_SESSION_EXPIRE.search(r.url):
            return self.expire()
        self.cookies.update(dict(r.cookies))
        self.user_alias = slash_right(r.url)
        self.logger.debug('flush with user_alias <%s>' % self.user_alias)
        return
1295695
protected void resumeSession (AuthRequest req, PresentsConnection conn)
    {
        // check to see if we've already got a connection object, in which case it's probably stale
        Connection oldconn = getConnection();
        if (oldconn != null && !oldconn.isClosed()) {
            log.info("Closing stale connection", "old", oldconn, "new", conn);
            // close the old connection (which results in everything being properly unregistered)
            oldconn.close();
        }

        // note our new auth request (so that we can deliver the proper bootstrap services)
        _areq = req;

        // start using the new connection
        setConnection(conn);

        // if a client connects, drops the connection and reconnects within the span of a very
        // short period of time, we'll find ourselves in resumeSession() before their client object
        // was resolved from the initial connection; in such a case, we can simply bail out here
        // and let the original session establishment code take care of initializing this resumed
        // session
        if (_clobj == null) {
            log.info("Rapid-fire reconnect caused us to arrive in resumeSession() before the " +
                     "original session resolved its client object " + this + ".");
            return;
        }

        // we need to get onto the dobj thread so that we can finalize resumption of the session
        _omgr.postRunnable(new Runnable() {
            public void run () {
                // now that we're on the dobjmgr thread we can resume our session resumption
                finishResumeSession();
            }
        });
    }
1136026
def refresh(self):
        """"""
        self._request_token(
            grant_type="password",
            username=self._username,
            password=self._password,
        )
1183510
def retry_on_bad_auth(func):
    """"""
    @wraps(func)
    def retry_version(self, *args, **kwargs):
        while True:
            try:
                return func(self, *args, **kwargs)
            except trolly.ResourceUnavailable:
                sys.stderr.write('bad request (refresh board id)\n')
                self._board_id = None
                self.save_key('board_id', None)
            except trolly.Unauthorised:
                sys.stderr.write('bad permissions (refresh token)\n')
                self._client = None
                self._token = None
                self.save_key('token', None)
    return retry_version
459148
function(creds) {
      var accessToken = creds['oauth2.accessToken'];
      var refreshToken = creds[StackMob.REFRESH_TOKEN_KEY];

      //Because the server sends back how long the credentials are valid for and not the expiration date, we construct the expiration date on the client side.  For the login scenario where we are using OAuth 2.0's redirect URL mechanism and where a user refreshes the logged-in redirected URL page, we don't want to incorrectly generate and save a new expiration date.  If the access token is the same, then leave the expiration date as is.
      //FIXME:  don't even pass in the expires value if we dont' intend to save it.  Move this logic out to handleOAuthCallback.  This check is happening too late down the line.
      if(this.Storage.retrieve('oauth2.accessToken') != accessToken) {
        this.Storage.persist('oauth2.expires', creds['oauth2.expires']);
      }

      this.Storage.persist('oauth2.accessToken', accessToken);
      this.Storage.persist(StackMob.REFRESH_TOKEN_KEY, refreshToken);
      this.Storage.persist('oauth2.macKey', creds['oauth2.macKey']);
      this.Storage.persist('oauth2.user', creds['oauth2.user']);
      this.Storage.persist('oauth2.userSchemaInfo', JSON.stringify(creds['oauth2.userSchemaInfo']));
    }
1125746
def refresh_token(self):
        
        if self.session is None:
            self.session = self.get_session()

        token = self.token_backend.token
        if token and token.is_long_lived:
            client_id, client_secret = self.auth
            token = Token(self.session.refresh_token(
                self._oauth2_token_url,
                client_id=client_id,
                client_secret=client_secret))
        else:
            log.error('You can not refresh an access token that has no "refreh_token" available.'
                      'Include "offline_access" scope when authentication to get a "refresh_token"')
            return False

        self.token_backend.token = token

        if self.store_token:
            self.token_backend.save_token()
        return True
786074
def change_authentication(self, client_id=None, client_secret=None,
                              access_token=None, refresh_token=None):
        """"""
        # TODO: Add error checking so you cannot change client_id and retain
        # access_token. Because that doesn't make sense.
        self.client_id = client_id or self.client_id
        self.client_secret = client_secret or self.client_secret
        self.access_token = access_token or self.access_token
        self.refresh_token = refresh_token or self.refresh_token