Get authorized and then continuously renew authorization before it expires

 @param [Integer, NilClass] wait time before attempt to renew; defaults to
   have the expiry time if authorized, otherwise 0

 @return [TrueClass] always true
769898
def renew_authorization(wait = nil)
      wait ||= (state == :authorized) ? ((@expires_at - Time.now).to_i / RENEW_FACTOR) : 0

      if @renew_timer && wait == 0
        @renew_timer.cancel
        @renew_timer = nil
      end

      unless @renew_timer
        @renew_timer = EM_S::Timer.new(wait) do
          @renew_timer = nil
          previous_state = state
          begin
            get_authorized
            renew_authorization
          rescue Exceptions::ConnectivityFailure => e
            if wait > 0
              renew_authorization([(wait * RENEW_FACTOR), MAX_RENEW_TIME].min)
            else
              renew_authorization(MIN_RENEW_TIME)
            end
          rescue BalancedHttpClient::NotResponding => e
            if (expires_in = (@expires_at - Time.now).to_i) > MIN_RENEW_TIME
              renew_authorization(expires_in / RENEW_FACTOR)
            else
              self.state = :expired
              reconnect
            end
          rescue Exceptions::Unauthorized => e
            if previous_state == :unauthorized && wait > 0
              renew_authorization([(wait * RENEW_FACTOR), MAX_UNAUTHORIZED_RENEW_INTERVAL].min)
            else
              renew_authorization(UNAUTHORIZED_RENEW_INTERVAL)
            end
          rescue CommunicationModeSwitch => e
            ErrorTracker.log(self, "Failed authorization renewal", e, nil, :no_trace)
            self.state = :failed
          rescue Exception => e
            ErrorTracker.log(self, "Failed authorization renewal", e)
            self.state = :failed
          end
        end
      end
      true
    end
431256
def _make_authorization_grant_assertion(self):
        
        now = _helpers.utcnow()
        lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
        expiry = now + lifetime

        payload = {
            'iat': _helpers.datetime_to_secs(now),
            'exp': _helpers.datetime_to_secs(expiry),
            # The issuer must be the service account email.
            'iss': self._service_account_email,
            # The audience must be the auth token endpoint's URI
            'aud': self._token_uri,
            'scope': _helpers.scopes_to_string(self._scopes or ())
        }

        payload.update(self._additional_claims)

        # The subject can be a user email for domain-wide delegation.
        if self._subject:
            payload.setdefault('sub', self._subject)

        token = jwt.encode(self._signer, payload)

        return token
449963
def renew_self(increment = 0, options = {})
      headers = extract_headers!(options)
      json = client.put("/v1/auth/token/renew-self", JSON.fast_generate(
        increment: increment,
      ), headers)
      return Secret.decode(json)
    end
761613
def index_authorize
        if !::Authorization::Fbuser::V1::User.index?(current_user)
          render :json => {errors: "User is not authorized for this action"}, status: :forbidden
        end
      end
336830
function authorized (req, res) {
  const { params, uppy } = req
  const providerName = params.providerName

  if (!uppy.providerTokens || !uppy.providerTokens[providerName]) {
    return res.json({ authenticated: false })
  }

  const token = uppy.providerTokens[providerName]
  uppy.provider.list({ token, uppy }, (err, response, body) => {
    const notAuthenticated = Boolean(err)
    if (notAuthenticated) {
      logger.debug(`${providerName} failed authorizarion test err:${err}`, 'provider.auth.check')
    }
    return res.json({ authenticated: !notAuthenticated })
  })
}
984855
def expired? connection
    return true  if     @max_requests && connection.requests >= @max_requests
    return false unless @idle_timeout
    return true  if     @idle_timeout.zero?

    Time.now - connection.last_use > @idle_timeout
  end
432786
def authenticate!
      access_token = get_access_token
    
      if @client.authorized?
        session[:access_token] = access_token.token
        session[:secret_token] = access_token.secret
        session[:user] = @client.info

        session[:user]
      else
        nil
      end
    end
783368
def activate(options = {})
      options = options.merge(
        user_name: @user_name,
        access_key_id: @id,
        status: "Active"
      )
      resp = @client.update_access_key(options)
      resp.data
    end
904464
def authorized_handler(self, f):
        
        @functools.wraps(f)
        def decorated():
            resp = self._handle_authorize_response()
            return f(resp)
        self._authorized_handler = decorated
        return decorated
457729
def extended(self):
        """"""
        if self.expires_at:
            return self.expires_at - self.issued_at > timedelta(days=30)
        else:
            return False
907480
def update_attributes_from_token(access_token)
        @expires_at               = Time.now + access_token.params[:oauth_expires_in].to_i
        @authorization_expires_at = Time.now + access_token.params[:oauth_authorization_expires_in].to_i
        @session_handle           = access_token.params[:oauth_session_handle]
        @atoken, @asecret         = access_token.token, access_token.secret
        @access_token             = nil
      end
187567
def authorize(self, req):
        
        try:
            version, account, container, obj = split_path(req.path, 1, 4, True)
        except ValueError:
            return HTTPNotFound(request=req)
        if not account or not account.startswith(self.reseller_prefix):
            return self.denied_response(req)
        user_groups = (req.remote_user or '').split(',')
        if '.reseller_admin' in user_groups and \
                account != self.reseller_prefix and \
                account[len(self.reseller_prefix)] != '.':
            req.environ['swift_owner'] = True
            return None
        if account in user_groups and \
                (req.method not in ('DELETE', 'PUT') or container):
            # If the user is admin for the account and is not trying to do an
            # account DELETE or PUT...
            req.environ['swift_owner'] = True
            return None
        if (req.environ.get('swift_sync_key') and
            req.environ['swift_sync_key'] ==
                req.headers.get('x-container-sync-key', None) and
            'x-timestamp' in req.headers and
            (req.remote_addr in self.allowed_sync_hosts or
             get_remote_client(req) in self.allowed_sync_hosts)):
            return None
        referrers, groups = parse_acl(getattr(req, 'acl', None))
        if referrer_allowed(req.referer, referrers):
            if obj or '.rlistings' in groups:
                return None
            return self.denied_response(req)
        if not req.remote_user:
            return self.denied_response(req)
        for user_group in user_groups:
            if user_group in groups:
                return None
        return self.denied_response(req)
1291350
def authorized_for?(obj)
      logger.debug("Checking to see if authorized to access object")
      if @auth_user.nil?
        # :nocov:
        return false
        # :nocov:
      elsif @auth_user.role >= Roles::ADMIN
        return true
      elsif obj.is_a? User
        return obj == @auth_user
      else
        return obj.try(:user) == @auth_user
      end
    end
387814
def authorize_for(opts = {})
      authorize! opts[:action], opts[:resource] if opts[:resource].present?
      authorize! opts[:action], opts[:object] if opts[:object].present?
    end
6657
def customer_active?(code = nil)
      subscription = customer_subscription(code)
      if subscription[:canceledDatetime] && subscription[:canceledDatetime] <= Time.now
        false
      else
        true
      end
    end
1178384
def expired?
      return false if @task.expires_after.blank?

      expire_duration.from_now(@scheduled_time) < Time.now.in_time_zone(@task.time_zone)
    end
730191
def authorize(action, subject)
      current_ability.authorize! action, subject
    rescue ::CanCan::AccessDenied
      Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
      raise Forbidden
    end