TODO: decide if we want to renew the authorizations every time.
962103
def flush
      reports_to_flush = run_and_log_time('Getting the reports from Redis') do
        reports
      end

      run_and_log_time('Reporting to 3scale') { report(reports_to_flush) }

      # Ideally, we would like to ensure that once we start checking
      # authorizations, they have taken into account the reports that we just
      # performed. However, in 3scale, reports are asynchronous and the current
      # API does not provide a way to know whether a report has already been
      # processed.
      # For now, let's just wait a few seconds. This will greatly mitigate the
      # problem.
      run_and_log_time('Giving reports some time to be processed') do
        sleep(WAIT_TIME_REPORT_AUTH)
      end

      auths = run_and_log_time('Getting the auths from 3scale') do
        authorizations(reports_to_flush)
      end

      run_and_log_time('Renewing the auths in Redis') { renew(auths) }
    end
894164
public static boolean shouldBeUsed(String authMode) {
        return authMode != null &&
               (authMode.equalsIgnoreCase(AUTHMODE_SERVICE_ALL) || authMode.equalsIgnoreCase(AUTHMODE_SERVICE_ANY));
    }
498404
def renew_token(self):
        """"""
        url = _url_joiner(self._vault_url, 'v1/auth/token/renew-self')
        resp = requests.get(url, headers=self._headers)
        resp.raise_for_status()
        data = resp.json()
        if data.get('errors'):
            raise VaultException(u'Error renewing Vault token: {}'.format(data['errors']))
        return data
738185
@Subscribe
    @SneakyThrows
    public final synchronized void renew(final ShardingRuleChangedEvent shardingRuleChangedEvent) {
        dataSource = new ShardingDataSource(dataSource.getDataSourceMap(), new OrchestrationShardingRule(shardingRuleChangedEvent.getShardingRuleConfiguration(),
                dataSource.getDataSourceMap().keySet()), dataSource.getShardingContext().getShardingProperties().getProps());
    }
1225558
public synchronized void obtainAuthorization(Context context, ResponseListener listener, Object... params) {
        authorizationProcessManager.startAuthorizationProcess(context, listener);
    }
932898
def auth_as(self, user):
        """"""
        old_user = self._user
        self.auth(user)
        try:
            yield
        finally:
            self.auth(old_user)
1278636
def run_authorization_check
      if instance_authority_resource.is_a?(Array)
        # Array includes options; pass as separate args
        authorize_action_for(*instance_authority_resource, *authority_arguments)
      else
        # *resource would be interpreted as resource.to_a, which is wrong and
        # actually triggers a query if it's a Sequel model
        authorize_action_for(instance_authority_resource, *authority_arguments)
      end
    end
547231
@Override
    public void renew(Map<String, String> credentials, Map topologyConf) {
        renew(credentials, topologyConf, null);
    }
430500
def refresh_oauth_credential(self):
        """"""
        credential = self.session.oauth2credential

        if credential.is_stale():
            refresh_session = refresh_access_token(credential)
            self.session = refresh_session
273888
private static void renewCCTokenAsync(final Jwt jwt) {
        // Not expired yet, try to renew async but let requests use the old token.
        logger.trace("In renew window but token is not expired yet.");
        if(!jwt.isRenewing() || System.currentTimeMillis() > jwt.getEarlyRetryTimeout()) {
            jwt.setRenewing(true);
            jwt.setEarlyRetryTimeout(System.currentTimeMillis() + jwt.getEarlyRefreshRetryDelay());
            logger.trace("Retrieve token async is called while token is not expired yet");

            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

            executor.schedule(() -> {
                Result<Jwt> result = getCCTokenRemotely(jwt);
                if(result.isFailure()) {
                    // swallow the exception here as it is on a best effort basis.
                    logger.error("Async retrieve token error with status: {}", result.getError().toString());
                }
                //set renewing flag to false after response, doesn't matter if it's success or fail.
                jwt.setRenewing(false);
            }, 50, TimeUnit.MILLISECONDS);
            executor.shutdown();
        }
    }
