def jwt_auth_auth_mocks(jti_length, jwt_algorithm, jwt_key_id, sub, sub_type, oauth, assertion, client_id, secret): # pylint:disable=redefined-outer-name with patch('jwt.encode') as jwt_encode: with patch('boxsdk.auth.jwt_auth.datetime') as mock_datetime: with patch('boxsdk.auth.jwt_auth.random.SystemRandom') as mock_system_random: jwt_encode.return_value = assertion mock_datetime.utcnow.return_value = datetime(2015, 7, 6, 12, 1, 2) mock_datetime.return_value = datetime(1970, 1, 1) now_plus_30 = mock_datetime.utcnow.return_value + timedelta(seconds=30) exp = int(total_seconds(now_plus_30 - datetime(1970, 1, 1))) system_random = mock_system_random.return_value system_random.randint.return_value = jti_length random_choices = [random.random() for _ in range(jti_length)] system_random.random.side_effect = random_choices ascii_alphabet = string.ascii_letters + string.digits ascii_len = len(ascii_alphabet) jti = ''.join(ascii_alphabet[int(r * ascii_len)] for r in random_choices) yield oauth system_random.randint.assert_called_once_with(16, 128) assert len(system_random.random.mock_calls) == jti_length jwt_encode.assert_called_once_with({ 'iss': client_id, 'sub': sub, 'box_sub_type': sub_type, 'aud': 'https://api.box.com/oauth2/token', 'jti': jti, 'exp': exp, }, secret, algorithm=jwt_algorithm, headers={'kid': jwt_key_id})
def _auth_with_jwt(self, sub, sub_type): """ Get an access token for use with Box Developer Edition. Pass an enterprise ID to get an enterprise token (which can be used to provision/deprovision users), or a user ID to get an app user token. :param sub: The enterprise ID or user ID to auth. :type sub: `unicode` :param sub_type: Either 'enterprise' or 'user' :type sub_type: `unicode` :return: The access token for the enterprise or app user. :rtype: `unicode` """ system_random = random.SystemRandom() jti_length = system_random.randint(16, 128) ascii_alphabet = string.ascii_letters + string.digits ascii_len = len(ascii_alphabet) jti = ''.join(ascii_alphabet[int(system_random.random() * ascii_len)] for _ in range(jti_length)) now_plus_30 = datetime.utcnow() + timedelta(seconds=30) assertion = jwt.encode( { 'iss': self._client_id, 'sub': sub, 'box_sub_type': sub_type, 'aud': 'https://api.box.com/oauth2/token', 'jti': jti, 'exp': int(total_seconds(now_plus_30 - datetime(1970, 1, 1))), }, self._rsa_private_key, algorithm=self._jwt_algorithm, headers={ 'kid': self._jwt_key_id, }, ) data = { 'grant_type': self._GRANT_TYPE, 'client_id': self._client_id, 'client_secret': self._client_secret, 'assertion': assertion, } if self._box_device_id: data['box_device_id'] = self._box_device_id if self._box_device_name: data['box_device_name'] = self._box_device_name return self.send_token_request(data, access_token=None, expect_refresh_token=False)[0]
def test_total_seconds(total_seconds_data): # pylint:disable=redefined-outer-name delta, seconds = total_seconds_data assert total_seconds(delta) == seconds