Use OAuth Tokens from Cache
427358
private function useOAuthTokenFromCache()
    {
        if (!$this->use_cache_token) {
            return;
        }

        $this->oauth_tokens = \Cache::get($this->getOauthTokensCacheKey(), []);
        if (!empty($this->oauth_tokens)) {
            $this->printLine("Using OAuth Tokens from cache:");
            $this->printArray($this->oauth_tokens);
        }
    }
1068927
def _exchange_refresh_tokens(self):
        ''
        if self.token_cache is not None and 'refresh' in self.token_cache:
            # Attempt to use the refresh token to get a new access token.
            refresh_form = {
                'grant_type': 'refresh_token',
                'refresh_token': self.token_cache['refresh'],
                'client_id': self.client_id,
                'client_secret': self.client_secret,
            }
            try:
                tokens = self._request_tokens_from_token_endpoint(refresh_form)
                tokens['refresh'] = self.token_cache['refresh']
                return tokens
            except OAuth2Exception:
                logging.exception(
                    'Encountered an exception during refresh token flow.')
        return None
1189299
async function fetchAndCache(cache, request) {
  const response = await fetch(request);
  cache.put(request, response.clone());
  return response;
}
868849
def _load_token_cache(self):
        ''
        try:
            logging.debug('About to read from local file cache file %s',
                          self.token_cache_file)
            with open(self.token_cache_file, 'rb') as f:
                fs_cached = cPickle.load(f)
                if self._check_token_cache_type(fs_cached):
                    logging.debug('Loaded from file system: %s', fs_cached)
                    return fs_cached
                else:
                    logging.warn('Found unexpected value in cache. %s',
                                 fs_cached)
                    return None
        except IOError:
            logging.debug(
                'Did not find file: %s on the file system.',
                self.token_cache_file)
            return None
        except:
            logging.info(
                'Encountered exception loading from the file system.',
                exc_info=True)
            return None
1214139
def get_cache_key(request, meta, orgaMode, currentOrga):
    """"""

    # Caching
    cacheKey = None

    if 'cache_time' in meta:
        if meta['cache_time'] > 0:

            # by default, no cache by user
            useUser = False

            # If a logged user in needed, cache the result by user
            if ('only_logged_user' in meta and meta['only_logged_user']) or \
                    ('only_member_user' in meta and meta['only_member_user']) or \
                    ('only_admin_user' in meta and meta['only_admin_user']) or \
                    ('only_orga_member_user' in meta and meta['only_orga_member_user']) or \
                    ('only_orga_admin_user' in meta and meta['only_orga_admin_user']):
                useUser = True

            # If a value if present in meta, use it
            if 'cache_by_user' in meta:
                useUser = meta['cache_by_user']

            cacheKey = '-'

            # Add user info if needed
            if useUser:
                cacheKey += str(request.user.pk) + 'usr-'

            # Add orga
            if orgaMode:
                cacheKey += str(currentOrga.pk) + 'org-'

            # Add current query
            cacheKey += request.get_full_path()

            # Add current template (if the template changed, cache must be invalided)
            cacheKey += meta['template_tag']

    return cacheKey
1257697
def _get_tokens_cached(self, cli):
        
        return self._token_cache.get(
            cli.render_counter, lambda: self.get_tokens(cli))
103565
def _save_token_cache(self, new_cache):
        ''
        logging.debug('Looking to write to local authentication cache...')
        if not self._check_token_cache_type(new_cache):
            logging.error('Attempt to save a bad value: %s', new_cache)
            return
        try:
            logging.debug('About to write to fs cache file: %s',
                          self.token_cache_file)
            with open(self.token_cache_file, 'wb') as f:
                cPickle.dump(new_cache, f, protocol=cPickle.HIGHEST_PROTOCOL)
                logging.debug('Finished dumping cache_value to fs cache file.')
        except:
            logging.exception(
                'Could not successfully cache OAuth2 secrets on the file '
                'system.')
775483
function getUserForToken(decodedToken) {
        var userId = decodedToken._id;
        var authToken = decodedToken.authToken;
        var cacheKey = userId + authToken;
        var conditions = {
            caller: userService.admin,
            where: { _id: userId, authToken: authToken, status: 'created' },
            findOne: true
        };
        var cachedUser;

        // if no user id or authToken, then no user
        if (!userId || !authToken) { return null; }

        // try to get user from cache, then DB
        return userCacheService.get({ key: cacheKey })
            .then(function (user) {
                cachedUser = user;
                return user ? user : userService.find(conditions);
            })
            .then(function (user) {

                // if user found in database, but not in cache, save in cache
                if (user && !cachedUser) {
                    userCacheService.set({ key: cacheKey, value: user });
                }

                // return the user
                return user;
            });
    }
