Reinject token and consistency into requests.
554393
def token_middleware(ctx, get_response):
    
    async def middleware(request):
        params = request.setdefault('params', {})
        if params.get("token") is None:
            params['token'] = ctx.token
        return await get_response(request)
    return middleware
1024324
def request(self, method, url, data=None, headers=None, **kwargs):
        """"""
        # pylint: disable=arguments-differ
        # Requests has a ton of arguments to request, but only two
        # (method, url) are required. We pass through all of the other
        # arguments to super, so no need to exhaustively list them here.

        # Use a kwarg for this instead of an attribute to maintain
        # thread-safety.
        _credential_refresh_attempt = kwargs.pop(
            '_credential_refresh_attempt', 0)

        # Make a copy of the headers. They will be modified by the credentials
        # and we want to pass the original headers if we recurse.
        request_headers = headers.copy() if headers is not None else {}

        self.credentials.before_request(
            self._auth_request, method, url, request_headers)

        response = super(AuthorizedSession, self).request(
            method, url, data=data, headers=request_headers, **kwargs)

        # If the response indicated that the credentials needed to be
        # refreshed, then refresh the credentials and re-attempt the
        # request.
        # A stored token may expire between the time it is retrieved and
        # the time the request is made, so we may need to try twice.
        if (response.status_code in self._refresh_status_codes
                and _credential_refresh_attempt < self._max_refresh_attempts):

            _LOGGER.info(
                'Refreshing credentials due to a %s response. Attempt %s/%s.',
                response.status_code, _credential_refresh_attempt + 1,
                self._max_refresh_attempts)

            auth_request_with_timeout = functools.partial(
                self._auth_request, timeout=self._refresh_timeout)
            self.credentials.refresh(auth_request_with_timeout)

            # Recurse. Pass in the original headers, not our modified set.
            return self.request(
                method, url, data=data, headers=headers,
                _credential_refresh_attempt=_credential_refresh_attempt + 1,
                **kwargs)

        return response
510859
def process_request(self, req, resp):  # pylint: disable=unused-argument
        

        if req.path in (self.revoke_endpoint, self.token_endpoint):
            return

        try:
            token = self._get_token(req)
            self.auth_token(token)
        except (AuthRequired, InvalidAuthSyntax) as exc:
            if not self.optional:
                abort(exc)
        except AuthRejected as exc:
            if not self.optional:
                exc.headers = self._get_invalid_token_headers(exc.detail)
                abort(exc)
1306969
def refresh(self):
        """"""
        grant_type = "https://oauth.reddit.com/grants/installed_client"
        self._request_token(grant_type=grant_type, device_id=self._device_id)
1348313
def request(self, method, url, **kwargs):
        """"""
        user_token = kwargs.pop('token', self.token)
        token, secret, expires_at = self.parse_raw_token(user_token)
        if token is not None:
            params = kwargs.get('params', {})
            params['access_token'] = token
            kwargs['params'] = params
        return super(OAuth2Provider, self).request(method, url, **kwargs)
907778
def request(self, url, method='GET', params=None, data=None,
                expected_response_code=200):
        """"""
        url = "{0}/{1}".format(self._baseurl, url)

        if params is None:
            params = {}

        auth = {
            'u': self._username,
            'p': self._password
        }

        params.update(auth)

        if data is not None and not isinstance(data, str):
            data = json.dumps(data)

        retry = True
        _try = 0
        # Try to send the request more than once by default (see #103)
        while retry:
            try:
                response = session.request(
                    method=method,
                    url=url,
                    params=params,
                    data=data,
                    headers=self._headers,
                    verify=self._verify_ssl,
                    timeout=self._timeout
                )
                break
            except (requests.exceptions.ConnectionError,
                    requests.exceptions.Timeout):
                _try += 1
                if self._retries != 0:
                    retry = _try < self._retries
        else:
            raise requests.exceptions.ConnectionError

        if response.status_code == expected_response_code:
            return response
        else:
            raise InfluxDBClientError(response.content, response.status_code)
405759
def add_token_object(self, token):
        '''  '''
        token.sent = self  # take ownership of given token
        self.__tokens.append(token)
        return token
846419
def reindex(self, request):
    
    r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"])
    try:
        with SearchLock(r, timeout=30 * 60, blocking_timeout=30):
            p = urllib.parse.urlparse(request.registry.settings["elasticsearch.url"])
            client = elasticsearch.Elasticsearch(
                [urllib.parse.urlunparse(p[:2] + ("",) * 4)],
                verify_certs=True,
                ca_certs=certifi.where(),
                timeout=30,
                retry_on_timeout=True,
                serializer=serializer.serializer,
            )
            number_of_replicas = request.registry.get("elasticsearch.replicas", 0)
            refresh_interval = request.registry.get("elasticsearch.interval", "1s")

            # We use a randomly named index so that we can do a zero downtime reindex.
            # Essentially we'll use a randomly named index which we will use until all
            # of the data has been reindexed, at which point we'll point an alias at
            # our randomly named index, and then delete the old randomly named index.

            # Create the new index and associate all of our doc types with it.
            index_base = request.registry["elasticsearch.index"]
            random_token = binascii.hexlify(os.urandom(5)).decode("ascii")
            new_index_name = "{}-{}".format(index_base, random_token)
            doc_types = request.registry.get("search.doc_types", set())
            shards = request.registry.get("elasticsearch.shards", 1)

            # Create the new index with zero replicas and index refreshes disabled
            # while we are bulk indexing.
            new_index = get_index(
                new_index_name,
                doc_types,
                using=client,
                shards=shards,
                replicas=0,
                interval="-1",
            )
            new_index.create(wait_for_active_shards=shards)

            # From this point on, if any error occurs, we want to be able to delete our
            # in progress index.
            try:
                request.db.execute("SET statement_timeout = '600s'")

                for _ in parallel_bulk(
                    client, _project_docs(request.db), index=new_index_name
                ):
                    pass
            except:  # noqa
                new_index.delete()
                raise
            finally:
                request.db.rollback()
                request.db.close()

            # Now that we've finished indexing all of our data we can update the
            # replicas and refresh intervals.
            client.indices.put_settings(
                index=new_index_name,
                body={
                    "index": {
                        "number_of_replicas": number_of_replicas,
                        "refresh_interval": refresh_interval,
                    }
                },
            )

            # Point the alias at our new randomly named index and delete the old index.
            if client.indices.exists_alias(name=index_base):
                to_delete = set()
                actions = []
                for name in client.indices.get_alias(name=index_base):
                    to_delete.add(name)
                    actions.append({"remove": {"index": name, "alias": index_base}})
                actions.append({"add": {"index": new_index_name, "alias": index_base}})
                client.indices.update_aliases({"actions": actions})
                client.indices.delete(",".join(to_delete))
            else:
                client.indices.put_alias(name=index_base, index=new_index_name)
    except redis.exceptions.LockError as exc:
        raise self.retry(countdown=60, exc=exc)
