Decorator to check if Smappee's access token has expired.
    If it has, use the refresh token to request a new access token
355138
def authenticated(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        if self.refresh_token is not None and \
           self.token_expiration_time <= dt.datetime.utcnow():
            self.re_authenticate()
        return func(*args, **kwargs)
    return wrapper
709779
def verify_refresh_token(self, expired_token) -> bool:
        
        try:
            decoded_token = jwt.decode(
                Security.decrypt(expired_token),
                self.app_secret,
                options={'verify_exp': False})
            if 'refresh_token' in decoded_token and \
                    decoded_token['refresh_token'] is not None:
                try:
                    jwt.decode(decoded_token['refresh_token'], self.app_secret)
                    self.data = decoded_token
                    return True
                except (Exception, BaseException) as error:
                    self.errors.append(error)
                    return False
        except (Exception, BaseException) as error:
            self.errors.append(error)
            return False
        return False
1066081
def is_authenticated(self):
        
        token = self.con.token_backend.token
        if not token:
            token = self.con.token_backend.get_token()

        return token is not None and not token.is_expired
1179139
def get_expired(self):
        
        max_age = timezone.now() - timedelta(seconds=app_settings.ESI_TOKEN_VALID_DURATION)
        return self.filter(created__lte=max_age)
196459
def _do_refresh_request(self, unused_http_request):
        
        relative_url = 'instance/service-accounts/{0}/token'.format(
            self.__service_account_name)
        try:
            response = _GceMetadataRequest(relative_url)
        except exceptions.CommunicationError:
            self.invalid = True
            if self.store:
                self.store.locked_put(self)
            raise
        content = response.read()
        try:
            credential_info = json.loads(content)
        except ValueError:
            raise exceptions.CredentialsError(
                'Could not parse response as JSON: %s' % content)

        self.access_token = credential_info['access_token']
        if 'expires_in' in credential_info:
            expires_in = int(credential_info['expires_in'])
            self.token_expiry = (
                datetime.timedelta(seconds=expires_in) +
                datetime.datetime.utcnow())
        else:
            self.token_expiry = None
        self.invalid = False
        if self.store:
            self.store.locked_put(self)
1070627
def check_token(self, token: 'RedisEphemeralTokens') -> bool:
        
        if self.get_state() is None:  # Token expired
            return False

        correct_token = self.make_token(self)
        self.clear()
        return constant_time_compare(correct_token, token)
1178562
def is_authorization_expired(self):
        
        if not self.auth.token_expiration:
            return True
        return (datetime.datetime.utcnow() > self.auth.token_expiration)
448381
def jwt_refresh_token_required(fn):
    
    @wraps(fn)
    def wrapper(*args, **kwargs):
        verify_jwt_refresh_token_in_request()
        return fn(*args, **kwargs)
    return wrapper
875336
def is_expired(self, token, when=0):
        
        verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg])
        _payload = verifier.unpack(token)
        return is_expired(_payload['exp'], when)
647791
def access_token(self) -> str:
        
        if self._token_expires_at < time.time() + self._REFRESH_THRESHOLD:
            self.request_token()

        return self._token["access_token"]
649585
def on_expired(self):
        """"""

        print('Authentication expired')

        # Authentication expired
        self.is_authenticating.acquire()
        self.is_authenticating.notify_all()
        self.is_authenticating.release()
1135530
def _refresh_authentication_token(self):
        
        if self.retry == self._MAX_RETRIES:
            raise GeocoderAuthenticationFailure(
                'Too many retries for auth: %s' % self.retry
            )
        token_request_arguments = {
            'username': self.username,
            'password': self.password,
            'referer': self.referer,
            'expiration': self.token_lifetime,
            'f': 'json'
        }
        url = "?".join((self.auth_api, urlencode(token_request_arguments)))
        logger.debug(
            "%s._refresh_authentication_token: %s",
            self.__class__.__name__, url
        )
        self.token_expiry = int(time()) + self.token_lifetime
        response = self._base_call_geocoder(url)
        if 'token' not in response:
            raise GeocoderAuthenticationFailure(
                'Missing token in auth request.'
                'Request URL: %s; response JSON: %s' %
                (url, json.dumps(response))
            )
        self.retry = 0
        self.token = response['token']