716762
protected function getTokenFromCache()
    {
        if (!$this->cache || !$this->cache->hasItem(self::TOKEN_CACHE_KEY)) {
            return null;
        }

        /** @var Token $token */
        $token = $this->cache->getItem(self::TOKEN_CACHE_KEY)->get();

        if (!$token || !$token->getAuth()) {
            $this->logger->debug('No token in cache or auth is empty, returning null.');

            return null;
        }

        // invalidate token
        if ($this->isTokenExpired($token)) {
            $this->logger->debug('Token is expired.');

            $this->writeTokenInfoToDebugLog();

            return null;
        }

        return $token;
    }
550191
def mk_token(self, load):
        '''
        
        '''
        token = self.loadauth.mk_token(load)
        if not token:
            log.warning('Authentication failure of type "eauth" occurred.')
            return ''
        return token
7708
def _get_token(self, oauth_request, token_type='access'):
        """"""
        token_field = oauth_request.get_parameter('oauth_token')
        token = self.data_store.lookup_token(token_type, token_field)
        if not token:
            raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
        return token
584406
def oauth_request(self):
        
        # get tokens from server and make a dict of them.
        self._server_tokens = self.request_token()

        self.store["oauth-request-token"] = self._server_tokens["token"]
        self.store["oauth-request-secret"] = self._server_tokens["token_secret"]

        # now we need the user to authorize me to use their pump.io account
        result = self.verifier_callback(self.construct_oauth_url())
        if result is not None:
            self.verifier(result)
1359913
def core_oauth_token_create(self, data, **kwargs):
        ""
        api_path = "/oauth/tokens"
        return self.call(api_path, method="POST", data=data, **kwargs)
1225256
def get_authentication_tokens(self):
        
        callback_url = self.callback_url or 'oob'
        request_args = {}
        if OAUTH_LIB_SUPPORTS_CALLBACK:
            request_args['callback_url'] = callback_url

        resp, content = self.client.request(self.request_token_url,
            "GET", **request_args)

        if resp['status'] != '200':
            raise AuthError("Seems something couldn't be verified "\
                "withyour OAuth junk. Error: %s, Message: %s" \
                % (resp['status'], content))

        request_tokens = dict(urlparse.parse_qsl(content))
        oauth_callback_confirmed = request_tokens\
            .get('oauth_callback_confirmed') == 'true'

        if not OAUTH_LIB_SUPPORTS_CALLBACK and callback_url != 'oob'\
            and oauth_callback_confirmed:
            import warnings
            warnings.warn("oauth2 library doesn't support OAuth 1.0a"\
                " type callback, but remote requires it")
            oauth_callback_confirmed = False

        auth_url_params = {'oauth_token': request_tokens['oauth_token']}

        # Use old-style callback argument
        if callback_url != 'oob' and not oauth_callback_confirmed:
            auth_url_params['oauth_callback'] = callback_url

        request_tokens['auth_url'] = self.authenticate_url + '?'\
            + urllib.urlencode(auth_url_params)

        return request_tokens
1119839
def save_token(self, access_token):
        
        key = self._generate_cache_key(access_token.token)
        self.mc.set(key, access_token.__dict__)

        unique_token_key = self._unique_token_key(access_token.client_id,
                                                  access_token.grant_type,
                                                  access_token.user_id)
        self.mc.set(self._generate_cache_key(unique_token_key),
                    access_token.__dict__)

        if access_token.refresh_token is not None:
            rft_key = self._generate_cache_key(access_token.refresh_token)
            self.mc.set(rft_key, access_token.__dict__)
1217475
private function retrieveToken($scopes, $cacheKey)
  {
    $this->token = AppIdentityService::getAccessToken($scopes);
    if ($this->token) {
      $this->client->getCache()->set(
          $cacheKey,
          $this->token
      );
    }
  }
963980
def authenticate(self, client_id, client_secret, use_cache=True):
        
        # We will reuse a token for as long as we have one cached
        # and it hasn't expired.
        if use_cache:
            client = self._get_client_from_cache(client_id)
            if (client) and (not self.is_expired_token(client)):
                self.authenticated = True
                self.client = client
                return

        # Let's authenticate the client
        client = {
            'id': client_id,
            'secret': client_secret
        }

        res = self._authenticate_client(client_id, client_secret)
        client.update(res)

        expires = datetime.datetime.now() + \
                  datetime.timedelta(seconds=res['expires_in'])
        client['expires'] = expires.isoformat()

        # Cache it for repeated use until expired
        self._write_to_uaa_cache(client)

        self.client = client
        self.authenticated = True