992194
def clone_request(request, method):
    
    ret = Request(request=request._request,
                  parsers=request.parsers,
                  authenticators=request.authenticators,
                  negotiator=request.negotiator,
                  parser_context=request.parser_context)
    ret._data = request._data
    ret._files = request._files
    ret._full_data = request._full_data
    ret._content_type = request._content_type
    ret._stream = request._stream
    ret.method = method
    if hasattr(request, '_user'):
        ret._user = request._user
    if hasattr(request, '_auth'):
        ret._auth = request._auth
    if hasattr(request, '_authenticator'):
        ret._authenticator = request._authenticator
    if hasattr(request, 'accepted_renderer'):
        ret.accepted_renderer = request.accepted_renderer
    if hasattr(request, 'accepted_media_type'):
        ret.accepted_media_type = request.accepted_media_type
    if hasattr(request, 'version'):
        ret.version = request.version
    if hasattr(request, 'versioning_scheme'):
        ret.versioning_scheme = request.versioning_scheme
    return ret
249010
def create_token(self, request, **kwargs):
        

        data = {
            "content": self.get_object().id,
            "create_date": get_request_data(request)["create_date"],
            "expire_date": get_request_data(request)["expire_date"]
        }
        serializer = ObfuscatedUrlInfoSerializer(data=data)
        if not serializer.is_valid():
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST,
                content_type="application/json",
            )
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK, content_type="application/json")
1256532
public function updateRefreshToken(): void
    {

        tap($this->token, function ($token) {

            // If no API call was made, the client would never have
            // been instantiated and auth information never updated.
            if (is_null($this->client) || $this->public_call)
                return;

            $last_auth = $this->client->getAuthentication();

            $token->token = $last_auth->access_token ?? '-';
            $token->expires_on = $last_auth->token_expires;

            $token->save();
        });
    }
721471
def token_new():
    """"""
    form = TokenForm(request.form)
    form.scopes.choices = current_oauth2server.scope_choices()

    if form.validate_on_submit():
        t = Token.create_personal(
            form.data['name'], current_user.get_id(), scopes=form.scopes.data
        )
        db.session.commit()
        session['show_personal_access_token'] = True
        return redirect(url_for(".token_view", token_id=t.id))

    if len(current_oauth2server.scope_choices()) == 0:
        del(form.scopes)

    return render_template(
        "invenio_oauth2server/settings/token_new.html",
        form=form,
    )
923304
def update_by_token(self, token, **kwargs):
        
        _sid = self.handler.sid(token)
        return self.update(_sid, **kwargs)
1254516
def get_request_token(self, request, callback):
        """"""
        callback = force_text(request.build_absolute_uri(callback))
        try:
            response = self.request('post', self.request_token_url, oauth_callback=callback)
            response.raise_for_status()
        except RequestException as e:
            logger.error('Unable to fetch request token: {0}'.format(e))
            return None
        else:
            return response.text
1248356
def _refresh_token(self):
        

        # use basic auth with API key and secret
        client_auth = requests.auth.HTTPBasicAuth(self.api_key, self.api_secret)

        # make request
        post_data = {"grant_type": "client_credentials"}
        response = requests.post(self.auth, auth=client_auth, data=post_data, proxies=self.proxies)
        self.last_response = response

        # raise exception if status code indicates an error
        if 400 <= response.status_code < 600:
            message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
                                                              "Client" if response.status_code < 500 else "Server",
                                                              self._get_trace_id(response),
                                                              "unable to get token")
            raise HTTPError(message, response=response)

        # set token property to the received token
        self.token = response.json()["access_token"]
447111
def refresh():
    
    old_token = guard.read_token_from_header()
    new_token = guard.refresh_jwt_token(old_token)
    ret = {'access_token': new_token}
    return flask.jsonify(ret), 200
329633
def request(self, method, url, **kwargs):
        ""
        user_token = kwargs.pop('token', self.token)
        token, secret = self.parse_raw_token(user_token)
        callback = kwargs.pop('oauth_callback', None)
        verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
        oauth = OAuth1(
            resource_owner_key=token,
            resource_owner_secret=secret,
            client_key=self.provider.consumer_key,
            client_secret=self.provider.consumer_secret,
            verifier=verifier,
            callback_uri=callback,
        )
        kwargs['auth'] = oauth
        return super(OAuthClient, self).request(method, url, **kwargs)