401357
def use_refresh_token(self, refresh_token, scope=None):
        # type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]]
        

        if refresh_token not in self.refresh_tokens:
            raise InvalidRefreshToken('{} unknown'.format(refresh_token))

        refresh_token_info = self.refresh_tokens[refresh_token]
        if 'exp' in refresh_token_info and refresh_token_info['exp'] < int(time.time()):
            raise InvalidRefreshToken('{} has expired'.format(refresh_token))

        authz_info = self.access_tokens[refresh_token_info['access_token']]

        if scope:
            if not requested_scope_is_allowed(scope, authz_info['granted_scope']):
                logger.debug('trying to refresh token with superset scope, requested_scope=%s, granted_scope=%s',
                             scope, authz_info['granted_scope'])
                raise InvalidScope('Requested scope includes non-granted value')
            scope = ' '.join(scope)
            logger.debug('refreshing token with new scope, old_scope=%s -> new_scope=%s', authz_info['scope'], scope)
        else:
            # OAuth 2.0: scope: "[...] if omitted is treated as equal to the scope originally granted by the resource owner"
            scope = authz_info['granted_scope']

        new_access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],
                                                     authz_info['granted_scope'], scope)

        new_refresh_token = None
        if self.refresh_token_threshold \
                and 'exp' in refresh_token_info \
                and refresh_token_info['exp'] - int(time.time()) < self.refresh_token_threshold:
            # refresh token is close to expiry, issue a new one
            new_refresh_token = self.create_refresh_token(new_access_token.value)
        else:
            self.refresh_tokens[refresh_token]['access_token'] = new_access_token.value

        logger.debug('refreshed tokens, new_access_token=%s new_refresh_token=%s old_refresh_token=%s',
                     new_access_token, new_refresh_token, refresh_token)
        return new_access_token, new_refresh_token
513011
def renew_access_token(self):
        
        auth_params = {'REFRESH_TOKEN': self.refresh_token}
        self._add_secret_hash(auth_params, 'SECRET_HASH')
        refresh_response = self.client.initiate_auth(
            ClientId=self.client_id,
            AuthFlow='REFRESH_TOKEN',
            AuthParameters=auth_params,
        )

        self._set_attributes(
            refresh_response,
            {
                'access_token': refresh_response['AuthenticationResult']['AccessToken'],
                'id_token': refresh_response['AuthenticationResult']['IdToken'],
                'token_type': refresh_response['AuthenticationResult']['TokenType']
            }
        )
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
1207516
def get_requester(self):
        
        # TODO(abrahms): Perhaps pull this out into a factory function for
        # generating an EdxApi instance with the proper requester & credentials.
        session = requests.session()
        session.headers.update({
            'Authorization': 'Bearer {}'.format(self.credentials['access_token'])
        })

        old_request = session.request

        def patched_request(*args, **kwargs):
            """
            adds timeout param to session.request
            """
            return old_request(*args, timeout=self.timeout, **kwargs)

        session.request = patched_request
        return session
1324736
def refresh_access_token(self):
        
        if self.client_secret is None:
            raise Exception("client_secret must be set to execute "
                            "refresh_access_token.")
        if self.refresh_token is None:
            raise Exception("refresh_token must be set to execute "
                            "refresh_access_token.")
        params = {'client_id': self.client_id,
                  'client_secret': self.client_secret,
                  'grant_type': 'refresh_token',
                  'refresh_token': self.refresh_token}
        result = self._send_request(REFRESH_URL.format(self._base_url),
                                    params=params, method='POST',
                                    data_field=None)
        self.access_token = result['access_token']
        return self.access_token