本文整理汇总了Python中oauth2client._helpers._from_bytes函数的典型用法代码示例。如果您正苦于以下问题:Python _from_bytes函数的具体用法?Python _from_bytes怎么用?Python _from_bytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_from_bytes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
self.fake_model = tests_models.CredentialsModel()
self.fake_model_field = self.fake_model._meta.get_field('credentials')
self.field = models.CredentialsField(null=True)
self.credentials = client.Credentials()
self.pickle_str = _helpers._from_bytes(
base64.b64encode(pickle.dumps(self.credentials)))
self.jsonpickle_str = _helpers._from_bytes(
base64.b64encode(jsonpickle.encode(self.credentials).encode()))
示例2: _refresh
def _refresh(self, http_request):
"""Refreshes the access_token.
Skip all the storage hoops and just refresh using the API.
Args:
http_request: callable, a callable that matches the method
signature of httplib2.Http.request, used to make
the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
query = '?scope=%s' % urllib.parse.quote(self.scope, '')
uri = META.replace('{?scope}', query)
response, content = http_request(uri)
content = _from_bytes(content)
if response.status == 200:
try:
d = json.loads(content)
except Exception as e:
raise AccessTokenRefreshError(str(e))
self.access_token = d['accessToken']
else:
if response.status == 404:
content += (' This can occur if a VM was created'
' with no service account or scopes.')
raise AccessTokenRefreshError(content)
示例3: _get_metadata
def _get_metadata(http_request=None, path=None, recursive=True):
"""Gets a JSON object from the specified path on the Metadata Server
Args:
http_request: an httplib2.Http().request object or equivalent
with which to make the call to the metadata server
path: a list of strings denoting the metadata server request
path.
recursive: if true, returns a json blob of the entire tree below
this level. If false, return a list of child keys.
Returns:
A deserialized JSON object representing the data returned
from the metadata server
"""
if path is None:
path = []
if not http_request:
http_request = httplib2.Http().request
r_string = "/?recursive=true" if recursive else ""
full_path = _METADATA_ROOT + "/".join(path) + r_string
response, content = http_request(full_path, headers={"Metadata-Flavor": "Google"})
if response.status == http_client.OK:
decoded = _from_bytes(content)
if response["content-type"] == "application/json":
return json.loads(decoded)
else:
return decoded
else:
msg = (
"Failed to retrieve {path} from the Google Compute Engine" "metadata service. Response:\n{error}"
).format(path=full_path, error=response)
raise MetadataServerHttpError(msg)
示例4: from_string
def from_string(cls, key, password='notasecret'):
"""Construct an RsaSigner instance from a string.
Args:
key: string, private key in PEM format.
password: string, password for private key file. Unused for PEM
files.
Returns:
RsaSigner instance.
Raises:
ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in
PEM format.
"""
key = _from_bytes(key) # pem expects str in Py3
marker_id, key_bytes = pem.readPemBlocksFromFile(
six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)
if marker_id == 0:
pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes,
format='DER')
elif marker_id == 1:
key_info, remaining = decoder.decode(
key_bytes, asn1Spec=_PKCS8_SPEC)
if remaining != b'':
raise ValueError('Unused bytes', remaining)
pkey_info = key_info.getComponentByName('privateKey')
pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(),
format='DER')
else:
raise ValueError('No key could be detected.')
return cls(pkey)
示例5: get
def get(http, path, root=METADATA_ROOT, recursive=None):
"""Fetch a resource from the metadata server.
Args:
http: an object to be used to make HTTP requests.
path: A string indicating the resource to retrieve. For example,
'instance/service-accounts/default'
root: A string indicating the full path to the metadata server root.
recursive: A boolean indicating whether to do a recursive query of
metadata. See
https://cloud.google.com/compute/docs/metadata#aggcontents
Returns:
A dictionary if the metadata server returns JSON, otherwise a string.
Raises:
http_client.HTTPException if an error corrured while
retrieving metadata.
"""
url = urlparse.urljoin(root, path)
url = _helpers._add_query_parameter(url, 'recursive', recursive)
response, content = transport.request(
http, url, headers=METADATA_HEADERS)
if response.status == http_client.OK:
decoded = _helpers._from_bytes(content)
if response['content-type'] == 'application/json':
return json.loads(decoded)
else:
return decoded
else:
raise http_client.HTTPException(
'Failed to retrieve {0} from the Google Compute Engine'
'metadata service. Response:\n{1}'.format(url, response))
示例6: setUp
def setUp(self):
self.fake_model = FakeCredentialsModel()
self.fake_model_field = self.fake_model._meta.get_field('credentials')
self.field = CredentialsField(null=True)
self.credentials = Credentials()
self.pickle_str = _from_bytes(
base64.b64encode(pickle.dumps(self.credentials)))
示例7: test_validate_error
def test_validate_error(self):
payload = (
b"{"
b' "web": {'
b' "client_id": "[[CLIENT ID REQUIRED]]",'
b' "client_secret": "[[CLIENT SECRET REQUIRED]]",'
b' "redirect_uris": ["http://localhost:8080/oauth2callback"],'
b' "auth_uri": "",'
b' "token_uri": ""'
b" }"
b"}"
)
ERRORS = [
("{}", "Invalid"),
('{"foo": {}}', "Unknown"),
('{"web": {}}', "Missing"),
('{"web": {"client_id": "dkkd"}}', "Missing"),
(payload, "Property"),
]
for src, match in ERRORS:
# Ensure that it is unicode
src = _helpers._from_bytes(src)
# Test load(s)
with self.assertRaises(clientsecrets.InvalidClientSecretsError) as exc_manager:
clientsecrets.loads(src)
self.assertTrue(str(exc_manager.exception).startswith(match))
# Test loads(fp)
with self.assertRaises(clientsecrets.InvalidClientSecretsError) as exc_manager:
fp = StringIO(src)
clientsecrets.load(fp)
self.assertTrue(str(exc_manager.exception).startswith(match))
示例8: _refresh
def _refresh(self, http_request):
"""Refreshes the access_token.
Skip all the storage hoops and just refresh using the API.
Args:
http_request: callable, a callable that matches the method
signature of httplib2.Http.request, used to make
the refresh request.
Raises:
HttpAccessTokenRefreshError: When the refresh fails.
"""
query = '?scope=%s' % urllib.parse.quote(self.scope, '')
uri = META.replace('{?scope}', query)
response, content = http_request(
uri, headers={'Metadata-Flavor': 'Google'})
content = _from_bytes(content)
if response.status == http_client.OK:
try:
token_content = json.loads(content)
except Exception as e:
raise HttpAccessTokenRefreshError(str(e),
status=response.status)
self.access_token = token_content['access_token']
else:
if response.status == http_client.NOT_FOUND:
content += (' This can occur if a VM was created'
' with no service account or scopes.')
raise HttpAccessTokenRefreshError(content, status=response.status)
示例9: test_validate_error
def test_validate_error(self):
payload = (
b'{'
b' "web": {'
b' "client_id": "[[CLIENT ID REQUIRED]]",'
b' "client_secret": "[[CLIENT SECRET REQUIRED]]",'
b' "redirect_uris": ["http://localhost:8080/oauth2callback"],'
b' "auth_uri": "",'
b' "token_uri": ""'
b' }'
b'}')
ERRORS = [
('{}', 'Invalid'),
('{"foo": {}}', 'Unknown'),
('{"web": {}}', 'Missing'),
('{"web": {"client_id": "dkkd"}}', 'Missing'),
(payload, 'Property'),
]
for src, match in ERRORS:
# Ensure that it is unicode
src = _from_bytes(src)
# Test load(s)
try:
clientsecrets.loads(src)
self.fail(src + ' should not be a valid client_secrets file.')
except clientsecrets.InvalidClientSecretsError as e:
self.assertTrue(str(e).startswith(match))
# Test loads(fp)
try:
fp = StringIO(src)
clientsecrets.load(fp)
self.fail(src + ' should not be a valid client_secrets file.')
except clientsecrets.InvalidClientSecretsError as e:
self.assertTrue(str(e).startswith(match))
示例10: run
def run(self):
s = None
try:
# Do not set the timeout on the socket, leave it in the blocking
# mode as setting the timeout seems to cause spurious EAGAIN
# errors on OSX.
self._socket.settimeout(None)
s, unused_addr = self._socket.accept()
resp_buffer = ''
resp_1 = s.recv(6).decode()
nstr, extra = resp_1.split('\n', 1)
resp_buffer = extra
n = int(nstr)
to_read = n - len(extra)
if to_read > 0:
resp_buffer += _from_bytes(s.recv(to_read, socket.MSG_WAITALL))
if resp_buffer != CREDENTIAL_INFO_REQUEST_JSON:
self.bad_request = True
l = len(self.response)
s.sendall('{0}\n{1}'.format(l, self.response).encode())
finally:
# Will fail if s is None, but these tests never encounter
# that scenario.
s.close()
示例11: from_json
def from_json(cls, json_data):
"""Deserialize a JSON-serialized instance.
Inverse to :meth:`to_json`.
Args:
json_data: dict or string, Serialized JSON (as a string or an
already parsed dictionary) representing a credential.
Returns:
ServiceAccountCredentials from the serialized data.
"""
if not isinstance(json_data, dict):
json_data = json.loads(_helpers._from_bytes(json_data))
private_key_pkcs8_pem = None
pkcs12_val = json_data.get(_PKCS12_KEY)
password = None
if pkcs12_val is None:
private_key_pkcs8_pem = json_data['_private_key_pkcs8_pem']
signer = crypt.Signer.from_string(private_key_pkcs8_pem)
else:
# NOTE: This assumes that private_key_pkcs8_pem is not also
# in the serialized data. This would be very incorrect
# state.
pkcs12_val = base64.b64decode(pkcs12_val)
password = json_data['_private_key_password']
signer = crypt.Signer.from_string(pkcs12_val, password)
credentials = cls(
json_data['_service_account_email'],
signer,
scopes=json_data['_scopes'],
private_key_id=json_data['_private_key_id'],
client_id=json_data['client_id'],
user_agent=json_data['_user_agent'],
**json_data['_kwargs']
)
if private_key_pkcs8_pem is not None:
credentials._private_key_pkcs8_pem = private_key_pkcs8_pem
if pkcs12_val is not None:
credentials._private_key_pkcs12 = pkcs12_val
if password is not None:
credentials._private_key_password = password
credentials.invalid = json_data['invalid']
credentials.access_token = json_data['access_token']
credentials.token_uri = json_data['token_uri']
credentials.revoke_uri = json_data['revoke_uri']
token_expiry = json_data.get('token_expiry', None)
if token_expiry is not None:
credentials.token_expiry = datetime.datetime.strptime(
token_expiry, client.EXPIRY_FORMAT)
return credentials
示例12: test_from_string_pkcs8_extra_bytes
def test_from_string_pkcs8_extra_bytes(self):
key_bytes = self._load_pkcs8_key_bytes()
_, pem_bytes = pem.readPemBlocksFromFile(
six.StringIO(_from_bytes(key_bytes)),
_pure_python_crypt._PKCS8_MARKER)
with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode:
key_info, remaining = None, 'extra'
mock_decode.return_value = (key_info, remaining)
with self.assertRaises(ValueError):
RsaSigner.from_string(key_bytes)
# Verify mock was called.
mock_decode.assert_called_once_with(
pem_bytes, asn1Spec=_pure_python_crypt._PKCS8_SPEC)
示例13: from_json
def from_json(cls, s):
data = json.loads(_from_bytes(s))
credentials = cls(
service_account_id=data['_service_account_id'],
service_account_email=data['_service_account_email'],
private_key_id=data['_private_key_id'],
private_key_pkcs8_text=data['_private_key_pkcs8_text'],
scopes=[],
user_agent=data['_user_agent'])
credentials.invalid = data['invalid']
credentials.access_token = data['access_token']
token_expiry = data.get('token_expiry', None)
if token_expiry is not None:
credentials.token_expiry = datetime.datetime.strptime(
token_expiry, EXPIRY_FORMAT)
return credentials
示例14: verify_signed_jwt_with_certs
def verify_signed_jwt_with_certs(jwt, certs, audience=None):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
jwt: string, A JWT.
certs: dict, Dictionary where values of public keys in PEM format.
audience: string, The audience, 'aud', that this JWT should contain. If
None then the JWT's 'aud' parameter is not verified.
Returns:
dict, The deserialized JSON payload in the JWT.
Raises:
AppIdentityError: if any checks are failed.
"""
jwt = _helpers._to_bytes(jwt)
if jwt.count(b'.') != 2:
raise AppIdentityError(
'Wrong number of segments in token: {0}'.format(jwt))
header, payload, signature = jwt.split(b'.')
message_to_sign = header + b'.' + payload
signature = _helpers._urlsafe_b64decode(signature)
# Parse token.
payload_bytes = _helpers._urlsafe_b64decode(payload)
try:
payload_dict = json.loads(_helpers._from_bytes(payload_bytes))
except:
raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes))
# Verify that the signature matches the message.
_verify_signature(message_to_sign, signature, certs.values())
# Verify the issued at and created times in the payload.
_verify_time_range(payload_dict)
# Check audience.
_check_audience(payload_dict, audience)
return payload_dict
示例15: _write_credentials_file
def _write_credentials_file(credentials_file, credentials):
"""Writes credentials to a file.
Refer to :func:`_load_credentials_file` for the format.
Args:
credentials_file: An open file handle, must be read/write.
credentials: A dictionary mapping user-defined keys to an instance of
:class:`oauth2client.client.Credentials`.
"""
data = {"file_version": 2, "credentials": {}}
for key, credential in iteritems(credentials):
credential_json = credential.to_json()
encoded_credential = _helpers._from_bytes(base64.b64encode(_helpers._to_bytes(credential_json)))
data["credentials"][key] = encoded_credential
credentials_file.seek(0)
json.dump(data, credentials_file)
credentials_file.truncate()