コード例 #1
0
    def test_error_handling(self, requests_mock, mock_kwargs,
                            expected_exception):
        """Test that various errors are handled as expected."""
        requests_mock.post(
            f'{settings.STAFF_SSO_BASE_URL}o/introspect/',
            **mock_kwargs,
        )
        with pytest.raises(expected_exception.__class__) as excinfo:
            introspect_token('test-token')

        assert str(excinfo.value) == str(expected_exception)
コード例 #2
0
ファイル: auth.py プロジェクト: uktrade/data-hub-api
def _look_up_token(token, request) -> Tuple[Optional[dict], bool]:
    """
    Look up data about an access token.

    This first checks the cache, and falls back to querying Staff SSO if the token isn't cached.

    :returns: a 2-tuple of: (token data, was the token cached)
    """
    cached_token_data = get_token_data_from_cache(token)

    if cached_token_data:
        return cached_token_data, True

    try:
        introspection_data = introspect_token(token, request)
    except SSOInvalidTokenError:
        return None, False
    except SSORequestError:
        logger.exception('SSO introspection request failed')
        return None, False

    relative_expiry = _calculate_expiry(introspection_data['exp'])

    # This should not happen as expiry times should be in the future
    if relative_expiry <= 0:
        logger.warning('Introspected token has an expiry time in the past')
        return None, False

    cached_token_data = add_token_data_to_cache(
        token,
        introspection_data['username'],
        introspection_data['email_user_id'],
        relative_expiry,
    )
    return cached_token_data, False
コード例 #3
0
 def test_returns_validated_data(self, requests_mock):
     """Test that introspected token data is returned on success."""
     mock_data = {
         'active': True,
         'username': '******',
         'email_user_id': '*****@*****.**',
         'exp': 1584118925,
     }
     requests_mock.post(
         f'{settings.STAFF_SSO_BASE_URL}o/introspect/',
         json=mock_data,
     )
     assert introspect_token('test-token') == mock_data
     assert requests_mock.last_request.text == 'token=test-token'
コード例 #4
0
def _look_up_token(token) -> Tuple[Optional[dict], bool]:
    """
    Look up data about an access token.

    This first checks the cache, and falls back to querying Staff SSO if the token isn't cached.

    :returns: a 2-tuple of: (token data, was the token cached)
    """
    cache_key = f'access_token:{token}'
    cached_token_data = cache.get(cache_key)

    if cached_token_data:
        return cached_token_data, True

    try:
        token_data = introspect_token(token)
    except SSOTokenDoesNotExist:
        return None, False
    except SSORequestError:
        logger.exception('SSO introspection request failed')
        return None, False

    # This should not be possible as all valid tokens should be active
    if not token_data['active']:
        logger.warning('Introspected token was inactive')
        return None, False

    relative_expiry = _calculate_expiry(token_data['exp'])

    # This should not happen as expiry times should be in the future
    if relative_expiry <= 0:
        logger.warning('Introspected token has an expiry time in the past')
        return None, False

    cache.set(cache_key, token_data, timeout=relative_expiry)

    return token_data, False