578895
public function forAuthorization()
    {
        $this->router->group(['middleware' => ['web', 'auth']], function ($router) {
            $router->get('/authorize', [
                'uses' => 'AuthorizationController@authorize',
            ]);

            $router->post('/authorize', [
                'uses' => 'ApproveAuthorizationController@approve',
            ]);

            $router->delete('/authorize', [
                'uses' => 'DenyAuthorizationController@deny',
            ]);
        });
    }
462042
def renew(key, write = true, options = {})
      new_version = (Time.current.to_f * 10000).to_i
      seconds = options[:ttl] ? options[:ttl] + (rand(options[:ttl] / 2) * [1, -1].sample) : nil
      written = @store.write(key, new_version, {:expires_in => seconds})
      @on_write_failure.call(key) if !written && write && @on_write_failure
      RecordCache::Base.logger.debug{ "Version Store: renew #{key}: nil => #{new_version}" }
      new_version
    end
672053
protected function reauthorize()
    {
        $order = $this->getOrder();

        if ($order->getCapturedAmount() > 0) {
            $handler = $this->getReauthorizeHandler();
            try {
                $response = $handler->getPayPalResponse();

                $payment = oxNew(\OxidEsales\PayPalModule\Model\OrderPayment::class);
                $payment->setDate($this->getDate());
                $payment->setTransactionId($response->getAuthorizationId());
                $payment->setCorrelationId($response->getCorrelationId());
                $payment->setAction('re-authorization');
                $payment->setStatus($response->getPaymentStatus());

                $order->getPaymentList()->addPayment($payment);
            } catch (\OxidEsales\PayPalModule\Core\Exception\PayPalResponseException $e) {
                // Ignore PayPal response exceptions
            }
        }
    }
1178562
def is_authorization_expired(self):
        
        if not self.auth.token_expiration:
            return True
        return (datetime.datetime.utcnow() > self.auth.token_expiration)
919608
protected boolean shouldAuthorize(Authentication authentication) {
        Assert.state(getAccessDecisionManager() != null, "The AccessDecisionManager can not be null!");
        boolean authorize = false;
        try {
            if( authentication != null ) {
                Object securedObject = getSecuredObject();
                List<ConfigAttribute> cad = getConfigAttributeDefinition( securedObject );
                getAccessDecisionManager().decide( authentication, getSecuredObject(), cad );
                authorize = true;
            }
        } catch( AccessDeniedException e ) {
            // This means the secured objects should not be authorized
        }
        return authorize;
    }
376094
@Override
    public boolean renewCredentials ( String locationHint, Throwable error ) {
        Credentials cred = getCredentials();
        if ( cred instanceof SmbRenewableCredentials ) {
            SmbRenewableCredentials renewable = (SmbRenewableCredentials) cred;
            CredentialsInternal renewed = renewable.renew();
            if ( renewed != null ) {
                this.creds = renewed;
                return true;
            }
        }
        NtlmAuthenticator auth = NtlmAuthenticator.getDefault();
        if ( auth != null ) {
            NtlmPasswordAuthenticator newAuth = NtlmAuthenticator
                    .requestNtlmPasswordAuthentication(auth, locationHint, ( error instanceof SmbAuthException ) ? (SmbAuthException) error : null);
            if ( newAuth != null ) {
                this.creds = newAuth;
                return true;
            }
        }
        return false;
    }
295424
@Subscribe
    public synchronized void renew(final MasterSlaveRuleChangedEvent masterSlaveRuleChangedEvent) {
        if (getName().equals(masterSlaveRuleChangedEvent.getShardingSchemaName())) {
            masterSlaveRule = new OrchestrationMasterSlaveRule(masterSlaveRuleChangedEvent.getMasterSlaveRuleConfiguration());
        }
    }