id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,800 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/request_validator.py | RequestValidator.check_verifier | def check_verifier(self, verifier):
"""Checks that the verifier contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.verifier_length
return (set(verifier) <= self.safe_characters and
lower <= len(verifier) <= upper) | python | def check_verifier(self, verifier):
"""Checks that the verifier contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.verifier_length
return (set(verifier) <= self.safe_characters and
lower <= len(verifier) <= upper) | [
"def",
"check_verifier",
"(",
"self",
",",
"verifier",
")",
":",
"lower",
",",
"upper",
"=",
"self",
".",
"verifier_length",
"return",
"(",
"set",
"(",
"verifier",
")",
"<=",
"self",
".",
"safe_characters",
"and",
"lower",
"<=",
"len",
"(",
"verifier",
")",
"<=",
"upper",
")"
] | Checks that the verifier contains only safe characters
and is no shorter than lower and no longer than upper. | [
"Checks",
"that",
"the",
"verifier",
"contains",
"only",
"safe",
"characters",
"and",
"is",
"no",
"shorter",
"than",
"lower",
"and",
"no",
"longer",
"than",
"upper",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L190-L196 |
229,801 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/request_validator.py | RequestValidator.validate_timestamp_and_nonce | def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,
request, request_token=None, access_token=None):
"""Validates that the nonce has not been used before.
:param client_key: The client/consumer key.
:param timestamp: The ``oauth_timestamp`` parameter.
:param nonce: The ``oauth_nonce`` parameter.
:param request_token: Request token string, if any.
:param access_token: Access token string, if any.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:returns: True or False
Per `Section 3.3`_ of the spec.
"A nonce is a random string, uniquely generated by the client to allow
the server to verify that a request has never been made before and
helps prevent replay attacks when requests are made over a non-secure
channel. The nonce value MUST be unique across all requests with the
same timestamp, client credentials, and token combinations."
.. _`Section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
One of the first validation checks that will be made is for the validity
of the nonce and timestamp, which are associated with a client key and
possibly a token. If invalid then immediately fail the request
by returning False. If the nonce/timestamp pair has been used before and
you may just have detected a replay attack. Therefore it is an essential
part of OAuth security that you not allow nonce/timestamp reuse.
Note that this validation check is done before checking the validity of
the client and token.::
nonces_and_timestamps_database = [
(u'foo', 1234567890, u'rannoMstrInghere', u'bar')
]
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,
request_token=None, access_token=None):
return ((client_key, timestamp, nonce, request_token or access_token)
not in self.nonces_and_timestamps_database)
This method is used by
* AccessTokenEndpoint
* RequestTokenEndpoint
* ResourceEndpoint
* SignatureOnlyEndpoint
"""
raise self._subclass_must_implement("validate_timestamp_and_nonce") | python | def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,
request, request_token=None, access_token=None):
"""Validates that the nonce has not been used before.
:param client_key: The client/consumer key.
:param timestamp: The ``oauth_timestamp`` parameter.
:param nonce: The ``oauth_nonce`` parameter.
:param request_token: Request token string, if any.
:param access_token: Access token string, if any.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:returns: True or False
Per `Section 3.3`_ of the spec.
"A nonce is a random string, uniquely generated by the client to allow
the server to verify that a request has never been made before and
helps prevent replay attacks when requests are made over a non-secure
channel. The nonce value MUST be unique across all requests with the
same timestamp, client credentials, and token combinations."
.. _`Section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
One of the first validation checks that will be made is for the validity
of the nonce and timestamp, which are associated with a client key and
possibly a token. If invalid then immediately fail the request
by returning False. If the nonce/timestamp pair has been used before and
you may just have detected a replay attack. Therefore it is an essential
part of OAuth security that you not allow nonce/timestamp reuse.
Note that this validation check is done before checking the validity of
the client and token.::
nonces_and_timestamps_database = [
(u'foo', 1234567890, u'rannoMstrInghere', u'bar')
]
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,
request_token=None, access_token=None):
return ((client_key, timestamp, nonce, request_token or access_token)
not in self.nonces_and_timestamps_database)
This method is used by
* AccessTokenEndpoint
* RequestTokenEndpoint
* ResourceEndpoint
* SignatureOnlyEndpoint
"""
raise self._subclass_must_implement("validate_timestamp_and_nonce") | [
"def",
"validate_timestamp_and_nonce",
"(",
"self",
",",
"client_key",
",",
"timestamp",
",",
"nonce",
",",
"request",
",",
"request_token",
"=",
"None",
",",
"access_token",
"=",
"None",
")",
":",
"raise",
"self",
".",
"_subclass_must_implement",
"(",
"\"validate_timestamp_and_nonce\"",
")"
] | Validates that the nonce has not been used before.
:param client_key: The client/consumer key.
:param timestamp: The ``oauth_timestamp`` parameter.
:param nonce: The ``oauth_nonce`` parameter.
:param request_token: Request token string, if any.
:param access_token: Access token string, if any.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:returns: True or False
Per `Section 3.3`_ of the spec.
"A nonce is a random string, uniquely generated by the client to allow
the server to verify that a request has never been made before and
helps prevent replay attacks when requests are made over a non-secure
channel. The nonce value MUST be unique across all requests with the
same timestamp, client credentials, and token combinations."
.. _`Section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
One of the first validation checks that will be made is for the validity
of the nonce and timestamp, which are associated with a client key and
possibly a token. If invalid then immediately fail the request
by returning False. If the nonce/timestamp pair has been used before and
you may just have detected a replay attack. Therefore it is an essential
part of OAuth security that you not allow nonce/timestamp reuse.
Note that this validation check is done before checking the validity of
the client and token.::
nonces_and_timestamps_database = [
(u'foo', 1234567890, u'rannoMstrInghere', u'bar')
]
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,
request_token=None, access_token=None):
return ((client_key, timestamp, nonce, request_token or access_token)
not in self.nonces_and_timestamps_database)
This method is used by
* AccessTokenEndpoint
* RequestTokenEndpoint
* ResourceEndpoint
* SignatureOnlyEndpoint | [
"Validates",
"that",
"the",
"nonce",
"has",
"not",
"been",
"used",
"before",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L576-L625 |
229,802 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/parameters.py | prepare_grant_uri | def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,
scope=None, state=None, **kwargs):
"""Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the ``application/x-www-form-urlencoded`` format as defined by
[`W3C.REC-html401-19991224`_]:
:param uri:
:param client_id: The client identifier as described in `Section 2.2`_.
:param response_type: To indicate which OAuth 2 grant/flow is required,
"code" and "token".
:param redirect_uri: The client provided URI to redirect back to after
authorization as described in `Section 3.1.2`_.
:param scope: The scope of the access request as described by
`Section 3.3`_.
:param state: An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent
back to the client. The parameter SHOULD be used for
preventing cross-site request forgery as described in
`Section 10.12`_.
:param kwargs: Extra arguments to embed in the grant/authorization URL.
An example of an authorization code grant authorization URL:
.. code-block:: http
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
.. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224
.. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
.. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
params = [(('response_type', response_type)),
(('client_id', client_id))]
if redirect_uri:
params.append(('redirect_uri', redirect_uri))
if scope:
params.append(('scope', list_to_scope(scope)))
if state:
params.append(('state', state))
for k in kwargs:
if kwargs[k]:
params.append((unicode_type(k), kwargs[k]))
return add_params_to_uri(uri, params) | python | def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,
scope=None, state=None, **kwargs):
"""Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the ``application/x-www-form-urlencoded`` format as defined by
[`W3C.REC-html401-19991224`_]:
:param uri:
:param client_id: The client identifier as described in `Section 2.2`_.
:param response_type: To indicate which OAuth 2 grant/flow is required,
"code" and "token".
:param redirect_uri: The client provided URI to redirect back to after
authorization as described in `Section 3.1.2`_.
:param scope: The scope of the access request as described by
`Section 3.3`_.
:param state: An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent
back to the client. The parameter SHOULD be used for
preventing cross-site request forgery as described in
`Section 10.12`_.
:param kwargs: Extra arguments to embed in the grant/authorization URL.
An example of an authorization code grant authorization URL:
.. code-block:: http
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
.. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224
.. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
.. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
params = [(('response_type', response_type)),
(('client_id', client_id))]
if redirect_uri:
params.append(('redirect_uri', redirect_uri))
if scope:
params.append(('scope', list_to_scope(scope)))
if state:
params.append(('state', state))
for k in kwargs:
if kwargs[k]:
params.append((unicode_type(k), kwargs[k]))
return add_params_to_uri(uri, params) | [
"def",
"prepare_grant_uri",
"(",
"uri",
",",
"client_id",
",",
"response_type",
",",
"redirect_uri",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_secure_transport",
"(",
"uri",
")",
":",
"raise",
"InsecureTransportError",
"(",
")",
"params",
"=",
"[",
"(",
"(",
"'response_type'",
",",
"response_type",
")",
")",
",",
"(",
"(",
"'client_id'",
",",
"client_id",
")",
")",
"]",
"if",
"redirect_uri",
":",
"params",
".",
"append",
"(",
"(",
"'redirect_uri'",
",",
"redirect_uri",
")",
")",
"if",
"scope",
":",
"params",
".",
"append",
"(",
"(",
"'scope'",
",",
"list_to_scope",
"(",
"scope",
")",
")",
")",
"if",
"state",
":",
"params",
".",
"append",
"(",
"(",
"'state'",
",",
"state",
")",
")",
"for",
"k",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"k",
"]",
":",
"params",
".",
"append",
"(",
"(",
"unicode_type",
"(",
"k",
")",
",",
"kwargs",
"[",
"k",
"]",
")",
")",
"return",
"add_params_to_uri",
"(",
"uri",
",",
"params",
")"
] | Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the ``application/x-www-form-urlencoded`` format as defined by
[`W3C.REC-html401-19991224`_]:
:param uri:
:param client_id: The client identifier as described in `Section 2.2`_.
:param response_type: To indicate which OAuth 2 grant/flow is required,
"code" and "token".
:param redirect_uri: The client provided URI to redirect back to after
authorization as described in `Section 3.1.2`_.
:param scope: The scope of the access request as described by
`Section 3.3`_.
:param state: An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent
back to the client. The parameter SHOULD be used for
preventing cross-site request forgery as described in
`Section 10.12`_.
:param kwargs: Extra arguments to embed in the grant/authorization URL.
An example of an authorization code grant authorization URL:
.. code-block:: http
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
.. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224
.. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
.. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 | [
"Prepare",
"the",
"authorization",
"grant",
"request",
"URI",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L31-L87 |
229,803 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/parameters.py | prepare_token_request | def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs):
"""Prepare the access token request.
The client makes a request to the token endpoint by adding the
following parameters using the ``application/x-www-form-urlencoded``
format in the HTTP request entity-body:
:param grant_type: To indicate grant type being used, i.e. "password",
"authorization_code" or "client_credentials".
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra parameters. Default ''.
:param include_client_id: `True` (default) to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_.
:type include_client_id: Boolean
:param client_id: Unicode client identifier. Will only appear if
`include_client_id` is True. *
:param client_secret: Unicode client secret. Will only appear if set to a
value that is not `None`. Invoking this function with
an empty string will send an empty `client_secret`
value to the server. *
:param code: If using authorization_code grant, pass the previously
obtained authorization code as the ``code`` argument. *
:param redirect_uri: If the "redirect_uri" parameter was included in the
authorization request as described in
`Section 4.1.1`_, and their values MUST be identical. *
:param kwargs: Extra arguments to embed in the request body.
Parameters marked with a `*` above are not explicit arguments in the
function signature, but are specially documented arguments for items
appearing in the generic `**kwargs` keyworded input.
An example of an authorization code token request body:
.. code-block:: http
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
.. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1
"""
params = [('grant_type', grant_type)]
if 'scope' in kwargs:
kwargs['scope'] = list_to_scope(kwargs['scope'])
# pull the `client_id` out of the kwargs.
client_id = kwargs.pop('client_id', None)
if include_client_id:
if client_id is not None:
params.append((unicode_type('client_id'), client_id))
# the kwargs iteration below only supports including boolean truth (truthy)
# values, but some servers may require an empty string for `client_secret`
client_secret = kwargs.pop('client_secret', None)
if client_secret is not None:
params.append((unicode_type('client_secret'), client_secret))
# this handles: `code`, `redirect_uri`, and other undocumented params
for k in kwargs:
if kwargs[k]:
params.append((unicode_type(k), kwargs[k]))
return add_params_to_qs(body, params) | python | def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs):
"""Prepare the access token request.
The client makes a request to the token endpoint by adding the
following parameters using the ``application/x-www-form-urlencoded``
format in the HTTP request entity-body:
:param grant_type: To indicate grant type being used, i.e. "password",
"authorization_code" or "client_credentials".
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra parameters. Default ''.
:param include_client_id: `True` (default) to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_.
:type include_client_id: Boolean
:param client_id: Unicode client identifier. Will only appear if
`include_client_id` is True. *
:param client_secret: Unicode client secret. Will only appear if set to a
value that is not `None`. Invoking this function with
an empty string will send an empty `client_secret`
value to the server. *
:param code: If using authorization_code grant, pass the previously
obtained authorization code as the ``code`` argument. *
:param redirect_uri: If the "redirect_uri" parameter was included in the
authorization request as described in
`Section 4.1.1`_, and their values MUST be identical. *
:param kwargs: Extra arguments to embed in the request body.
Parameters marked with a `*` above are not explicit arguments in the
function signature, but are specially documented arguments for items
appearing in the generic `**kwargs` keyworded input.
An example of an authorization code token request body:
.. code-block:: http
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
.. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1
"""
params = [('grant_type', grant_type)]
if 'scope' in kwargs:
kwargs['scope'] = list_to_scope(kwargs['scope'])
# pull the `client_id` out of the kwargs.
client_id = kwargs.pop('client_id', None)
if include_client_id:
if client_id is not None:
params.append((unicode_type('client_id'), client_id))
# the kwargs iteration below only supports including boolean truth (truthy)
# values, but some servers may require an empty string for `client_secret`
client_secret = kwargs.pop('client_secret', None)
if client_secret is not None:
params.append((unicode_type('client_secret'), client_secret))
# this handles: `code`, `redirect_uri`, and other undocumented params
for k in kwargs:
if kwargs[k]:
params.append((unicode_type(k), kwargs[k]))
return add_params_to_qs(body, params) | [
"def",
"prepare_token_request",
"(",
"grant_type",
",",
"body",
"=",
"''",
",",
"include_client_id",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"[",
"(",
"'grant_type'",
",",
"grant_type",
")",
"]",
"if",
"'scope'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'scope'",
"]",
"=",
"list_to_scope",
"(",
"kwargs",
"[",
"'scope'",
"]",
")",
"# pull the `client_id` out of the kwargs.",
"client_id",
"=",
"kwargs",
".",
"pop",
"(",
"'client_id'",
",",
"None",
")",
"if",
"include_client_id",
":",
"if",
"client_id",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"(",
"unicode_type",
"(",
"'client_id'",
")",
",",
"client_id",
")",
")",
"# the kwargs iteration below only supports including boolean truth (truthy)",
"# values, but some servers may require an empty string for `client_secret`",
"client_secret",
"=",
"kwargs",
".",
"pop",
"(",
"'client_secret'",
",",
"None",
")",
"if",
"client_secret",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"(",
"unicode_type",
"(",
"'client_secret'",
")",
",",
"client_secret",
")",
")",
"# this handles: `code`, `redirect_uri`, and other undocumented params",
"for",
"k",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"k",
"]",
":",
"params",
".",
"append",
"(",
"(",
"unicode_type",
"(",
"k",
")",
",",
"kwargs",
"[",
"k",
"]",
")",
")",
"return",
"add_params_to_qs",
"(",
"body",
",",
"params",
")"
] | Prepare the access token request.
The client makes a request to the token endpoint by adding the
following parameters using the ``application/x-www-form-urlencoded``
format in the HTTP request entity-body:
:param grant_type: To indicate grant type being used, i.e. "password",
"authorization_code" or "client_credentials".
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra parameters. Default ''.
:param include_client_id: `True` (default) to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_.
:type include_client_id: Boolean
:param client_id: Unicode client identifier. Will only appear if
`include_client_id` is True. *
:param client_secret: Unicode client secret. Will only appear if set to a
value that is not `None`. Invoking this function with
an empty string will send an empty `client_secret`
value to the server. *
:param code: If using authorization_code grant, pass the previously
obtained authorization code as the ``code`` argument. *
:param redirect_uri: If the "redirect_uri" parameter was included in the
authorization request as described in
`Section 4.1.1`_, and their values MUST be identical. *
:param kwargs: Extra arguments to embed in the request body.
Parameters marked with a `*` above are not explicit arguments in the
function signature, but are specially documented arguments for items
appearing in the generic `**kwargs` keyworded input.
An example of an authorization code token request body:
.. code-block:: http
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
.. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 | [
"Prepare",
"the",
"access",
"token",
"request",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L90-L162 |
229,804 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/parameters.py | parse_authorization_code_response | def parse_authorization_code_response(uri, state=None):
"""Parse authorization grant response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an authorization code and delivers it to the client by
adding the following parameters to the query component of the
redirection URI using the ``application/x-www-form-urlencoded`` format:
**code**
REQUIRED. The authorization code generated by the
authorization server. The authorization code MUST expire
shortly after it is issued to mitigate the risk of leaks. A
maximum authorization code lifetime of 10 minutes is
RECOMMENDED. The client MUST NOT use the authorization code
more than once. If an authorization code is used more than
once, the authorization server MUST deny the request and SHOULD
revoke (when possible) all tokens previously issued based on
that authorization code. The authorization code is bound to
the client identifier and redirection URI.
**state**
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
:param uri: The full redirect URL back to the client.
:param state: The state parameter from the authorization request.
For example, the authorization server redirects the user-agent by
sending the following HTTP response:
.. code-block:: http
HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
&state=xyz
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
query = urlparse.urlparse(uri).query
params = dict(urlparse.parse_qsl(query))
if not 'code' in params:
raise MissingCodeError("Missing code parameter in response.")
if state and params.get('state', None) != state:
raise MismatchingStateError()
return params | python | def parse_authorization_code_response(uri, state=None):
"""Parse authorization grant response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an authorization code and delivers it to the client by
adding the following parameters to the query component of the
redirection URI using the ``application/x-www-form-urlencoded`` format:
**code**
REQUIRED. The authorization code generated by the
authorization server. The authorization code MUST expire
shortly after it is issued to mitigate the risk of leaks. A
maximum authorization code lifetime of 10 minutes is
RECOMMENDED. The client MUST NOT use the authorization code
more than once. If an authorization code is used more than
once, the authorization server MUST deny the request and SHOULD
revoke (when possible) all tokens previously issued based on
that authorization code. The authorization code is bound to
the client identifier and redirection URI.
**state**
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
:param uri: The full redirect URL back to the client.
:param state: The state parameter from the authorization request.
For example, the authorization server redirects the user-agent by
sending the following HTTP response:
.. code-block:: http
HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
&state=xyz
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
query = urlparse.urlparse(uri).query
params = dict(urlparse.parse_qsl(query))
if not 'code' in params:
raise MissingCodeError("Missing code parameter in response.")
if state and params.get('state', None) != state:
raise MismatchingStateError()
return params | [
"def",
"parse_authorization_code_response",
"(",
"uri",
",",
"state",
"=",
"None",
")",
":",
"if",
"not",
"is_secure_transport",
"(",
"uri",
")",
":",
"raise",
"InsecureTransportError",
"(",
")",
"query",
"=",
"urlparse",
".",
"urlparse",
"(",
"uri",
")",
".",
"query",
"params",
"=",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"query",
")",
")",
"if",
"not",
"'code'",
"in",
"params",
":",
"raise",
"MissingCodeError",
"(",
"\"Missing code parameter in response.\"",
")",
"if",
"state",
"and",
"params",
".",
"get",
"(",
"'state'",
",",
"None",
")",
"!=",
"state",
":",
"raise",
"MismatchingStateError",
"(",
")",
"return",
"params"
] | Parse authorization grant response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an authorization code and delivers it to the client by
adding the following parameters to the query component of the
redirection URI using the ``application/x-www-form-urlencoded`` format:
**code**
REQUIRED. The authorization code generated by the
authorization server. The authorization code MUST expire
shortly after it is issued to mitigate the risk of leaks. A
maximum authorization code lifetime of 10 minutes is
RECOMMENDED. The client MUST NOT use the authorization code
more than once. If an authorization code is used more than
once, the authorization server MUST deny the request and SHOULD
revoke (when possible) all tokens previously issued based on
that authorization code. The authorization code is bound to
the client identifier and redirection URI.
**state**
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
:param uri: The full redirect URL back to the client.
:param state: The state parameter from the authorization request.
For example, the authorization server redirects the user-agent by
sending the following HTTP response:
.. code-block:: http
HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
&state=xyz | [
"Parse",
"authorization",
"grant",
"response",
"URI",
"into",
"a",
"dict",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L223-L273 |
229,805 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/parameters.py | parse_implicit_response | def parse_implicit_response(uri, state=None, scope=None):
"""Parse the implicit token response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the ``application/x-www-form-urlencoded`` format:
**access_token**
REQUIRED. The access token issued by the authorization server.
**token_type**
REQUIRED. The type of the token issued as described in
Section 7.1. Value is case insensitive.
**expires_in**
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
**scope**
OPTIONAL, if identical to the scope requested by the client,
otherwise REQUIRED. The scope of the access token as described
by Section 3.3.
**state**
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
:param uri:
:param state:
:param scope:
Similar to the authorization code response, but with a full token provided
in the URL fragment:
.. code-block:: http
HTTP/1.1 302 Found
Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA
&state=xyz&token_type=example&expires_in=3600
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
fragment = urlparse.urlparse(uri).fragment
params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True))
for key in ('expires_in',):
if key in params: # cast things to int
params[key] = int(params[key])
if 'scope' in params:
params['scope'] = scope_to_list(params['scope'])
if 'expires_in' in params:
params['expires_at'] = time.time() + int(params['expires_in'])
if state and params.get('state', None) != state:
raise ValueError("Mismatching or missing state in params.")
params = OAuth2Token(params, old_scope=scope)
validate_token_parameters(params)
return params | python | def parse_implicit_response(uri, state=None, scope=None):
"""Parse the implicit token response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the ``application/x-www-form-urlencoded`` format:
**access_token**
REQUIRED. The access token issued by the authorization server.
**token_type**
REQUIRED. The type of the token issued as described in
Section 7.1. Value is case insensitive.
**expires_in**
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
**scope**
OPTIONAL, if identical to the scope requested by the client,
otherwise REQUIRED. The scope of the access token as described
by Section 3.3.
**state**
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
:param uri:
:param state:
:param scope:
Similar to the authorization code response, but with a full token provided
in the URL fragment:
.. code-block:: http
HTTP/1.1 302 Found
Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA
&state=xyz&token_type=example&expires_in=3600
"""
if not is_secure_transport(uri):
raise InsecureTransportError()
fragment = urlparse.urlparse(uri).fragment
params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True))
for key in ('expires_in',):
if key in params: # cast things to int
params[key] = int(params[key])
if 'scope' in params:
params['scope'] = scope_to_list(params['scope'])
if 'expires_in' in params:
params['expires_at'] = time.time() + int(params['expires_in'])
if state and params.get('state', None) != state:
raise ValueError("Mismatching or missing state in params.")
params = OAuth2Token(params, old_scope=scope)
validate_token_parameters(params)
return params | [
"def",
"parse_implicit_response",
"(",
"uri",
",",
"state",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"if",
"not",
"is_secure_transport",
"(",
"uri",
")",
":",
"raise",
"InsecureTransportError",
"(",
")",
"fragment",
"=",
"urlparse",
".",
"urlparse",
"(",
"uri",
")",
".",
"fragment",
"params",
"=",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"fragment",
",",
"keep_blank_values",
"=",
"True",
")",
")",
"for",
"key",
"in",
"(",
"'expires_in'",
",",
")",
":",
"if",
"key",
"in",
"params",
":",
"# cast things to int",
"params",
"[",
"key",
"]",
"=",
"int",
"(",
"params",
"[",
"key",
"]",
")",
"if",
"'scope'",
"in",
"params",
":",
"params",
"[",
"'scope'",
"]",
"=",
"scope_to_list",
"(",
"params",
"[",
"'scope'",
"]",
")",
"if",
"'expires_in'",
"in",
"params",
":",
"params",
"[",
"'expires_at'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"+",
"int",
"(",
"params",
"[",
"'expires_in'",
"]",
")",
"if",
"state",
"and",
"params",
".",
"get",
"(",
"'state'",
",",
"None",
")",
"!=",
"state",
":",
"raise",
"ValueError",
"(",
"\"Mismatching or missing state in params.\"",
")",
"params",
"=",
"OAuth2Token",
"(",
"params",
",",
"old_scope",
"=",
"scope",
")",
"validate_token_parameters",
"(",
"params",
")",
"return",
"params"
] | Parse the implicit token response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the ``application/x-www-form-urlencoded`` format:
**access_token**
REQUIRED. The access token issued by the authorization server.
**token_type**
REQUIRED. The type of the token issued as described in
Section 7.1. Value is case insensitive.
**expires_in**
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
**scope**
OPTIONAL, if identical to the scope requested by the client,
otherwise REQUIRED. The scope of the access token as described
by Section 3.3.
**state**
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
:param uri:
:param state:
:param scope:
Similar to the authorization code response, but with a full token provided
in the URL fragment:
.. code-block:: http
HTTP/1.1 302 Found
Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA
&state=xyz&token_type=example&expires_in=3600 | [
"Parse",
"the",
"implicit",
"token",
"response",
"URI",
"into",
"a",
"dict",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L276-L342 |
229,806 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/parameters.py | parse_token_response | def parse_token_response(body, scope=None):
"""Parse the JSON token response body into a dict.
The authorization server issues an access token and optional refresh
token, and constructs the response by adding the following parameters
to the entity body of the HTTP response with a 200 (OK) status code:
access_token
REQUIRED. The access token issued by the authorization server.
token_type
REQUIRED. The type of the token issued as described in
`Section 7.1`_. Value is case insensitive.
expires_in
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
refresh_token
OPTIONAL. The refresh token which can be used to obtain new
access tokens using the same authorization grant as described
in `Section 6`_.
scope
OPTIONAL, if identical to the scope requested by the client,
otherwise REQUIRED. The scope of the access token as described
by `Section 3.3`_.
The parameters are included in the entity body of the HTTP response
using the "application/json" media type as defined by [`RFC4627`_]. The
parameters are serialized into a JSON structure by adding each
parameter at the highest structure level. Parameter names and string
values are included as JSON strings. Numerical values are included
as JSON numbers. The order of parameters does not matter and can
vary.
:param body: The full json encoded response body.
:param scope: The scope requested during authorization.
For example:
.. code-block:: http
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
"example_parameter":"example_value"
}
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
.. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`RFC4627`: https://tools.ietf.org/html/rfc4627
"""
try:
params = json.loads(body)
except ValueError:
# Fall back to URL-encoded string, to support old implementations,
# including (at time of writing) Facebook. See:
# https://github.com/oauthlib/oauthlib/issues/267
params = dict(urlparse.parse_qsl(body))
for key in ('expires_in',):
if key in params: # cast things to int
params[key] = int(params[key])
if 'scope' in params:
params['scope'] = scope_to_list(params['scope'])
if 'expires_in' in params:
params['expires_at'] = time.time() + int(params['expires_in'])
params = OAuth2Token(params, old_scope=scope)
validate_token_parameters(params)
return params | python | def parse_token_response(body, scope=None):
"""Parse the JSON token response body into a dict.
The authorization server issues an access token and optional refresh
token, and constructs the response by adding the following parameters
to the entity body of the HTTP response with a 200 (OK) status code:
access_token
REQUIRED. The access token issued by the authorization server.
token_type
REQUIRED. The type of the token issued as described in
`Section 7.1`_. Value is case insensitive.
expires_in
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
refresh_token
OPTIONAL. The refresh token which can be used to obtain new
access tokens using the same authorization grant as described
in `Section 6`_.
scope
OPTIONAL, if identical to the scope requested by the client,
otherwise REQUIRED. The scope of the access token as described
by `Section 3.3`_.
The parameters are included in the entity body of the HTTP response
using the "application/json" media type as defined by [`RFC4627`_]. The
parameters are serialized into a JSON structure by adding each
parameter at the highest structure level. Parameter names and string
values are included as JSON strings. Numerical values are included
as JSON numbers. The order of parameters does not matter and can
vary.
:param body: The full json encoded response body.
:param scope: The scope requested during authorization.
For example:
.. code-block:: http
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
"example_parameter":"example_value"
}
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
.. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`RFC4627`: https://tools.ietf.org/html/rfc4627
"""
try:
params = json.loads(body)
except ValueError:
# Fall back to URL-encoded string, to support old implementations,
# including (at time of writing) Facebook. See:
# https://github.com/oauthlib/oauthlib/issues/267
params = dict(urlparse.parse_qsl(body))
for key in ('expires_in',):
if key in params: # cast things to int
params[key] = int(params[key])
if 'scope' in params:
params['scope'] = scope_to_list(params['scope'])
if 'expires_in' in params:
params['expires_at'] = time.time() + int(params['expires_in'])
params = OAuth2Token(params, old_scope=scope)
validate_token_parameters(params)
return params | [
"def",
"parse_token_response",
"(",
"body",
",",
"scope",
"=",
"None",
")",
":",
"try",
":",
"params",
"=",
"json",
".",
"loads",
"(",
"body",
")",
"except",
"ValueError",
":",
"# Fall back to URL-encoded string, to support old implementations,",
"# including (at time of writing) Facebook. See:",
"# https://github.com/oauthlib/oauthlib/issues/267",
"params",
"=",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"body",
")",
")",
"for",
"key",
"in",
"(",
"'expires_in'",
",",
")",
":",
"if",
"key",
"in",
"params",
":",
"# cast things to int",
"params",
"[",
"key",
"]",
"=",
"int",
"(",
"params",
"[",
"key",
"]",
")",
"if",
"'scope'",
"in",
"params",
":",
"params",
"[",
"'scope'",
"]",
"=",
"scope_to_list",
"(",
"params",
"[",
"'scope'",
"]",
")",
"if",
"'expires_in'",
"in",
"params",
":",
"params",
"[",
"'expires_at'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"+",
"int",
"(",
"params",
"[",
"'expires_in'",
"]",
")",
"params",
"=",
"OAuth2Token",
"(",
"params",
",",
"old_scope",
"=",
"scope",
")",
"validate_token_parameters",
"(",
"params",
")",
"return",
"params"
] | Parse the JSON token response body into a dict.
The authorization server issues an access token and optional refresh
token, and constructs the response by adding the following parameters
to the entity body of the HTTP response with a 200 (OK) status code:
access_token
REQUIRED. The access token issued by the authorization server.
token_type
REQUIRED. The type of the token issued as described in
`Section 7.1`_. Value is case insensitive.
expires_in
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
refresh_token
OPTIONAL. The refresh token which can be used to obtain new
access tokens using the same authorization grant as described
in `Section 6`_.
scope
OPTIONAL, if identical to the scope requested by the client,
otherwise REQUIRED. The scope of the access token as described
by `Section 3.3`_.
The parameters are included in the entity body of the HTTP response
using the "application/json" media type as defined by [`RFC4627`_]. The
parameters are serialized into a JSON structure by adding each
parameter at the highest structure level. Parameter names and string
values are included as JSON strings. Numerical values are included
as JSON numbers. The order of parameters does not matter and can
vary.
:param body: The full json encoded response body.
:param scope: The scope requested during authorization.
For example:
.. code-block:: http
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
"example_parameter":"example_value"
}
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
.. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`RFC4627`: https://tools.ietf.org/html/rfc4627 | [
"Parse",
"the",
"JSON",
"token",
"response",
"body",
"into",
"a",
"dict",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L345-L426 |
229,807 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/parameters.py | validate_token_parameters | def validate_token_parameters(params):
"""Ensures token precence, token type, expiration and scope in params."""
if 'error' in params:
raise_from_error(params.get('error'), params)
if not 'access_token' in params:
raise MissingTokenError(description="Missing access token parameter.")
if not 'token_type' in params:
if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):
raise MissingTokenTypeError()
# If the issued access token scope is different from the one requested by
# the client, the authorization server MUST include the "scope" response
# parameter to inform the client of the actual scope granted.
# https://tools.ietf.org/html/rfc6749#section-3.3
if params.scope_changed:
message = 'Scope has changed from "{old}" to "{new}".'.format(
old=params.old_scope, new=params.scope,
)
scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)
if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):
w = Warning(message)
w.token = params
w.old_scope = params.old_scopes
w.new_scope = params.scopes
raise w | python | def validate_token_parameters(params):
"""Ensures token precence, token type, expiration and scope in params."""
if 'error' in params:
raise_from_error(params.get('error'), params)
if not 'access_token' in params:
raise MissingTokenError(description="Missing access token parameter.")
if not 'token_type' in params:
if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):
raise MissingTokenTypeError()
# If the issued access token scope is different from the one requested by
# the client, the authorization server MUST include the "scope" response
# parameter to inform the client of the actual scope granted.
# https://tools.ietf.org/html/rfc6749#section-3.3
if params.scope_changed:
message = 'Scope has changed from "{old}" to "{new}".'.format(
old=params.old_scope, new=params.scope,
)
scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)
if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):
w = Warning(message)
w.token = params
w.old_scope = params.old_scopes
w.new_scope = params.scopes
raise w | [
"def",
"validate_token_parameters",
"(",
"params",
")",
":",
"if",
"'error'",
"in",
"params",
":",
"raise_from_error",
"(",
"params",
".",
"get",
"(",
"'error'",
")",
",",
"params",
")",
"if",
"not",
"'access_token'",
"in",
"params",
":",
"raise",
"MissingTokenError",
"(",
"description",
"=",
"\"Missing access token parameter.\"",
")",
"if",
"not",
"'token_type'",
"in",
"params",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'OAUTHLIB_STRICT_TOKEN_TYPE'",
")",
":",
"raise",
"MissingTokenTypeError",
"(",
")",
"# If the issued access token scope is different from the one requested by",
"# the client, the authorization server MUST include the \"scope\" response",
"# parameter to inform the client of the actual scope granted.",
"# https://tools.ietf.org/html/rfc6749#section-3.3",
"if",
"params",
".",
"scope_changed",
":",
"message",
"=",
"'Scope has changed from \"{old}\" to \"{new}\".'",
".",
"format",
"(",
"old",
"=",
"params",
".",
"old_scope",
",",
"new",
"=",
"params",
".",
"scope",
",",
")",
"scope_changed",
".",
"send",
"(",
"message",
"=",
"message",
",",
"old",
"=",
"params",
".",
"old_scopes",
",",
"new",
"=",
"params",
".",
"scopes",
")",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'OAUTHLIB_RELAX_TOKEN_SCOPE'",
",",
"None",
")",
":",
"w",
"=",
"Warning",
"(",
"message",
")",
"w",
".",
"token",
"=",
"params",
"w",
".",
"old_scope",
"=",
"params",
".",
"old_scopes",
"w",
".",
"new_scope",
"=",
"params",
".",
"scopes",
"raise",
"w"
] | Ensures token precence, token type, expiration and scope in params. | [
"Ensures",
"token",
"precence",
"token",
"type",
"expiration",
"and",
"scope",
"in",
"params",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L429-L455 |
229,808 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/clients/legacy_application.py | LegacyApplicationClient.prepare_request_body | def prepare_request_body(self, username, password, body='', scope=None,
include_client_id=False, **kwargs):
"""Add the resource owner password and username to the request body.
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format per `Appendix B`_ in the HTTP request entity-body:
:param username: The resource owner username.
:param password: The resource owner password.
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
:param scope: The scope of the access request as described by
`Section 3.3`_.
:param include_client_id: `True` to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param kwargs: Extra credentials to include in the token request.
If the client type is confidential or the client was issued client
credentials (or assigned other authentication requirements), the
client MUST authenticate with the authorization server as described
in `Section 3.2.1`_.
The prepared body will include all provided credentials as well as
the ``grant_type`` parameter set to ``password``::
>>> from oauthlib.oauth2 import LegacyApplicationClient
>>> client = LegacyApplicationClient('your_id')
>>> client.prepare_request_body(username='foo', password='bar', scope=['hello', 'world'])
'grant_type=password&username=foo&scope=hello+world&password=bar'
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1
"""
kwargs['client_id'] = self.client_id
kwargs['include_client_id'] = include_client_id
return prepare_token_request(self.grant_type, body=body, username=username,
password=password, scope=scope, **kwargs) | python | def prepare_request_body(self, username, password, body='', scope=None,
include_client_id=False, **kwargs):
"""Add the resource owner password and username to the request body.
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format per `Appendix B`_ in the HTTP request entity-body:
:param username: The resource owner username.
:param password: The resource owner password.
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
:param scope: The scope of the access request as described by
`Section 3.3`_.
:param include_client_id: `True` to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param kwargs: Extra credentials to include in the token request.
If the client type is confidential or the client was issued client
credentials (or assigned other authentication requirements), the
client MUST authenticate with the authorization server as described
in `Section 3.2.1`_.
The prepared body will include all provided credentials as well as
the ``grant_type`` parameter set to ``password``::
>>> from oauthlib.oauth2 import LegacyApplicationClient
>>> client = LegacyApplicationClient('your_id')
>>> client.prepare_request_body(username='foo', password='bar', scope=['hello', 'world'])
'grant_type=password&username=foo&scope=hello+world&password=bar'
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1
"""
kwargs['client_id'] = self.client_id
kwargs['include_client_id'] = include_client_id
return prepare_token_request(self.grant_type, body=body, username=username,
password=password, scope=scope, **kwargs) | [
"def",
"prepare_request_body",
"(",
"self",
",",
"username",
",",
"password",
",",
"body",
"=",
"''",
",",
"scope",
"=",
"None",
",",
"include_client_id",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'client_id'",
"]",
"=",
"self",
".",
"client_id",
"kwargs",
"[",
"'include_client_id'",
"]",
"=",
"include_client_id",
"return",
"prepare_token_request",
"(",
"self",
".",
"grant_type",
",",
"body",
"=",
"body",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"scope",
"=",
"scope",
",",
"*",
"*",
"kwargs",
")"
] | Add the resource owner password and username to the request body.
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format per `Appendix B`_ in the HTTP request entity-body:
:param username: The resource owner username.
:param password: The resource owner password.
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
:param scope: The scope of the access request as described by
`Section 3.3`_.
:param include_client_id: `True` to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param kwargs: Extra credentials to include in the token request.
If the client type is confidential or the client was issued client
credentials (or assigned other authentication requirements), the
client MUST authenticate with the authorization server as described
in `Section 3.2.1`_.
The prepared body will include all provided credentials as well as
the ``grant_type`` parameter set to ``password``::
>>> from oauthlib.oauth2 import LegacyApplicationClient
>>> client = LegacyApplicationClient('your_id')
>>> client.prepare_request_body(username='foo', password='bar', scope=['hello', 'world'])
'grant_type=password&username=foo&scope=hello+world&password=bar'
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 | [
"Add",
"the",
"resource",
"owner",
"password",
"and",
"username",
"to",
"the",
"request",
"body",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/legacy_application.py#L43-L85 |
229,809 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/clients/mobile_application.py | MobileApplicationClient.prepare_request_uri | def prepare_request_uri(self, uri, redirect_uri=None, scope=None,
state=None, **kwargs):
"""Prepare the implicit grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format, per `Appendix B`_:
:param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI
and it should have been registerd with the OAuth
provider prior to use. As described in `Section 3.1.2`_.
:param scope: OPTIONAL. The scope of the access request as described by
Section 3.3`_. These may be any string but are commonly
URIs or various categories such as ``videos`` or ``documents``.
:param state: RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in `Section 10.12`_.
:param kwargs: Extra arguments to include in the request URI.
In addition to supplied parameters, OAuthLib will append the ``client_id``
that was provided in the constructor as well as the mandatory ``response_type``
argument, set to ``token``::
>>> from oauthlib.oauth2 import MobileApplicationClient
>>> client = MobileApplicationClient('your_id')
>>> client.prepare_request_uri('https://example.com')
'https://example.com?client_id=your_id&response_type=token'
>>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback')
'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback'
>>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures'])
'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures'
>>> client.prepare_request_uri('https://example.com', foo='bar')
'https://example.com?client_id=your_id&response_type=token&foo=bar'
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
.. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
"""
return prepare_grant_uri(uri, self.client_id, self.response_type,
redirect_uri=redirect_uri, state=state, scope=scope, **kwargs) | python | def prepare_request_uri(self, uri, redirect_uri=None, scope=None,
state=None, **kwargs):
"""Prepare the implicit grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format, per `Appendix B`_:
:param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI
and it should have been registerd with the OAuth
provider prior to use. As described in `Section 3.1.2`_.
:param scope: OPTIONAL. The scope of the access request as described by
Section 3.3`_. These may be any string but are commonly
URIs or various categories such as ``videos`` or ``documents``.
:param state: RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in `Section 10.12`_.
:param kwargs: Extra arguments to include in the request URI.
In addition to supplied parameters, OAuthLib will append the ``client_id``
that was provided in the constructor as well as the mandatory ``response_type``
argument, set to ``token``::
>>> from oauthlib.oauth2 import MobileApplicationClient
>>> client = MobileApplicationClient('your_id')
>>> client.prepare_request_uri('https://example.com')
'https://example.com?client_id=your_id&response_type=token'
>>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback')
'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback'
>>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures'])
'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures'
>>> client.prepare_request_uri('https://example.com', foo='bar')
'https://example.com?client_id=your_id&response_type=token&foo=bar'
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
.. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
"""
return prepare_grant_uri(uri, self.client_id, self.response_type,
redirect_uri=redirect_uri, state=state, scope=scope, **kwargs) | [
"def",
"prepare_request_uri",
"(",
"self",
",",
"uri",
",",
"redirect_uri",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"prepare_grant_uri",
"(",
"uri",
",",
"self",
".",
"client_id",
",",
"self",
".",
"response_type",
",",
"redirect_uri",
"=",
"redirect_uri",
",",
"state",
"=",
"state",
",",
"scope",
"=",
"scope",
",",
"*",
"*",
"kwargs",
")"
] | Prepare the implicit grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format, per `Appendix B`_:
:param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI
and it should have been registerd with the OAuth
provider prior to use. As described in `Section 3.1.2`_.
:param scope: OPTIONAL. The scope of the access request as described by
Section 3.3`_. These may be any string but are commonly
URIs or various categories such as ``videos`` or ``documents``.
:param state: RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in `Section 10.12`_.
:param kwargs: Extra arguments to include in the request URI.
In addition to supplied parameters, OAuthLib will append the ``client_id``
that was provided in the constructor as well as the mandatory ``response_type``
argument, set to ``token``::
>>> from oauthlib.oauth2 import MobileApplicationClient
>>> client = MobileApplicationClient('your_id')
>>> client.prepare_request_uri('https://example.com')
'https://example.com?client_id=your_id&response_type=token'
>>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback')
'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback'
>>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures'])
'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures'
>>> client.prepare_request_uri('https://example.com', foo='bar')
'https://example.com?client_id=your_id&response_type=token&foo=bar'
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
.. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 | [
"Prepare",
"the",
"implicit",
"grant",
"request",
"URI",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/mobile_application.py#L51-L97 |
229,810 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/clients/mobile_application.py | MobileApplicationClient.parse_request_uri_response | def parse_request_uri_response(self, uri, state=None, scope=None):
"""Parse the response URI fragment.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format:
:param uri: The callback URI that resulted from the user being redirected
back from the provider to you, the client.
:param state: The state provided in the authorization request.
:param scope: The scopes provided in the authorization request.
:return: Dictionary of token parameters.
:raises: OAuth2Error if response is invalid.
A successful response should always contain
**access_token**
The access token issued by the authorization server. Often
a random string.
**token_type**
The type of the token issued as described in `Section 7.1`_.
Commonly ``Bearer``.
**state**
If you provided the state parameter in the authorization phase, then
the provider is required to include that exact state value in the
response.
While it is not mandated it is recommended that the provider include
**expires_in**
The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
**scope**
Providers may supply this in all responses but are required to only
if it has changed since the authorization request.
A few example responses can be seen below::
>>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world'
>>> from oauthlib.oauth2 import MobileApplicationClient
>>> client = MobileApplicationClient('your_id')
>>> client.parse_request_uri_response(response_uri)
{
'access_token': 'sdlfkj452',
'token_type': 'Bearer',
'state': 'ss345asyht',
'scope': [u'hello', u'world']
}
>>> client.parse_request_uri_response(response_uri, state='other')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response
**scope**
File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response
raise ValueError("Mismatching or missing state in params.")
ValueError: Mismatching or missing state in params.
>>> def alert_scope_changed(message, old, new):
... print(message, old, new)
...
>>> oauthlib.signals.scope_changed.connect(alert_scope_changed)
>>> client.parse_request_body_response(response_body, scope=['other'])
('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world'])
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
"""
self.token = parse_implicit_response(uri, state=state, scope=scope)
self.populate_token_attributes(self.token)
return self.token | python | def parse_request_uri_response(self, uri, state=None, scope=None):
"""Parse the response URI fragment.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format:
:param uri: The callback URI that resulted from the user being redirected
back from the provider to you, the client.
:param state: The state provided in the authorization request.
:param scope: The scopes provided in the authorization request.
:return: Dictionary of token parameters.
:raises: OAuth2Error if response is invalid.
A successful response should always contain
**access_token**
The access token issued by the authorization server. Often
a random string.
**token_type**
The type of the token issued as described in `Section 7.1`_.
Commonly ``Bearer``.
**state**
If you provided the state parameter in the authorization phase, then
the provider is required to include that exact state value in the
response.
While it is not mandated it is recommended that the provider include
**expires_in**
The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
**scope**
Providers may supply this in all responses but are required to only
if it has changed since the authorization request.
A few example responses can be seen below::
>>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world'
>>> from oauthlib.oauth2 import MobileApplicationClient
>>> client = MobileApplicationClient('your_id')
>>> client.parse_request_uri_response(response_uri)
{
'access_token': 'sdlfkj452',
'token_type': 'Bearer',
'state': 'ss345asyht',
'scope': [u'hello', u'world']
}
>>> client.parse_request_uri_response(response_uri, state='other')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response
**scope**
File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response
raise ValueError("Mismatching or missing state in params.")
ValueError: Mismatching or missing state in params.
>>> def alert_scope_changed(message, old, new):
... print(message, old, new)
...
>>> oauthlib.signals.scope_changed.connect(alert_scope_changed)
>>> client.parse_request_body_response(response_body, scope=['other'])
('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world'])
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
"""
self.token = parse_implicit_response(uri, state=state, scope=scope)
self.populate_token_attributes(self.token)
return self.token | [
"def",
"parse_request_uri_response",
"(",
"self",
",",
"uri",
",",
"state",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"self",
".",
"token",
"=",
"parse_implicit_response",
"(",
"uri",
",",
"state",
"=",
"state",
",",
"scope",
"=",
"scope",
")",
"self",
".",
"populate_token_attributes",
"(",
"self",
".",
"token",
")",
"return",
"self",
".",
"token"
] | Parse the response URI fragment.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format:
:param uri: The callback URI that resulted from the user being redirected
back from the provider to you, the client.
:param state: The state provided in the authorization request.
:param scope: The scopes provided in the authorization request.
:return: Dictionary of token parameters.
:raises: OAuth2Error if response is invalid.
A successful response should always contain
**access_token**
The access token issued by the authorization server. Often
a random string.
**token_type**
The type of the token issued as described in `Section 7.1`_.
Commonly ``Bearer``.
**state**
If you provided the state parameter in the authorization phase, then
the provider is required to include that exact state value in the
response.
While it is not mandated it is recommended that the provider include
**expires_in**
The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
**scope**
Providers may supply this in all responses but are required to only
if it has changed since the authorization request.
A few example responses can be seen below::
>>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world'
>>> from oauthlib.oauth2 import MobileApplicationClient
>>> client = MobileApplicationClient('your_id')
>>> client.parse_request_uri_response(response_uri)
{
'access_token': 'sdlfkj452',
'token_type': 'Bearer',
'state': 'ss345asyht',
'scope': [u'hello', u'world']
}
>>> client.parse_request_uri_response(response_uri, state='other')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response
**scope**
File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response
raise ValueError("Mismatching or missing state in params.")
ValueError: Mismatching or missing state in params.
>>> def alert_scope_changed(message, old, new):
... print(message, old, new)
...
>>> oauthlib.signals.scope_changed.connect(alert_scope_changed)
>>> client.parse_request_body_response(response_body, scope=['other'])
('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world'])
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 | [
"Parse",
"the",
"response",
"URI",
"fragment",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/mobile_application.py#L99-L174 |
229,811 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/request_validator.py | RequestValidator.confirm_redirect_uri | def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request,
*args, **kwargs):
"""Ensure that the authorization process represented by this authorization
code began with this 'redirect_uri'.
If the client specifies a redirect_uri when obtaining code then that
redirect URI must be bound to the code and verified equal in this
method, according to RFC 6749 section 4.1.3. Do not compare against
the client's allowed redirect URIs, but against the URI used when the
code was saved.
:param client_id: Unicode client identifier.
:param code: Unicode authorization_code.
:param redirect_uri: Unicode absolute URI.
:param client: Client object set by you, see ``.authenticate_client``.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:rtype: True or False
Method is used by:
- Authorization Code Grant (during token request)
"""
raise NotImplementedError('Subclasses must implement this method.') | python | def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request,
*args, **kwargs):
"""Ensure that the authorization process represented by this authorization
code began with this 'redirect_uri'.
If the client specifies a redirect_uri when obtaining code then that
redirect URI must be bound to the code and verified equal in this
method, according to RFC 6749 section 4.1.3. Do not compare against
the client's allowed redirect URIs, but against the URI used when the
code was saved.
:param client_id: Unicode client identifier.
:param code: Unicode authorization_code.
:param redirect_uri: Unicode absolute URI.
:param client: Client object set by you, see ``.authenticate_client``.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:rtype: True or False
Method is used by:
- Authorization Code Grant (during token request)
"""
raise NotImplementedError('Subclasses must implement this method.') | [
"def",
"confirm_redirect_uri",
"(",
"self",
",",
"client_id",
",",
"code",
",",
"redirect_uri",
",",
"client",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Subclasses must implement this method.'",
")"
] | Ensure that the authorization process represented by this authorization
code began with this 'redirect_uri'.
If the client specifies a redirect_uri when obtaining code then that
redirect URI must be bound to the code and verified equal in this
method, according to RFC 6749 section 4.1.3. Do not compare against
the client's allowed redirect URIs, but against the URI used when the
code was saved.
:param client_id: Unicode client identifier.
:param code: Unicode authorization_code.
:param redirect_uri: Unicode absolute URI.
:param client: Client object set by you, see ``.authenticate_client``.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:rtype: True or False
Method is used by:
- Authorization Code Grant (during token request) | [
"Ensure",
"that",
"the",
"authorization",
"process",
"represented",
"by",
"this",
"authorization",
"code",
"began",
"with",
"this",
"redirect_uri",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/request_validator.py#L89-L111 |
229,812 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/request_validator.py | RequestValidator.save_token | def save_token(self, token, request, *args, **kwargs):
"""Persist the token with a token type specific method.
Currently, only save_bearer_token is supported.
:param token: A (Bearer) token dict.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
return self.save_bearer_token(token, request, *args, **kwargs) | python | def save_token(self, token, request, *args, **kwargs):
"""Persist the token with a token type specific method.
Currently, only save_bearer_token is supported.
:param token: A (Bearer) token dict.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
return self.save_bearer_token(token, request, *args, **kwargs) | [
"def",
"save_token",
"(",
"self",
",",
"token",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"save_bearer_token",
"(",
"token",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Persist the token with a token type specific method.
Currently, only save_bearer_token is supported.
:param token: A (Bearer) token dict.
:param request: OAuthlib request.
:type request: oauthlib.common.Request | [
"Persist",
"the",
"token",
"with",
"a",
"token",
"type",
"specific",
"method",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/request_validator.py#L294-L303 |
229,813 | oauthlib/oauthlib | oauthlib/common.py | encode_params_utf8 | def encode_params_utf8(params):
"""Ensures that all parameters in a list of 2-element tuples are encoded to
bytestrings using UTF-8
"""
encoded = []
for k, v in params:
encoded.append((
k.encode('utf-8') if isinstance(k, unicode_type) else k,
v.encode('utf-8') if isinstance(v, unicode_type) else v))
return encoded | python | def encode_params_utf8(params):
"""Ensures that all parameters in a list of 2-element tuples are encoded to
bytestrings using UTF-8
"""
encoded = []
for k, v in params:
encoded.append((
k.encode('utf-8') if isinstance(k, unicode_type) else k,
v.encode('utf-8') if isinstance(v, unicode_type) else v))
return encoded | [
"def",
"encode_params_utf8",
"(",
"params",
")",
":",
"encoded",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"params",
":",
"encoded",
".",
"append",
"(",
"(",
"k",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"k",
",",
"unicode_type",
")",
"else",
"k",
",",
"v",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"v",
",",
"unicode_type",
")",
"else",
"v",
")",
")",
"return",
"encoded"
] | Ensures that all parameters in a list of 2-element tuples are encoded to
bytestrings using UTF-8 | [
"Ensures",
"that",
"all",
"parameters",
"in",
"a",
"list",
"of",
"2",
"-",
"element",
"tuples",
"are",
"encoded",
"to",
"bytestrings",
"using",
"UTF",
"-",
"8"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L92-L101 |
229,814 | oauthlib/oauthlib | oauthlib/common.py | decode_params_utf8 | def decode_params_utf8(params):
"""Ensures that all parameters in a list of 2-element tuples are decoded to
unicode using UTF-8.
"""
decoded = []
for k, v in params:
decoded.append((
k.decode('utf-8') if isinstance(k, bytes) else k,
v.decode('utf-8') if isinstance(v, bytes) else v))
return decoded | python | def decode_params_utf8(params):
"""Ensures that all parameters in a list of 2-element tuples are decoded to
unicode using UTF-8.
"""
decoded = []
for k, v in params:
decoded.append((
k.decode('utf-8') if isinstance(k, bytes) else k,
v.decode('utf-8') if isinstance(v, bytes) else v))
return decoded | [
"def",
"decode_params_utf8",
"(",
"params",
")",
":",
"decoded",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"params",
":",
"decoded",
".",
"append",
"(",
"(",
"k",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"k",
",",
"bytes",
")",
"else",
"k",
",",
"v",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"v",
",",
"bytes",
")",
"else",
"v",
")",
")",
"return",
"decoded"
] | Ensures that all parameters in a list of 2-element tuples are decoded to
unicode using UTF-8. | [
"Ensures",
"that",
"all",
"parameters",
"in",
"a",
"list",
"of",
"2",
"-",
"element",
"tuples",
"are",
"decoded",
"to",
"unicode",
"using",
"UTF",
"-",
"8",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L104-L113 |
229,815 | oauthlib/oauthlib | oauthlib/common.py | urldecode | def urldecode(query):
"""Decode a query string in x-www-form-urlencoded format into a sequence
of two-element tuples.
Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce
correct formatting of the query string by validation. If validation fails
a ValueError will be raised. urllib.parse_qsl will only raise errors if
any of name-value pairs omits the equals sign.
"""
# Check if query contains invalid characters
if query and not set(query) <= urlencoded:
error = ("Error trying to decode a non urlencoded string. "
"Found invalid characters: %s "
"in the string: '%s'. "
"Please ensure the request/response body is "
"x-www-form-urlencoded.")
raise ValueError(error % (set(query) - urlencoded, query))
# Check for correctly hex encoded values using a regular expression
# All encoded values begin with % followed by two hex characters
# correct = %00, %A0, %0A, %FF
# invalid = %G0, %5H, %PO
if INVALID_HEX_PATTERN.search(query):
raise ValueError('Invalid hex encoding in query string.')
# We encode to utf-8 prior to parsing because parse_qsl behaves
# differently on unicode input in python 2 and 3.
# Python 2.7
# >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6')
# u'\xe5\x95\xa6\xe5\x95\xa6'
# Python 2.7, non unicode input gives the same
# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6')
# '\xe5\x95\xa6\xe5\x95\xa6'
# but now we can decode it to unicode
# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8')
# u'\u5566\u5566'
# Python 3.3 however
# >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6')
# u'\u5566\u5566'
query = query.encode(
'utf-8') if not PY3 and isinstance(query, unicode_type) else query
# We want to allow queries such as "c2" whereas urlparse.parse_qsl
# with the strict_parsing flag will not.
params = urlparse.parse_qsl(query, keep_blank_values=True)
# unicode all the things
return decode_params_utf8(params) | python | def urldecode(query):
"""Decode a query string in x-www-form-urlencoded format into a sequence
of two-element tuples.
Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce
correct formatting of the query string by validation. If validation fails
a ValueError will be raised. urllib.parse_qsl will only raise errors if
any of name-value pairs omits the equals sign.
"""
# Check if query contains invalid characters
if query and not set(query) <= urlencoded:
error = ("Error trying to decode a non urlencoded string. "
"Found invalid characters: %s "
"in the string: '%s'. "
"Please ensure the request/response body is "
"x-www-form-urlencoded.")
raise ValueError(error % (set(query) - urlencoded, query))
# Check for correctly hex encoded values using a regular expression
# All encoded values begin with % followed by two hex characters
# correct = %00, %A0, %0A, %FF
# invalid = %G0, %5H, %PO
if INVALID_HEX_PATTERN.search(query):
raise ValueError('Invalid hex encoding in query string.')
# We encode to utf-8 prior to parsing because parse_qsl behaves
# differently on unicode input in python 2 and 3.
# Python 2.7
# >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6')
# u'\xe5\x95\xa6\xe5\x95\xa6'
# Python 2.7, non unicode input gives the same
# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6')
# '\xe5\x95\xa6\xe5\x95\xa6'
# but now we can decode it to unicode
# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8')
# u'\u5566\u5566'
# Python 3.3 however
# >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6')
# u'\u5566\u5566'
query = query.encode(
'utf-8') if not PY3 and isinstance(query, unicode_type) else query
# We want to allow queries such as "c2" whereas urlparse.parse_qsl
# with the strict_parsing flag will not.
params = urlparse.parse_qsl(query, keep_blank_values=True)
# unicode all the things
return decode_params_utf8(params) | [
"def",
"urldecode",
"(",
"query",
")",
":",
"# Check if query contains invalid characters",
"if",
"query",
"and",
"not",
"set",
"(",
"query",
")",
"<=",
"urlencoded",
":",
"error",
"=",
"(",
"\"Error trying to decode a non urlencoded string. \"",
"\"Found invalid characters: %s \"",
"\"in the string: '%s'. \"",
"\"Please ensure the request/response body is \"",
"\"x-www-form-urlencoded.\"",
")",
"raise",
"ValueError",
"(",
"error",
"%",
"(",
"set",
"(",
"query",
")",
"-",
"urlencoded",
",",
"query",
")",
")",
"# Check for correctly hex encoded values using a regular expression",
"# All encoded values begin with % followed by two hex characters",
"# correct = %00, %A0, %0A, %FF",
"# invalid = %G0, %5H, %PO",
"if",
"INVALID_HEX_PATTERN",
".",
"search",
"(",
"query",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid hex encoding in query string.'",
")",
"# We encode to utf-8 prior to parsing because parse_qsl behaves",
"# differently on unicode input in python 2 and 3.",
"# Python 2.7",
"# >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6')",
"# u'\\xe5\\x95\\xa6\\xe5\\x95\\xa6'",
"# Python 2.7, non unicode input gives the same",
"# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6')",
"# '\\xe5\\x95\\xa6\\xe5\\x95\\xa6'",
"# but now we can decode it to unicode",
"# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8')",
"# u'\\u5566\\u5566'",
"# Python 3.3 however",
"# >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6')",
"# u'\\u5566\\u5566'",
"query",
"=",
"query",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"not",
"PY3",
"and",
"isinstance",
"(",
"query",
",",
"unicode_type",
")",
"else",
"query",
"# We want to allow queries such as \"c2\" whereas urlparse.parse_qsl",
"# with the strict_parsing flag will not.",
"params",
"=",
"urlparse",
".",
"parse_qsl",
"(",
"query",
",",
"keep_blank_values",
"=",
"True",
")",
"# unicode all the things",
"return",
"decode_params_utf8",
"(",
"params",
")"
] | Decode a query string in x-www-form-urlencoded format into a sequence
of two-element tuples.
Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce
correct formatting of the query string by validation. If validation fails
a ValueError will be raised. urllib.parse_qsl will only raise errors if
any of name-value pairs omits the equals sign. | [
"Decode",
"a",
"query",
"string",
"in",
"x",
"-",
"www",
"-",
"form",
"-",
"urlencoded",
"format",
"into",
"a",
"sequence",
"of",
"two",
"-",
"element",
"tuples",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L119-L165 |
229,816 | oauthlib/oauthlib | oauthlib/common.py | extract_params | def extract_params(raw):
"""Extract parameters and return them as a list of 2-tuples.
Will successfully extract parameters from urlencoded query strings,
dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an
empty list of parameters. Any other input will result in a return
value of None.
"""
if isinstance(raw, (bytes, unicode_type)):
try:
params = urldecode(raw)
except ValueError:
params = None
elif hasattr(raw, '__iter__'):
try:
dict(raw)
except ValueError:
params = None
except TypeError:
params = None
else:
params = list(raw.items() if isinstance(raw, dict) else raw)
params = decode_params_utf8(params)
else:
params = None
return params | python | def extract_params(raw):
"""Extract parameters and return them as a list of 2-tuples.
Will successfully extract parameters from urlencoded query strings,
dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an
empty list of parameters. Any other input will result in a return
value of None.
"""
if isinstance(raw, (bytes, unicode_type)):
try:
params = urldecode(raw)
except ValueError:
params = None
elif hasattr(raw, '__iter__'):
try:
dict(raw)
except ValueError:
params = None
except TypeError:
params = None
else:
params = list(raw.items() if isinstance(raw, dict) else raw)
params = decode_params_utf8(params)
else:
params = None
return params | [
"def",
"extract_params",
"(",
"raw",
")",
":",
"if",
"isinstance",
"(",
"raw",
",",
"(",
"bytes",
",",
"unicode_type",
")",
")",
":",
"try",
":",
"params",
"=",
"urldecode",
"(",
"raw",
")",
"except",
"ValueError",
":",
"params",
"=",
"None",
"elif",
"hasattr",
"(",
"raw",
",",
"'__iter__'",
")",
":",
"try",
":",
"dict",
"(",
"raw",
")",
"except",
"ValueError",
":",
"params",
"=",
"None",
"except",
"TypeError",
":",
"params",
"=",
"None",
"else",
":",
"params",
"=",
"list",
"(",
"raw",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"raw",
",",
"dict",
")",
"else",
"raw",
")",
"params",
"=",
"decode_params_utf8",
"(",
"params",
")",
"else",
":",
"params",
"=",
"None",
"return",
"params"
] | Extract parameters and return them as a list of 2-tuples.
Will successfully extract parameters from urlencoded query strings,
dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an
empty list of parameters. Any other input will result in a return
value of None. | [
"Extract",
"parameters",
"and",
"return",
"them",
"as",
"a",
"list",
"of",
"2",
"-",
"tuples",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L168-L194 |
229,817 | oauthlib/oauthlib | oauthlib/common.py | generate_token | def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):
"""Generates a non-guessable OAuth token
OAuth (1 and 2) does not specify the format of tokens except that they
should be strings of random characters. Tokens should not be guessable
and entropy when generating the random characters is important. Which is
why SystemRandom is used instead of the default random.choice method.
"""
rand = SystemRandom()
return ''.join(rand.choice(chars) for x in range(length)) | python | def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):
"""Generates a non-guessable OAuth token
OAuth (1 and 2) does not specify the format of tokens except that they
should be strings of random characters. Tokens should not be guessable
and entropy when generating the random characters is important. Which is
why SystemRandom is used instead of the default random.choice method.
"""
rand = SystemRandom()
return ''.join(rand.choice(chars) for x in range(length)) | [
"def",
"generate_token",
"(",
"length",
"=",
"30",
",",
"chars",
"=",
"UNICODE_ASCII_CHARACTER_SET",
")",
":",
"rand",
"=",
"SystemRandom",
"(",
")",
"return",
"''",
".",
"join",
"(",
"rand",
".",
"choice",
"(",
"chars",
")",
"for",
"x",
"in",
"range",
"(",
"length",
")",
")"
] | Generates a non-guessable OAuth token
OAuth (1 and 2) does not specify the format of tokens except that they
should be strings of random characters. Tokens should not be guessable
and entropy when generating the random characters is important. Which is
why SystemRandom is used instead of the default random.choice method. | [
"Generates",
"a",
"non",
"-",
"guessable",
"OAuth",
"token"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L224-L233 |
229,818 | oauthlib/oauthlib | oauthlib/common.py | add_params_to_qs | def add_params_to_qs(query, params):
"""Extend a query with a list of two-tuples."""
if isinstance(params, dict):
params = params.items()
queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
queryparams.extend(params)
return urlencode(queryparams) | python | def add_params_to_qs(query, params):
"""Extend a query with a list of two-tuples."""
if isinstance(params, dict):
params = params.items()
queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
queryparams.extend(params)
return urlencode(queryparams) | [
"def",
"add_params_to_qs",
"(",
"query",
",",
"params",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"params",
"=",
"params",
".",
"items",
"(",
")",
"queryparams",
"=",
"urlparse",
".",
"parse_qsl",
"(",
"query",
",",
"keep_blank_values",
"=",
"True",
")",
"queryparams",
".",
"extend",
"(",
"params",
")",
"return",
"urlencode",
"(",
"queryparams",
")"
] | Extend a query with a list of two-tuples. | [
"Extend",
"a",
"query",
"with",
"a",
"list",
"of",
"two",
"-",
"tuples",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L269-L275 |
229,819 | oauthlib/oauthlib | oauthlib/common.py | add_params_to_uri | def add_params_to_uri(uri, params, fragment=False):
"""Add a list of two-tuples to the uri query components."""
sch, net, path, par, query, fra = urlparse.urlparse(uri)
if fragment:
fra = add_params_to_qs(fra, params)
else:
query = add_params_to_qs(query, params)
return urlparse.urlunparse((sch, net, path, par, query, fra)) | python | def add_params_to_uri(uri, params, fragment=False):
"""Add a list of two-tuples to the uri query components."""
sch, net, path, par, query, fra = urlparse.urlparse(uri)
if fragment:
fra = add_params_to_qs(fra, params)
else:
query = add_params_to_qs(query, params)
return urlparse.urlunparse((sch, net, path, par, query, fra)) | [
"def",
"add_params_to_uri",
"(",
"uri",
",",
"params",
",",
"fragment",
"=",
"False",
")",
":",
"sch",
",",
"net",
",",
"path",
",",
"par",
",",
"query",
",",
"fra",
"=",
"urlparse",
".",
"urlparse",
"(",
"uri",
")",
"if",
"fragment",
":",
"fra",
"=",
"add_params_to_qs",
"(",
"fra",
",",
"params",
")",
"else",
":",
"query",
"=",
"add_params_to_qs",
"(",
"query",
",",
"params",
")",
"return",
"urlparse",
".",
"urlunparse",
"(",
"(",
"sch",
",",
"net",
",",
"path",
",",
"par",
",",
"query",
",",
"fra",
")",
")"
] | Add a list of two-tuples to the uri query components. | [
"Add",
"a",
"list",
"of",
"two",
"-",
"tuples",
"to",
"the",
"uri",
"query",
"components",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L278-L285 |
229,820 | oauthlib/oauthlib | oauthlib/common.py | to_unicode | def to_unicode(data, encoding='UTF-8'):
"""Convert a number of different types of objects to unicode."""
if isinstance(data, unicode_type):
return data
if isinstance(data, bytes):
return unicode_type(data, encoding=encoding)
if hasattr(data, '__iter__'):
try:
dict(data)
except TypeError:
pass
except ValueError:
# Assume it's a one dimensional data structure
return (to_unicode(i, encoding) for i in data)
else:
# We support 2.6 which lacks dict comprehensions
if hasattr(data, 'items'):
data = data.items()
return dict(((to_unicode(k, encoding), to_unicode(v, encoding)) for k, v in data))
return data | python | def to_unicode(data, encoding='UTF-8'):
"""Convert a number of different types of objects to unicode."""
if isinstance(data, unicode_type):
return data
if isinstance(data, bytes):
return unicode_type(data, encoding=encoding)
if hasattr(data, '__iter__'):
try:
dict(data)
except TypeError:
pass
except ValueError:
# Assume it's a one dimensional data structure
return (to_unicode(i, encoding) for i in data)
else:
# We support 2.6 which lacks dict comprehensions
if hasattr(data, 'items'):
data = data.items()
return dict(((to_unicode(k, encoding), to_unicode(v, encoding)) for k, v in data))
return data | [
"def",
"to_unicode",
"(",
"data",
",",
"encoding",
"=",
"'UTF-8'",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"unicode_type",
")",
":",
"return",
"data",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"return",
"unicode_type",
"(",
"data",
",",
"encoding",
"=",
"encoding",
")",
"if",
"hasattr",
"(",
"data",
",",
"'__iter__'",
")",
":",
"try",
":",
"dict",
"(",
"data",
")",
"except",
"TypeError",
":",
"pass",
"except",
"ValueError",
":",
"# Assume it's a one dimensional data structure",
"return",
"(",
"to_unicode",
"(",
"i",
",",
"encoding",
")",
"for",
"i",
"in",
"data",
")",
"else",
":",
"# We support 2.6 which lacks dict comprehensions",
"if",
"hasattr",
"(",
"data",
",",
"'items'",
")",
":",
"data",
"=",
"data",
".",
"items",
"(",
")",
"return",
"dict",
"(",
"(",
"(",
"to_unicode",
"(",
"k",
",",
"encoding",
")",
",",
"to_unicode",
"(",
"v",
",",
"encoding",
")",
")",
"for",
"k",
",",
"v",
"in",
"data",
")",
")",
"return",
"data"
] | Convert a number of different types of objects to unicode. | [
"Convert",
"a",
"number",
"of",
"different",
"types",
"of",
"objects",
"to",
"unicode",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L306-L328 |
229,821 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/parameters.py | _append_params | def _append_params(oauth_params, params):
"""Append OAuth params to an existing set of parameters.
Both params and oauth_params is must be lists of 2-tuples.
Per `section 3.5.2`_ and `3.5.3`_ of the spec.
.. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2
.. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
"""
merged = list(params)
merged.extend(oauth_params)
# The request URI / entity-body MAY include other request-specific
# parameters, in which case, the protocol parameters SHOULD be appended
# following the request-specific parameters, properly separated by an "&"
# character (ASCII code 38)
merged.sort(key=lambda i: i[0].startswith('oauth_'))
return merged | python | def _append_params(oauth_params, params):
"""Append OAuth params to an existing set of parameters.
Both params and oauth_params is must be lists of 2-tuples.
Per `section 3.5.2`_ and `3.5.3`_ of the spec.
.. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2
.. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
"""
merged = list(params)
merged.extend(oauth_params)
# The request URI / entity-body MAY include other request-specific
# parameters, in which case, the protocol parameters SHOULD be appended
# following the request-specific parameters, properly separated by an "&"
# character (ASCII code 38)
merged.sort(key=lambda i: i[0].startswith('oauth_'))
return merged | [
"def",
"_append_params",
"(",
"oauth_params",
",",
"params",
")",
":",
"merged",
"=",
"list",
"(",
"params",
")",
"merged",
".",
"extend",
"(",
"oauth_params",
")",
"# The request URI / entity-body MAY include other request-specific",
"# parameters, in which case, the protocol parameters SHOULD be appended",
"# following the request-specific parameters, properly separated by an \"&\"",
"# character (ASCII code 38)",
"merged",
".",
"sort",
"(",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"0",
"]",
".",
"startswith",
"(",
"'oauth_'",
")",
")",
"return",
"merged"
] | Append OAuth params to an existing set of parameters.
Both params and oauth_params is must be lists of 2-tuples.
Per `section 3.5.2`_ and `3.5.3`_ of the spec.
.. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2
.. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 | [
"Append",
"OAuth",
"params",
"to",
"an",
"existing",
"set",
"of",
"parameters",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/parameters.py#L94-L112 |
229,822 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/parameters.py | prepare_request_uri_query | def prepare_request_uri_query(oauth_params, uri):
"""Prepare the Request URI Query.
Per `section 3.5.3`_ of the spec.
.. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
"""
# append OAuth params to the existing set of query components
sch, net, path, par, query, fra = urlparse(uri)
query = urlencode(
_append_params(oauth_params, extract_params(query) or []))
return urlunparse((sch, net, path, par, query, fra)) | python | def prepare_request_uri_query(oauth_params, uri):
"""Prepare the Request URI Query.
Per `section 3.5.3`_ of the spec.
.. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
"""
# append OAuth params to the existing set of query components
sch, net, path, par, query, fra = urlparse(uri)
query = urlencode(
_append_params(oauth_params, extract_params(query) or []))
return urlunparse((sch, net, path, par, query, fra)) | [
"def",
"prepare_request_uri_query",
"(",
"oauth_params",
",",
"uri",
")",
":",
"# append OAuth params to the existing set of query components",
"sch",
",",
"net",
",",
"path",
",",
"par",
",",
"query",
",",
"fra",
"=",
"urlparse",
"(",
"uri",
")",
"query",
"=",
"urlencode",
"(",
"_append_params",
"(",
"oauth_params",
",",
"extract_params",
"(",
"query",
")",
"or",
"[",
"]",
")",
")",
"return",
"urlunparse",
"(",
"(",
"sch",
",",
"net",
",",
"path",
",",
"par",
",",
"query",
",",
"fra",
")",
")"
] | Prepare the Request URI Query.
Per `section 3.5.3`_ of the spec.
.. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 | [
"Prepare",
"the",
"Request",
"URI",
"Query",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/parameters.py#L127-L139 |
229,823 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/request_token.py | RequestTokenEndpoint.validate_request_token_request | def validate_request_token_request(self, request):
"""Validate a request token request.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object.
"""
self._check_transport_security(request)
self._check_mandatory_parameters(request)
if request.realm:
request.realms = request.realm.split(' ')
else:
request.realms = self.request_validator.get_default_realms(
request.client_key, request)
if not self.request_validator.check_realms(request.realms):
raise errors.InvalidRequestError(
description='Invalid realm %s. Allowed are %r.' % (
request.realms, self.request_validator.realms))
if not request.redirect_uri:
raise errors.InvalidRequestError(
description='Missing callback URI.')
if not self.request_validator.validate_timestamp_and_nonce(
request.client_key, request.timestamp, request.nonce, request,
request_token=request.resource_owner_key):
return False, request
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid client credentials.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy client is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable client enumeration
valid_client = self.request_validator.validate_client_key(
request.client_key, request)
if not valid_client:
request.client_key = self.request_validator.dummy_client
# Note that `realm`_ is only used in authorization headers and how
# it should be interepreted is not included in the OAuth spec.
# However they could be seen as a scope or realm to which the
# client has access and as such every client should be checked
# to ensure it is authorized access to that scope or realm.
# .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2
#
# Note that early exit would enable client realm access enumeration.
#
# The require_realm indicates this is the first step in the OAuth
# workflow where a client requests access to a specific realm.
# This first step (obtaining request token) need not require a realm
# and can then be identified by checking the require_resource_owner
# flag and abscence of realm.
#
# Clients obtaining an access token will not supply a realm and it will
# not be checked. Instead the previously requested realm should be
# transferred from the request token to the access token.
#
# Access to protected resources will always validate the realm but note
# that the realm is now tied to the access token and not provided by
# the client.
valid_realm = self.request_validator.validate_requested_realms(
request.client_key, request.realms, request)
# Callback is normally never required, except for requests for
# a Temporary Credential as described in `Section 2.1`_
# .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1
valid_redirect = self.request_validator.validate_redirect_uri(
request.client_key, request.redirect_uri, request)
if not request.redirect_uri:
raise NotImplementedError('Redirect URI must either be provided '
'or set to a default during validation.')
valid_signature = self._check_signature(request)
# log the results to the validator_log
# this lets us handle internal reporting and analysis
request.validator_log['client'] = valid_client
request.validator_log['realm'] = valid_realm
request.validator_log['callback'] = valid_redirect
request.validator_log['signature'] = valid_signature
# We delay checking validity until the very end, using dummy values for
# calculations and fetching secrets/keys to ensure the flow of every
# request remains almost identical regardless of whether valid values
# have been supplied. This ensures near constant time execution and
# prevents malicious users from guessing sensitive information
v = all((valid_client, valid_realm, valid_redirect, valid_signature))
if not v:
log.info("[Failure] request verification failed.")
log.info("Valid client: %s.", valid_client)
log.info("Valid realm: %s.", valid_realm)
log.info("Valid callback: %s.", valid_redirect)
log.info("Valid signature: %s.", valid_signature)
return v, request | python | def validate_request_token_request(self, request):
"""Validate a request token request.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object.
"""
self._check_transport_security(request)
self._check_mandatory_parameters(request)
if request.realm:
request.realms = request.realm.split(' ')
else:
request.realms = self.request_validator.get_default_realms(
request.client_key, request)
if not self.request_validator.check_realms(request.realms):
raise errors.InvalidRequestError(
description='Invalid realm %s. Allowed are %r.' % (
request.realms, self.request_validator.realms))
if not request.redirect_uri:
raise errors.InvalidRequestError(
description='Missing callback URI.')
if not self.request_validator.validate_timestamp_and_nonce(
request.client_key, request.timestamp, request.nonce, request,
request_token=request.resource_owner_key):
return False, request
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid client credentials.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy client is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable client enumeration
valid_client = self.request_validator.validate_client_key(
request.client_key, request)
if not valid_client:
request.client_key = self.request_validator.dummy_client
# Note that `realm`_ is only used in authorization headers and how
# it should be interepreted is not included in the OAuth spec.
# However they could be seen as a scope or realm to which the
# client has access and as such every client should be checked
# to ensure it is authorized access to that scope or realm.
# .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2
#
# Note that early exit would enable client realm access enumeration.
#
# The require_realm indicates this is the first step in the OAuth
# workflow where a client requests access to a specific realm.
# This first step (obtaining request token) need not require a realm
# and can then be identified by checking the require_resource_owner
# flag and abscence of realm.
#
# Clients obtaining an access token will not supply a realm and it will
# not be checked. Instead the previously requested realm should be
# transferred from the request token to the access token.
#
# Access to protected resources will always validate the realm but note
# that the realm is now tied to the access token and not provided by
# the client.
valid_realm = self.request_validator.validate_requested_realms(
request.client_key, request.realms, request)
# Callback is normally never required, except for requests for
# a Temporary Credential as described in `Section 2.1`_
# .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1
valid_redirect = self.request_validator.validate_redirect_uri(
request.client_key, request.redirect_uri, request)
if not request.redirect_uri:
raise NotImplementedError('Redirect URI must either be provided '
'or set to a default during validation.')
valid_signature = self._check_signature(request)
# log the results to the validator_log
# this lets us handle internal reporting and analysis
request.validator_log['client'] = valid_client
request.validator_log['realm'] = valid_realm
request.validator_log['callback'] = valid_redirect
request.validator_log['signature'] = valid_signature
# We delay checking validity until the very end, using dummy values for
# calculations and fetching secrets/keys to ensure the flow of every
# request remains almost identical regardless of whether valid values
# have been supplied. This ensures near constant time execution and
# prevents malicious users from guessing sensitive information
v = all((valid_client, valid_realm, valid_redirect, valid_signature))
if not v:
log.info("[Failure] request verification failed.")
log.info("Valid client: %s.", valid_client)
log.info("Valid realm: %s.", valid_realm)
log.info("Valid callback: %s.", valid_redirect)
log.info("Valid signature: %s.", valid_signature)
return v, request | [
"def",
"validate_request_token_request",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_check_transport_security",
"(",
"request",
")",
"self",
".",
"_check_mandatory_parameters",
"(",
"request",
")",
"if",
"request",
".",
"realm",
":",
"request",
".",
"realms",
"=",
"request",
".",
"realm",
".",
"split",
"(",
"' '",
")",
"else",
":",
"request",
".",
"realms",
"=",
"self",
".",
"request_validator",
".",
"get_default_realms",
"(",
"request",
".",
"client_key",
",",
"request",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"check_realms",
"(",
"request",
".",
"realms",
")",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Invalid realm %s. Allowed are %r.'",
"%",
"(",
"request",
".",
"realms",
",",
"self",
".",
"request_validator",
".",
"realms",
")",
")",
"if",
"not",
"request",
".",
"redirect_uri",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Missing callback URI.'",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_timestamp_and_nonce",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"timestamp",
",",
"request",
".",
"nonce",
",",
"request",
",",
"request_token",
"=",
"request",
".",
"resource_owner_key",
")",
":",
"return",
"False",
",",
"request",
"# The server SHOULD return a 401 (Unauthorized) status code when",
"# receiving a request with invalid client credentials.",
"# Note: This is postponed in order to avoid timing attacks, instead",
"# a dummy client is assigned and used to maintain near constant",
"# time request verification.",
"#",
"# Note that early exit would enable client enumeration",
"valid_client",
"=",
"self",
".",
"request_validator",
".",
"validate_client_key",
"(",
"request",
".",
"client_key",
",",
"request",
")",
"if",
"not",
"valid_client",
":",
"request",
".",
"client_key",
"=",
"self",
".",
"request_validator",
".",
"dummy_client",
"# Note that `realm`_ is only used in authorization headers and how",
"# it should be interepreted is not included in the OAuth spec.",
"# However they could be seen as a scope or realm to which the",
"# client has access and as such every client should be checked",
"# to ensure it is authorized access to that scope or realm.",
"# .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2",
"#",
"# Note that early exit would enable client realm access enumeration.",
"#",
"# The require_realm indicates this is the first step in the OAuth",
"# workflow where a client requests access to a specific realm.",
"# This first step (obtaining request token) need not require a realm",
"# and can then be identified by checking the require_resource_owner",
"# flag and abscence of realm.",
"#",
"# Clients obtaining an access token will not supply a realm and it will",
"# not be checked. Instead the previously requested realm should be",
"# transferred from the request token to the access token.",
"#",
"# Access to protected resources will always validate the realm but note",
"# that the realm is now tied to the access token and not provided by",
"# the client.",
"valid_realm",
"=",
"self",
".",
"request_validator",
".",
"validate_requested_realms",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"realms",
",",
"request",
")",
"# Callback is normally never required, except for requests for",
"# a Temporary Credential as described in `Section 2.1`_",
"# .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1",
"valid_redirect",
"=",
"self",
".",
"request_validator",
".",
"validate_redirect_uri",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"redirect_uri",
",",
"request",
")",
"if",
"not",
"request",
".",
"redirect_uri",
":",
"raise",
"NotImplementedError",
"(",
"'Redirect URI must either be provided '",
"'or set to a default during validation.'",
")",
"valid_signature",
"=",
"self",
".",
"_check_signature",
"(",
"request",
")",
"# log the results to the validator_log",
"# this lets us handle internal reporting and analysis",
"request",
".",
"validator_log",
"[",
"'client'",
"]",
"=",
"valid_client",
"request",
".",
"validator_log",
"[",
"'realm'",
"]",
"=",
"valid_realm",
"request",
".",
"validator_log",
"[",
"'callback'",
"]",
"=",
"valid_redirect",
"request",
".",
"validator_log",
"[",
"'signature'",
"]",
"=",
"valid_signature",
"# We delay checking validity until the very end, using dummy values for",
"# calculations and fetching secrets/keys to ensure the flow of every",
"# request remains almost identical regardless of whether valid values",
"# have been supplied. This ensures near constant time execution and",
"# prevents malicious users from guessing sensitive information",
"v",
"=",
"all",
"(",
"(",
"valid_client",
",",
"valid_realm",
",",
"valid_redirect",
",",
"valid_signature",
")",
")",
"if",
"not",
"v",
":",
"log",
".",
"info",
"(",
"\"[Failure] request verification failed.\"",
")",
"log",
".",
"info",
"(",
"\"Valid client: %s.\"",
",",
"valid_client",
")",
"log",
".",
"info",
"(",
"\"Valid realm: %s.\"",
",",
"valid_realm",
")",
"log",
".",
"info",
"(",
"\"Valid callback: %s.\"",
",",
"valid_redirect",
")",
"log",
".",
"info",
"(",
"\"Valid signature: %s.\"",
",",
"valid_signature",
")",
"return",
"v",
",",
"request"
] | Validate a request token request.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object. | [
"Validate",
"a",
"request",
"token",
"request",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/request_token.py#L112-L211 |
229,824 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/signature_only.py | SignatureOnlyEndpoint.validate_request | def validate_request(self, uri, http_method='GET',
body=None, headers=None):
"""Validate a signed OAuth request.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:returns: A tuple of 2 elements.
1. True if valid, False otherwise.
2. An oauthlib.common.Request object.
"""
try:
request = self._create_request(uri, http_method, body, headers)
except errors.OAuth1Error as err:
log.info(
'Exception caught while validating request, %s.' % err)
return False, None
try:
self._check_transport_security(request)
self._check_mandatory_parameters(request)
except errors.OAuth1Error as err:
log.info(
'Exception caught while validating request, %s.' % err)
return False, request
if not self.request_validator.validate_timestamp_and_nonce(
request.client_key, request.timestamp, request.nonce, request):
log.debug('[Failure] verification failed: timestamp/nonce')
return False, request
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid client credentials.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy client is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable client enumeration
valid_client = self.request_validator.validate_client_key(
request.client_key, request)
if not valid_client:
request.client_key = self.request_validator.dummy_client
valid_signature = self._check_signature(request)
# log the results to the validator_log
# this lets us handle internal reporting and analysis
request.validator_log['client'] = valid_client
request.validator_log['signature'] = valid_signature
# We delay checking validity until the very end, using dummy values for
# calculations and fetching secrets/keys to ensure the flow of every
# request remains almost identical regardless of whether valid values
# have been supplied. This ensures near constant time execution and
# prevents malicious users from guessing sensitive information
v = all((valid_client, valid_signature))
if not v:
log.info("[Failure] request verification failed.")
log.info("Valid client: %s", valid_client)
log.info("Valid signature: %s", valid_signature)
return v, request | python | def validate_request(self, uri, http_method='GET',
body=None, headers=None):
"""Validate a signed OAuth request.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:returns: A tuple of 2 elements.
1. True if valid, False otherwise.
2. An oauthlib.common.Request object.
"""
try:
request = self._create_request(uri, http_method, body, headers)
except errors.OAuth1Error as err:
log.info(
'Exception caught while validating request, %s.' % err)
return False, None
try:
self._check_transport_security(request)
self._check_mandatory_parameters(request)
except errors.OAuth1Error as err:
log.info(
'Exception caught while validating request, %s.' % err)
return False, request
if not self.request_validator.validate_timestamp_and_nonce(
request.client_key, request.timestamp, request.nonce, request):
log.debug('[Failure] verification failed: timestamp/nonce')
return False, request
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid client credentials.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy client is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable client enumeration
valid_client = self.request_validator.validate_client_key(
request.client_key, request)
if not valid_client:
request.client_key = self.request_validator.dummy_client
valid_signature = self._check_signature(request)
# log the results to the validator_log
# this lets us handle internal reporting and analysis
request.validator_log['client'] = valid_client
request.validator_log['signature'] = valid_signature
# We delay checking validity until the very end, using dummy values for
# calculations and fetching secrets/keys to ensure the flow of every
# request remains almost identical regardless of whether valid values
# have been supplied. This ensures near constant time execution and
# prevents malicious users from guessing sensitive information
v = all((valid_client, valid_signature))
if not v:
log.info("[Failure] request verification failed.")
log.info("Valid client: %s", valid_client)
log.info("Valid signature: %s", valid_signature)
return v, request | [
"def",
"validate_request",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"try",
":",
"request",
"=",
"self",
".",
"_create_request",
"(",
"uri",
",",
"http_method",
",",
"body",
",",
"headers",
")",
"except",
"errors",
".",
"OAuth1Error",
"as",
"err",
":",
"log",
".",
"info",
"(",
"'Exception caught while validating request, %s.'",
"%",
"err",
")",
"return",
"False",
",",
"None",
"try",
":",
"self",
".",
"_check_transport_security",
"(",
"request",
")",
"self",
".",
"_check_mandatory_parameters",
"(",
"request",
")",
"except",
"errors",
".",
"OAuth1Error",
"as",
"err",
":",
"log",
".",
"info",
"(",
"'Exception caught while validating request, %s.'",
"%",
"err",
")",
"return",
"False",
",",
"request",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_timestamp_and_nonce",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"timestamp",
",",
"request",
".",
"nonce",
",",
"request",
")",
":",
"log",
".",
"debug",
"(",
"'[Failure] verification failed: timestamp/nonce'",
")",
"return",
"False",
",",
"request",
"# The server SHOULD return a 401 (Unauthorized) status code when",
"# receiving a request with invalid client credentials.",
"# Note: This is postponed in order to avoid timing attacks, instead",
"# a dummy client is assigned and used to maintain near constant",
"# time request verification.",
"#",
"# Note that early exit would enable client enumeration",
"valid_client",
"=",
"self",
".",
"request_validator",
".",
"validate_client_key",
"(",
"request",
".",
"client_key",
",",
"request",
")",
"if",
"not",
"valid_client",
":",
"request",
".",
"client_key",
"=",
"self",
".",
"request_validator",
".",
"dummy_client",
"valid_signature",
"=",
"self",
".",
"_check_signature",
"(",
"request",
")",
"# log the results to the validator_log",
"# this lets us handle internal reporting and analysis",
"request",
".",
"validator_log",
"[",
"'client'",
"]",
"=",
"valid_client",
"request",
".",
"validator_log",
"[",
"'signature'",
"]",
"=",
"valid_signature",
"# We delay checking validity until the very end, using dummy values for",
"# calculations and fetching secrets/keys to ensure the flow of every",
"# request remains almost identical regardless of whether valid values",
"# have been supplied. This ensures near constant time execution and",
"# prevents malicious users from guessing sensitive information",
"v",
"=",
"all",
"(",
"(",
"valid_client",
",",
"valid_signature",
")",
")",
"if",
"not",
"v",
":",
"log",
".",
"info",
"(",
"\"[Failure] request verification failed.\"",
")",
"log",
".",
"info",
"(",
"\"Valid client: %s\"",
",",
"valid_client",
")",
"log",
".",
"info",
"(",
"\"Valid signature: %s\"",
",",
"valid_signature",
")",
"return",
"v",
",",
"request"
] | Validate a signed OAuth request.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:returns: A tuple of 2 elements.
1. True if valid, False otherwise.
2. An oauthlib.common.Request object. | [
"Validate",
"a",
"signed",
"OAuth",
"request",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/signature_only.py#L23-L84 |
229,825 | oauthlib/oauthlib | oauthlib/openid/connect/core/tokens.py | JWTToken.create_token | def create_token(self, request, refresh_token=False):
"""Create a JWT Token, using requestvalidator method."""
if callable(self.expires_in):
expires_in = self.expires_in(request)
else:
expires_in = self.expires_in
request.expires_in = expires_in
return self.request_validator.get_jwt_bearer_token(None, None, request) | python | def create_token(self, request, refresh_token=False):
"""Create a JWT Token, using requestvalidator method."""
if callable(self.expires_in):
expires_in = self.expires_in(request)
else:
expires_in = self.expires_in
request.expires_in = expires_in
return self.request_validator.get_jwt_bearer_token(None, None, request) | [
"def",
"create_token",
"(",
"self",
",",
"request",
",",
"refresh_token",
"=",
"False",
")",
":",
"if",
"callable",
"(",
"self",
".",
"expires_in",
")",
":",
"expires_in",
"=",
"self",
".",
"expires_in",
"(",
"request",
")",
"else",
":",
"expires_in",
"=",
"self",
".",
"expires_in",
"request",
".",
"expires_in",
"=",
"expires_in",
"return",
"self",
".",
"request_validator",
".",
"get_jwt_bearer_token",
"(",
"None",
",",
"None",
",",
"request",
")"
] | Create a JWT Token, using requestvalidator method. | [
"Create",
"a",
"JWT",
"Token",
"using",
"requestvalidator",
"method",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/tokens.py#L28-L38 |
229,826 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/__init__.py | Client.get_oauth_signature | def get_oauth_signature(self, request):
"""Get an OAuth signature to be used in signing a request
To satisfy `section 3.4.1.2`_ item 2, if the request argument's
headers dict attribute contains a Host item, its value will
replace any netloc part of the request argument's uri attribute
value.
.. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2
"""
if self.signature_method == SIGNATURE_PLAINTEXT:
# fast-path
return signature.sign_plaintext(self.client_secret,
self.resource_owner_secret)
uri, headers, body = self._render(request)
collected_params = signature.collect_parameters(
uri_query=urlparse.urlparse(uri).query,
body=body,
headers=headers)
log.debug("Collected params: {0}".format(collected_params))
normalized_params = signature.normalize_parameters(collected_params)
normalized_uri = signature.base_string_uri(uri, headers.get('Host', None))
log.debug("Normalized params: {0}".format(normalized_params))
log.debug("Normalized URI: {0}".format(normalized_uri))
base_string = signature.signature_base_string(request.http_method,
normalized_uri, normalized_params)
log.debug("Signing: signature base string: {0}".format(base_string))
if self.signature_method not in self.SIGNATURE_METHODS:
raise ValueError('Invalid signature method.')
sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self)
log.debug("Signature: {0}".format(sig))
return sig | python | def get_oauth_signature(self, request):
"""Get an OAuth signature to be used in signing a request
To satisfy `section 3.4.1.2`_ item 2, if the request argument's
headers dict attribute contains a Host item, its value will
replace any netloc part of the request argument's uri attribute
value.
.. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2
"""
if self.signature_method == SIGNATURE_PLAINTEXT:
# fast-path
return signature.sign_plaintext(self.client_secret,
self.resource_owner_secret)
uri, headers, body = self._render(request)
collected_params = signature.collect_parameters(
uri_query=urlparse.urlparse(uri).query,
body=body,
headers=headers)
log.debug("Collected params: {0}".format(collected_params))
normalized_params = signature.normalize_parameters(collected_params)
normalized_uri = signature.base_string_uri(uri, headers.get('Host', None))
log.debug("Normalized params: {0}".format(normalized_params))
log.debug("Normalized URI: {0}".format(normalized_uri))
base_string = signature.signature_base_string(request.http_method,
normalized_uri, normalized_params)
log.debug("Signing: signature base string: {0}".format(base_string))
if self.signature_method not in self.SIGNATURE_METHODS:
raise ValueError('Invalid signature method.')
sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self)
log.debug("Signature: {0}".format(sig))
return sig | [
"def",
"get_oauth_signature",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"signature_method",
"==",
"SIGNATURE_PLAINTEXT",
":",
"# fast-path",
"return",
"signature",
".",
"sign_plaintext",
"(",
"self",
".",
"client_secret",
",",
"self",
".",
"resource_owner_secret",
")",
"uri",
",",
"headers",
",",
"body",
"=",
"self",
".",
"_render",
"(",
"request",
")",
"collected_params",
"=",
"signature",
".",
"collect_parameters",
"(",
"uri_query",
"=",
"urlparse",
".",
"urlparse",
"(",
"uri",
")",
".",
"query",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"headers",
")",
"log",
".",
"debug",
"(",
"\"Collected params: {0}\"",
".",
"format",
"(",
"collected_params",
")",
")",
"normalized_params",
"=",
"signature",
".",
"normalize_parameters",
"(",
"collected_params",
")",
"normalized_uri",
"=",
"signature",
".",
"base_string_uri",
"(",
"uri",
",",
"headers",
".",
"get",
"(",
"'Host'",
",",
"None",
")",
")",
"log",
".",
"debug",
"(",
"\"Normalized params: {0}\"",
".",
"format",
"(",
"normalized_params",
")",
")",
"log",
".",
"debug",
"(",
"\"Normalized URI: {0}\"",
".",
"format",
"(",
"normalized_uri",
")",
")",
"base_string",
"=",
"signature",
".",
"signature_base_string",
"(",
"request",
".",
"http_method",
",",
"normalized_uri",
",",
"normalized_params",
")",
"log",
".",
"debug",
"(",
"\"Signing: signature base string: {0}\"",
".",
"format",
"(",
"base_string",
")",
")",
"if",
"self",
".",
"signature_method",
"not",
"in",
"self",
".",
"SIGNATURE_METHODS",
":",
"raise",
"ValueError",
"(",
"'Invalid signature method.'",
")",
"sig",
"=",
"self",
".",
"SIGNATURE_METHODS",
"[",
"self",
".",
"signature_method",
"]",
"(",
"base_string",
",",
"self",
")",
"log",
".",
"debug",
"(",
"\"Signature: {0}\"",
".",
"format",
"(",
"sig",
")",
")",
"return",
"sig"
] | Get an OAuth signature to be used in signing a request
To satisfy `section 3.4.1.2`_ item 2, if the request argument's
headers dict attribute contains a Host item, its value will
replace any netloc part of the request argument's uri attribute
value.
.. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 | [
"Get",
"an",
"OAuth",
"signature",
"to",
"be",
"used",
"in",
"signing",
"a",
"request"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L112-L151 |
229,827 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/__init__.py | Client.get_oauth_params | def get_oauth_params(self, request):
"""Get the basic OAuth parameters to be used in generating a signature.
"""
nonce = (generate_nonce()
if self.nonce is None else self.nonce)
timestamp = (generate_timestamp()
if self.timestamp is None else self.timestamp)
params = [
('oauth_nonce', nonce),
('oauth_timestamp', timestamp),
('oauth_version', '1.0'),
('oauth_signature_method', self.signature_method),
('oauth_consumer_key', self.client_key),
]
if self.resource_owner_key:
params.append(('oauth_token', self.resource_owner_key))
if self.callback_uri:
params.append(('oauth_callback', self.callback_uri))
if self.verifier:
params.append(('oauth_verifier', self.verifier))
# providing body hash for requests other than x-www-form-urlencoded
# as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1
# 4.1.1. When to include the body hash
# * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies
# * [...] SHOULD include the oauth_body_hash parameter on all other requests.
# Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2
# At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension.
content_type = request.headers.get('Content-Type', None)
content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0
if request.body is not None and content_type_eligible:
params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8')))
return params | python | def get_oauth_params(self, request):
"""Get the basic OAuth parameters to be used in generating a signature.
"""
nonce = (generate_nonce()
if self.nonce is None else self.nonce)
timestamp = (generate_timestamp()
if self.timestamp is None else self.timestamp)
params = [
('oauth_nonce', nonce),
('oauth_timestamp', timestamp),
('oauth_version', '1.0'),
('oauth_signature_method', self.signature_method),
('oauth_consumer_key', self.client_key),
]
if self.resource_owner_key:
params.append(('oauth_token', self.resource_owner_key))
if self.callback_uri:
params.append(('oauth_callback', self.callback_uri))
if self.verifier:
params.append(('oauth_verifier', self.verifier))
# providing body hash for requests other than x-www-form-urlencoded
# as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1
# 4.1.1. When to include the body hash
# * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies
# * [...] SHOULD include the oauth_body_hash parameter on all other requests.
# Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2
# At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension.
content_type = request.headers.get('Content-Type', None)
content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0
if request.body is not None and content_type_eligible:
params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8')))
return params | [
"def",
"get_oauth_params",
"(",
"self",
",",
"request",
")",
":",
"nonce",
"=",
"(",
"generate_nonce",
"(",
")",
"if",
"self",
".",
"nonce",
"is",
"None",
"else",
"self",
".",
"nonce",
")",
"timestamp",
"=",
"(",
"generate_timestamp",
"(",
")",
"if",
"self",
".",
"timestamp",
"is",
"None",
"else",
"self",
".",
"timestamp",
")",
"params",
"=",
"[",
"(",
"'oauth_nonce'",
",",
"nonce",
")",
",",
"(",
"'oauth_timestamp'",
",",
"timestamp",
")",
",",
"(",
"'oauth_version'",
",",
"'1.0'",
")",
",",
"(",
"'oauth_signature_method'",
",",
"self",
".",
"signature_method",
")",
",",
"(",
"'oauth_consumer_key'",
",",
"self",
".",
"client_key",
")",
",",
"]",
"if",
"self",
".",
"resource_owner_key",
":",
"params",
".",
"append",
"(",
"(",
"'oauth_token'",
",",
"self",
".",
"resource_owner_key",
")",
")",
"if",
"self",
".",
"callback_uri",
":",
"params",
".",
"append",
"(",
"(",
"'oauth_callback'",
",",
"self",
".",
"callback_uri",
")",
")",
"if",
"self",
".",
"verifier",
":",
"params",
".",
"append",
"(",
"(",
"'oauth_verifier'",
",",
"self",
".",
"verifier",
")",
")",
"# providing body hash for requests other than x-www-form-urlencoded",
"# as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1",
"# 4.1.1. When to include the body hash",
"# * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies",
"# * [...] SHOULD include the oauth_body_hash parameter on all other requests.",
"# Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2",
"# At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension.",
"content_type",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"None",
")",
"content_type_eligible",
"=",
"content_type",
"and",
"content_type",
".",
"find",
"(",
"'application/x-www-form-urlencoded'",
")",
"<",
"0",
"if",
"request",
".",
"body",
"is",
"not",
"None",
"and",
"content_type_eligible",
":",
"params",
".",
"append",
"(",
"(",
"'oauth_body_hash'",
",",
"base64",
".",
"b64encode",
"(",
"hashlib",
".",
"sha1",
"(",
"request",
".",
"body",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"digest",
"(",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")",
")",
"return",
"params"
] | Get the basic OAuth parameters to be used in generating a signature. | [
"Get",
"the",
"basic",
"OAuth",
"parameters",
"to",
"be",
"used",
"in",
"generating",
"a",
"signature",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L153-L186 |
229,828 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/__init__.py | Client._render | def _render(self, request, formencode=False, realm=None):
"""Render a signed request according to signature type
Returns a 3-tuple containing the request URI, headers, and body.
If the formencode argument is True and the body contains parameters, it
is escaped and returned as a valid formencoded string.
"""
# TODO what if there are body params on a header-type auth?
# TODO what if there are query params on a body-type auth?
uri, headers, body = request.uri, request.headers, request.body
# TODO: right now these prepare_* methods are very narrow in scope--they
# only affect their little thing. In some cases (for example, with
# header auth) it might be advantageous to allow these methods to touch
# other parts of the request, like the headers—so the prepare_headers
# method could also set the Content-Type header to x-www-form-urlencoded
# like the spec requires. This would be a fundamental change though, and
# I'm not sure how I feel about it.
if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER:
headers = parameters.prepare_headers(
request.oauth_params, request.headers, realm=realm)
elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:
body = parameters.prepare_form_encoded_body(
request.oauth_params, request.decoded_body)
if formencode:
body = urlencode(body)
headers['Content-Type'] = 'application/x-www-form-urlencoded'
elif self.signature_type == SIGNATURE_TYPE_QUERY:
uri = parameters.prepare_request_uri_query(
request.oauth_params, request.uri)
else:
raise ValueError('Unknown signature type specified.')
return uri, headers, body | python | def _render(self, request, formencode=False, realm=None):
"""Render a signed request according to signature type
Returns a 3-tuple containing the request URI, headers, and body.
If the formencode argument is True and the body contains parameters, it
is escaped and returned as a valid formencoded string.
"""
# TODO what if there are body params on a header-type auth?
# TODO what if there are query params on a body-type auth?
uri, headers, body = request.uri, request.headers, request.body
# TODO: right now these prepare_* methods are very narrow in scope--they
# only affect their little thing. In some cases (for example, with
# header auth) it might be advantageous to allow these methods to touch
# other parts of the request, like the headers—so the prepare_headers
# method could also set the Content-Type header to x-www-form-urlencoded
# like the spec requires. This would be a fundamental change though, and
# I'm not sure how I feel about it.
if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER:
headers = parameters.prepare_headers(
request.oauth_params, request.headers, realm=realm)
elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:
body = parameters.prepare_form_encoded_body(
request.oauth_params, request.decoded_body)
if formencode:
body = urlencode(body)
headers['Content-Type'] = 'application/x-www-form-urlencoded'
elif self.signature_type == SIGNATURE_TYPE_QUERY:
uri = parameters.prepare_request_uri_query(
request.oauth_params, request.uri)
else:
raise ValueError('Unknown signature type specified.')
return uri, headers, body | [
"def",
"_render",
"(",
"self",
",",
"request",
",",
"formencode",
"=",
"False",
",",
"realm",
"=",
"None",
")",
":",
"# TODO what if there are body params on a header-type auth?",
"# TODO what if there are query params on a body-type auth?",
"uri",
",",
"headers",
",",
"body",
"=",
"request",
".",
"uri",
",",
"request",
".",
"headers",
",",
"request",
".",
"body",
"# TODO: right now these prepare_* methods are very narrow in scope--they",
"# only affect their little thing. In some cases (for example, with",
"# header auth) it might be advantageous to allow these methods to touch",
"# other parts of the request, like the headers—so the prepare_headers",
"# method could also set the Content-Type header to x-www-form-urlencoded",
"# like the spec requires. This would be a fundamental change though, and",
"# I'm not sure how I feel about it.",
"if",
"self",
".",
"signature_type",
"==",
"SIGNATURE_TYPE_AUTH_HEADER",
":",
"headers",
"=",
"parameters",
".",
"prepare_headers",
"(",
"request",
".",
"oauth_params",
",",
"request",
".",
"headers",
",",
"realm",
"=",
"realm",
")",
"elif",
"self",
".",
"signature_type",
"==",
"SIGNATURE_TYPE_BODY",
"and",
"request",
".",
"decoded_body",
"is",
"not",
"None",
":",
"body",
"=",
"parameters",
".",
"prepare_form_encoded_body",
"(",
"request",
".",
"oauth_params",
",",
"request",
".",
"decoded_body",
")",
"if",
"formencode",
":",
"body",
"=",
"urlencode",
"(",
"body",
")",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded'",
"elif",
"self",
".",
"signature_type",
"==",
"SIGNATURE_TYPE_QUERY",
":",
"uri",
"=",
"parameters",
".",
"prepare_request_uri_query",
"(",
"request",
".",
"oauth_params",
",",
"request",
".",
"uri",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown signature type specified.'",
")",
"return",
"uri",
",",
"headers",
",",
"body"
] | Render a signed request according to signature type
Returns a 3-tuple containing the request URI, headers, and body.
If the formencode argument is True and the body contains parameters, it
is escaped and returned as a valid formencoded string. | [
"Render",
"a",
"signed",
"request",
"according",
"to",
"signature",
"type"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L188-L223 |
229,829 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/__init__.py | Client.sign | def sign(self, uri, http_method='GET', body=None, headers=None, realm=None):
"""Sign a request
Signs an HTTP request with the specified parts.
Returns a 3-tuple of the signed request's URI, headers, and body.
Note that http_method is not returned as it is unaffected by the OAuth
signing process. Also worth noting is that duplicate parameters
will be included in the signature, regardless of where they are
specified (query, body).
The body argument may be a dict, a list of 2-tuples, or a formencoded
string. The Content-Type header must be 'application/x-www-form-urlencoded'
if it is present.
If the body argument is not one of the above, it will be returned
verbatim as it is unaffected by the OAuth signing process. Attempting to
sign a request with non-formencoded data using the OAuth body signature
type is invalid and will raise an exception.
If the body does contain parameters, it will be returned as a properly-
formatted formencoded string.
Body may not be included if the http_method is either GET or HEAD as
this changes the semantic meaning of the request.
All string data MUST be unicode or be encoded with the same encoding
scheme supplied to the Client constructor, default utf-8. This includes
strings inside body dicts, for example.
"""
# normalize request data
request = Request(uri, http_method, body, headers,
encoding=self.encoding)
# sanity check
content_type = request.headers.get('Content-Type', None)
multipart = content_type and content_type.startswith('multipart/')
should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED
has_params = request.decoded_body is not None
# 3.4.1.3.1. Parameter Sources
# [Parameters are collected from the HTTP request entity-body, but only
# if [...]:
# * The entity-body is single-part.
if multipart and has_params:
raise ValueError(
"Headers indicate a multipart body but body contains parameters.")
# * The entity-body follows the encoding requirements of the
# "application/x-www-form-urlencoded" content-type as defined by
# [W3C.REC-html40-19980424].
elif should_have_params and not has_params:
raise ValueError(
"Headers indicate a formencoded body but body was not decodable.")
# * The HTTP request entity-header includes the "Content-Type"
# header field set to "application/x-www-form-urlencoded".
elif not should_have_params and has_params:
raise ValueError(
"Body contains parameters but Content-Type header was {0} "
"instead of {1}".format(content_type or "not set",
CONTENT_TYPE_FORM_URLENCODED))
# 3.5.2. Form-Encoded Body
# Protocol parameters can be transmitted in the HTTP request entity-
# body, but only if the following REQUIRED conditions are met:
# o The entity-body is single-part.
# o The entity-body follows the encoding requirements of the
# "application/x-www-form-urlencoded" content-type as defined by
# [W3C.REC-html40-19980424].
# o The HTTP request entity-header includes the "Content-Type" header
# field set to "application/x-www-form-urlencoded".
elif self.signature_type == SIGNATURE_TYPE_BODY and not (
should_have_params and has_params and not multipart):
raise ValueError(
'Body signatures may only be used with form-urlencoded content')
# We amend https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
# with the clause that parameters from body should only be included
# in non GET or HEAD requests. Extracting the request body parameters
# and including them in the signature base string would give semantic
# meaning to the body, which it should not have according to the
# HTTP 1.1 spec.
elif http_method.upper() in ('GET', 'HEAD') and has_params:
raise ValueError('GET/HEAD requests should not include body.')
# generate the basic OAuth parameters
request.oauth_params = self.get_oauth_params(request)
# generate the signature
request.oauth_params.append(
('oauth_signature', self.get_oauth_signature(request)))
# render the signed request and return it
uri, headers, body = self._render(request, formencode=True,
realm=(realm or self.realm))
if self.decoding:
log.debug('Encoding URI, headers and body to %s.', self.decoding)
uri = uri.encode(self.decoding)
body = body.encode(self.decoding) if body else body
new_headers = {}
for k, v in headers.items():
new_headers[k.encode(self.decoding)] = v.encode(self.decoding)
headers = new_headers
return uri, headers, body | python | def sign(self, uri, http_method='GET', body=None, headers=None, realm=None):
"""Sign a request
Signs an HTTP request with the specified parts.
Returns a 3-tuple of the signed request's URI, headers, and body.
Note that http_method is not returned as it is unaffected by the OAuth
signing process. Also worth noting is that duplicate parameters
will be included in the signature, regardless of where they are
specified (query, body).
The body argument may be a dict, a list of 2-tuples, or a formencoded
string. The Content-Type header must be 'application/x-www-form-urlencoded'
if it is present.
If the body argument is not one of the above, it will be returned
verbatim as it is unaffected by the OAuth signing process. Attempting to
sign a request with non-formencoded data using the OAuth body signature
type is invalid and will raise an exception.
If the body does contain parameters, it will be returned as a properly-
formatted formencoded string.
Body may not be included if the http_method is either GET or HEAD as
this changes the semantic meaning of the request.
All string data MUST be unicode or be encoded with the same encoding
scheme supplied to the Client constructor, default utf-8. This includes
strings inside body dicts, for example.
"""
# normalize request data
request = Request(uri, http_method, body, headers,
encoding=self.encoding)
# sanity check
content_type = request.headers.get('Content-Type', None)
multipart = content_type and content_type.startswith('multipart/')
should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED
has_params = request.decoded_body is not None
# 3.4.1.3.1. Parameter Sources
# [Parameters are collected from the HTTP request entity-body, but only
# if [...]:
# * The entity-body is single-part.
if multipart and has_params:
raise ValueError(
"Headers indicate a multipart body but body contains parameters.")
# * The entity-body follows the encoding requirements of the
# "application/x-www-form-urlencoded" content-type as defined by
# [W3C.REC-html40-19980424].
elif should_have_params and not has_params:
raise ValueError(
"Headers indicate a formencoded body but body was not decodable.")
# * The HTTP request entity-header includes the "Content-Type"
# header field set to "application/x-www-form-urlencoded".
elif not should_have_params and has_params:
raise ValueError(
"Body contains parameters but Content-Type header was {0} "
"instead of {1}".format(content_type or "not set",
CONTENT_TYPE_FORM_URLENCODED))
# 3.5.2. Form-Encoded Body
# Protocol parameters can be transmitted in the HTTP request entity-
# body, but only if the following REQUIRED conditions are met:
# o The entity-body is single-part.
# o The entity-body follows the encoding requirements of the
# "application/x-www-form-urlencoded" content-type as defined by
# [W3C.REC-html40-19980424].
# o The HTTP request entity-header includes the "Content-Type" header
# field set to "application/x-www-form-urlencoded".
elif self.signature_type == SIGNATURE_TYPE_BODY and not (
should_have_params and has_params and not multipart):
raise ValueError(
'Body signatures may only be used with form-urlencoded content')
# We amend https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
# with the clause that parameters from body should only be included
# in non GET or HEAD requests. Extracting the request body parameters
# and including them in the signature base string would give semantic
# meaning to the body, which it should not have according to the
# HTTP 1.1 spec.
elif http_method.upper() in ('GET', 'HEAD') and has_params:
raise ValueError('GET/HEAD requests should not include body.')
# generate the basic OAuth parameters
request.oauth_params = self.get_oauth_params(request)
# generate the signature
request.oauth_params.append(
('oauth_signature', self.get_oauth_signature(request)))
# render the signed request and return it
uri, headers, body = self._render(request, formencode=True,
realm=(realm or self.realm))
if self.decoding:
log.debug('Encoding URI, headers and body to %s.', self.decoding)
uri = uri.encode(self.decoding)
body = body.encode(self.decoding) if body else body
new_headers = {}
for k, v in headers.items():
new_headers[k.encode(self.decoding)] = v.encode(self.decoding)
headers = new_headers
return uri, headers, body | [
"def",
"sign",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"realm",
"=",
"None",
")",
":",
"# normalize request data",
"request",
"=",
"Request",
"(",
"uri",
",",
"http_method",
",",
"body",
",",
"headers",
",",
"encoding",
"=",
"self",
".",
"encoding",
")",
"# sanity check",
"content_type",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"None",
")",
"multipart",
"=",
"content_type",
"and",
"content_type",
".",
"startswith",
"(",
"'multipart/'",
")",
"should_have_params",
"=",
"content_type",
"==",
"CONTENT_TYPE_FORM_URLENCODED",
"has_params",
"=",
"request",
".",
"decoded_body",
"is",
"not",
"None",
"# 3.4.1.3.1. Parameter Sources",
"# [Parameters are collected from the HTTP request entity-body, but only",
"# if [...]:",
"# * The entity-body is single-part.",
"if",
"multipart",
"and",
"has_params",
":",
"raise",
"ValueError",
"(",
"\"Headers indicate a multipart body but body contains parameters.\"",
")",
"# * The entity-body follows the encoding requirements of the",
"# \"application/x-www-form-urlencoded\" content-type as defined by",
"# [W3C.REC-html40-19980424].",
"elif",
"should_have_params",
"and",
"not",
"has_params",
":",
"raise",
"ValueError",
"(",
"\"Headers indicate a formencoded body but body was not decodable.\"",
")",
"# * The HTTP request entity-header includes the \"Content-Type\"",
"# header field set to \"application/x-www-form-urlencoded\".",
"elif",
"not",
"should_have_params",
"and",
"has_params",
":",
"raise",
"ValueError",
"(",
"\"Body contains parameters but Content-Type header was {0} \"",
"\"instead of {1}\"",
".",
"format",
"(",
"content_type",
"or",
"\"not set\"",
",",
"CONTENT_TYPE_FORM_URLENCODED",
")",
")",
"# 3.5.2. Form-Encoded Body",
"# Protocol parameters can be transmitted in the HTTP request entity-",
"# body, but only if the following REQUIRED conditions are met:",
"# o The entity-body is single-part.",
"# o The entity-body follows the encoding requirements of the",
"# \"application/x-www-form-urlencoded\" content-type as defined by",
"# [W3C.REC-html40-19980424].",
"# o The HTTP request entity-header includes the \"Content-Type\" header",
"# field set to \"application/x-www-form-urlencoded\".",
"elif",
"self",
".",
"signature_type",
"==",
"SIGNATURE_TYPE_BODY",
"and",
"not",
"(",
"should_have_params",
"and",
"has_params",
"and",
"not",
"multipart",
")",
":",
"raise",
"ValueError",
"(",
"'Body signatures may only be used with form-urlencoded content'",
")",
"# We amend https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1",
"# with the clause that parameters from body should only be included",
"# in non GET or HEAD requests. Extracting the request body parameters",
"# and including them in the signature base string would give semantic",
"# meaning to the body, which it should not have according to the",
"# HTTP 1.1 spec.",
"elif",
"http_method",
".",
"upper",
"(",
")",
"in",
"(",
"'GET'",
",",
"'HEAD'",
")",
"and",
"has_params",
":",
"raise",
"ValueError",
"(",
"'GET/HEAD requests should not include body.'",
")",
"# generate the basic OAuth parameters",
"request",
".",
"oauth_params",
"=",
"self",
".",
"get_oauth_params",
"(",
"request",
")",
"# generate the signature",
"request",
".",
"oauth_params",
".",
"append",
"(",
"(",
"'oauth_signature'",
",",
"self",
".",
"get_oauth_signature",
"(",
"request",
")",
")",
")",
"# render the signed request and return it",
"uri",
",",
"headers",
",",
"body",
"=",
"self",
".",
"_render",
"(",
"request",
",",
"formencode",
"=",
"True",
",",
"realm",
"=",
"(",
"realm",
"or",
"self",
".",
"realm",
")",
")",
"if",
"self",
".",
"decoding",
":",
"log",
".",
"debug",
"(",
"'Encoding URI, headers and body to %s.'",
",",
"self",
".",
"decoding",
")",
"uri",
"=",
"uri",
".",
"encode",
"(",
"self",
".",
"decoding",
")",
"body",
"=",
"body",
".",
"encode",
"(",
"self",
".",
"decoding",
")",
"if",
"body",
"else",
"body",
"new_headers",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"headers",
".",
"items",
"(",
")",
":",
"new_headers",
"[",
"k",
".",
"encode",
"(",
"self",
".",
"decoding",
")",
"]",
"=",
"v",
".",
"encode",
"(",
"self",
".",
"decoding",
")",
"headers",
"=",
"new_headers",
"return",
"uri",
",",
"headers",
",",
"body"
] | Sign a request
Signs an HTTP request with the specified parts.
Returns a 3-tuple of the signed request's URI, headers, and body.
Note that http_method is not returned as it is unaffected by the OAuth
signing process. Also worth noting is that duplicate parameters
will be included in the signature, regardless of where they are
specified (query, body).
The body argument may be a dict, a list of 2-tuples, or a formencoded
string. The Content-Type header must be 'application/x-www-form-urlencoded'
if it is present.
If the body argument is not one of the above, it will be returned
verbatim as it is unaffected by the OAuth signing process. Attempting to
sign a request with non-formencoded data using the OAuth body signature
type is invalid and will raise an exception.
If the body does contain parameters, it will be returned as a properly-
formatted formencoded string.
Body may not be included if the http_method is either GET or HEAD as
this changes the semantic meaning of the request.
All string data MUST be unicode or be encoded with the same encoding
scheme supplied to the Client constructor, default utf-8. This includes
strings inside body dicts, for example. | [
"Sign",
"a",
"request"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L225-L327 |
229,830 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/base.py | BaseEndpoint._raise_on_invalid_client | def _raise_on_invalid_client(self, request):
"""Raise on failed client authentication."""
if self.request_validator.client_authentication_required(request):
if not self.request_validator.authenticate_client(request):
log.debug('Client authentication failed, %r.', request)
raise InvalidClientError(request=request)
elif not self.request_validator.authenticate_client_id(request.client_id, request):
log.debug('Client authentication failed, %r.', request)
raise InvalidClientError(request=request) | python | def _raise_on_invalid_client(self, request):
"""Raise on failed client authentication."""
if self.request_validator.client_authentication_required(request):
if not self.request_validator.authenticate_client(request):
log.debug('Client authentication failed, %r.', request)
raise InvalidClientError(request=request)
elif not self.request_validator.authenticate_client_id(request.client_id, request):
log.debug('Client authentication failed, %r.', request)
raise InvalidClientError(request=request) | [
"def",
"_raise_on_invalid_client",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"request_validator",
".",
"client_authentication_required",
"(",
"request",
")",
":",
"if",
"not",
"self",
".",
"request_validator",
".",
"authenticate_client",
"(",
"request",
")",
":",
"log",
".",
"debug",
"(",
"'Client authentication failed, %r.'",
",",
"request",
")",
"raise",
"InvalidClientError",
"(",
"request",
"=",
"request",
")",
"elif",
"not",
"self",
".",
"request_validator",
".",
"authenticate_client_id",
"(",
"request",
".",
"client_id",
",",
"request",
")",
":",
"log",
".",
"debug",
"(",
"'Client authentication failed, %r.'",
",",
"request",
")",
"raise",
"InvalidClientError",
"(",
"request",
"=",
"request",
")"
] | Raise on failed client authentication. | [
"Raise",
"on",
"failed",
"client",
"authentication",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/base.py#L48-L56 |
229,831 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/base.py | BaseEndpoint._raise_on_unsupported_token | def _raise_on_unsupported_token(self, request):
"""Raise on unsupported tokens."""
if (request.token_type_hint and
request.token_type_hint in self.valid_token_types and
request.token_type_hint not in self.supported_token_types):
raise UnsupportedTokenTypeError(request=request) | python | def _raise_on_unsupported_token(self, request):
"""Raise on unsupported tokens."""
if (request.token_type_hint and
request.token_type_hint in self.valid_token_types and
request.token_type_hint not in self.supported_token_types):
raise UnsupportedTokenTypeError(request=request) | [
"def",
"_raise_on_unsupported_token",
"(",
"self",
",",
"request",
")",
":",
"if",
"(",
"request",
".",
"token_type_hint",
"and",
"request",
".",
"token_type_hint",
"in",
"self",
".",
"valid_token_types",
"and",
"request",
".",
"token_type_hint",
"not",
"in",
"self",
".",
"supported_token_types",
")",
":",
"raise",
"UnsupportedTokenTypeError",
"(",
"request",
"=",
"request",
")"
] | Raise on unsupported tokens. | [
"Raise",
"on",
"unsupported",
"tokens",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/base.py#L58-L63 |
229,832 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/revocation.py | RevocationEndpoint.create_revocation_response | def create_revocation_response(self, uri, http_method='POST', body=None,
headers=None):
"""Revoke supplied access or refresh token.
The authorization server responds with HTTP status code 200 if the
token has been revoked sucessfully or if the client submitted an
invalid token.
Note: invalid tokens do not cause an error response since the client
cannot handle such an error in a reasonable way. Moreover, the purpose
of the revocation request, invalidating the particular token, is
already achieved.
The content of the response body is ignored by the client as all
necessary information is conveyed in the response code.
An invalid token type hint value is ignored by the authorization server
and does not influence the revocation response.
"""
resp_headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
}
request = Request(
uri, http_method=http_method, body=body, headers=headers)
try:
self.validate_revocation_request(request)
log.debug('Token revocation valid for %r.', request)
except OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
response_body = e.json
if self.enable_jsonp and request.callback:
response_body = '%s(%s);' % (request.callback, response_body)
resp_headers.update(e.headers)
return resp_headers, response_body, e.status_code
self.request_validator.revoke_token(request.token,
request.token_type_hint, request)
response_body = ''
if self.enable_jsonp and request.callback:
response_body = request.callback + '();'
return {}, response_body, 200 | python | def create_revocation_response(self, uri, http_method='POST', body=None,
headers=None):
"""Revoke supplied access or refresh token.
The authorization server responds with HTTP status code 200 if the
token has been revoked sucessfully or if the client submitted an
invalid token.
Note: invalid tokens do not cause an error response since the client
cannot handle such an error in a reasonable way. Moreover, the purpose
of the revocation request, invalidating the particular token, is
already achieved.
The content of the response body is ignored by the client as all
necessary information is conveyed in the response code.
An invalid token type hint value is ignored by the authorization server
and does not influence the revocation response.
"""
resp_headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
}
request = Request(
uri, http_method=http_method, body=body, headers=headers)
try:
self.validate_revocation_request(request)
log.debug('Token revocation valid for %r.', request)
except OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
response_body = e.json
if self.enable_jsonp and request.callback:
response_body = '%s(%s);' % (request.callback, response_body)
resp_headers.update(e.headers)
return resp_headers, response_body, e.status_code
self.request_validator.revoke_token(request.token,
request.token_type_hint, request)
response_body = ''
if self.enable_jsonp and request.callback:
response_body = request.callback + '();'
return {}, response_body, 200 | [
"def",
"create_revocation_response",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'POST'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"resp_headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Cache-Control'",
":",
"'no-store'",
",",
"'Pragma'",
":",
"'no-cache'",
",",
"}",
"request",
"=",
"Request",
"(",
"uri",
",",
"http_method",
"=",
"http_method",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"headers",
")",
"try",
":",
"self",
".",
"validate_revocation_request",
"(",
"request",
")",
"log",
".",
"debug",
"(",
"'Token revocation valid for %r.'",
",",
"request",
")",
"except",
"OAuth2Error",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'Client error during validation of %r. %r.'",
",",
"request",
",",
"e",
")",
"response_body",
"=",
"e",
".",
"json",
"if",
"self",
".",
"enable_jsonp",
"and",
"request",
".",
"callback",
":",
"response_body",
"=",
"'%s(%s);'",
"%",
"(",
"request",
".",
"callback",
",",
"response_body",
")",
"resp_headers",
".",
"update",
"(",
"e",
".",
"headers",
")",
"return",
"resp_headers",
",",
"response_body",
",",
"e",
".",
"status_code",
"self",
".",
"request_validator",
".",
"revoke_token",
"(",
"request",
".",
"token",
",",
"request",
".",
"token_type_hint",
",",
"request",
")",
"response_body",
"=",
"''",
"if",
"self",
".",
"enable_jsonp",
"and",
"request",
".",
"callback",
":",
"response_body",
"=",
"request",
".",
"callback",
"+",
"'();'",
"return",
"{",
"}",
",",
"response_body",
",",
"200"
] | Revoke supplied access or refresh token.
The authorization server responds with HTTP status code 200 if the
token has been revoked sucessfully or if the client submitted an
invalid token.
Note: invalid tokens do not cause an error response since the client
cannot handle such an error in a reasonable way. Moreover, the purpose
of the revocation request, invalidating the particular token, is
already achieved.
The content of the response body is ignored by the client as all
necessary information is conveyed in the response code.
An invalid token type hint value is ignored by the authorization server
and does not influence the revocation response. | [
"Revoke",
"supplied",
"access",
"or",
"refresh",
"token",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/revocation.py#L41-L85 |
229,833 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/grant_types/base.py | GrantTypeBase.prepare_authorization_response | def prepare_authorization_response(self, request, token, headers, body, status):
"""Place token according to response mode.
Base classes can define a default response mode for their authorization
response by overriding the static `default_response_mode` member.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token:
:param headers:
:param body:
:param status:
"""
request.response_mode = request.response_mode or self.default_response_mode
if request.response_mode not in ('query', 'fragment'):
log.debug('Overriding invalid response mode %s with %s',
request.response_mode, self.default_response_mode)
request.response_mode = self.default_response_mode
token_items = token.items()
if request.response_type == 'none':
state = token.get('state', None)
if state:
token_items = [('state', state)]
else:
token_items = []
if request.response_mode == 'query':
headers['Location'] = add_params_to_uri(
request.redirect_uri, token_items, fragment=False)
return headers, body, status
if request.response_mode == 'fragment':
headers['Location'] = add_params_to_uri(
request.redirect_uri, token_items, fragment=True)
return headers, body, status
raise NotImplementedError(
'Subclasses must set a valid default_response_mode') | python | def prepare_authorization_response(self, request, token, headers, body, status):
"""Place token according to response mode.
Base classes can define a default response mode for their authorization
response by overriding the static `default_response_mode` member.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token:
:param headers:
:param body:
:param status:
"""
request.response_mode = request.response_mode or self.default_response_mode
if request.response_mode not in ('query', 'fragment'):
log.debug('Overriding invalid response mode %s with %s',
request.response_mode, self.default_response_mode)
request.response_mode = self.default_response_mode
token_items = token.items()
if request.response_type == 'none':
state = token.get('state', None)
if state:
token_items = [('state', state)]
else:
token_items = []
if request.response_mode == 'query':
headers['Location'] = add_params_to_uri(
request.redirect_uri, token_items, fragment=False)
return headers, body, status
if request.response_mode == 'fragment':
headers['Location'] = add_params_to_uri(
request.redirect_uri, token_items, fragment=True)
return headers, body, status
raise NotImplementedError(
'Subclasses must set a valid default_response_mode') | [
"def",
"prepare_authorization_response",
"(",
"self",
",",
"request",
",",
"token",
",",
"headers",
",",
"body",
",",
"status",
")",
":",
"request",
".",
"response_mode",
"=",
"request",
".",
"response_mode",
"or",
"self",
".",
"default_response_mode",
"if",
"request",
".",
"response_mode",
"not",
"in",
"(",
"'query'",
",",
"'fragment'",
")",
":",
"log",
".",
"debug",
"(",
"'Overriding invalid response mode %s with %s'",
",",
"request",
".",
"response_mode",
",",
"self",
".",
"default_response_mode",
")",
"request",
".",
"response_mode",
"=",
"self",
".",
"default_response_mode",
"token_items",
"=",
"token",
".",
"items",
"(",
")",
"if",
"request",
".",
"response_type",
"==",
"'none'",
":",
"state",
"=",
"token",
".",
"get",
"(",
"'state'",
",",
"None",
")",
"if",
"state",
":",
"token_items",
"=",
"[",
"(",
"'state'",
",",
"state",
")",
"]",
"else",
":",
"token_items",
"=",
"[",
"]",
"if",
"request",
".",
"response_mode",
"==",
"'query'",
":",
"headers",
"[",
"'Location'",
"]",
"=",
"add_params_to_uri",
"(",
"request",
".",
"redirect_uri",
",",
"token_items",
",",
"fragment",
"=",
"False",
")",
"return",
"headers",
",",
"body",
",",
"status",
"if",
"request",
".",
"response_mode",
"==",
"'fragment'",
":",
"headers",
"[",
"'Location'",
"]",
"=",
"add_params_to_uri",
"(",
"request",
".",
"redirect_uri",
",",
"token_items",
",",
"fragment",
"=",
"True",
")",
"return",
"headers",
",",
"body",
",",
"status",
"raise",
"NotImplementedError",
"(",
"'Subclasses must set a valid default_response_mode'",
")"
] | Place token according to response mode.
Base classes can define a default response mode for their authorization
response by overriding the static `default_response_mode` member.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token:
:param headers:
:param body:
:param status: | [
"Place",
"token",
"according",
"to",
"response",
"mode",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/base.py#L180-L220 |
229,834 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/tokens.py | prepare_mac_header | def prepare_mac_header(token, uri, key, http_method,
nonce=None,
headers=None,
body=None,
ext='',
hash_algorithm='hmac-sha-1',
issue_time=None,
draft=0):
"""Add an `MAC Access Authentication`_ signature to headers.
Unlike OAuth 1, this HMAC signature does not require inclusion of the
request payload/body, neither does it use a combination of client_secret
and token_secret but rather a mac_key provided together with the access
token.
Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256",
`extension algorithms`_ are not supported.
Example MAC Authorization header, linebreaks added for clarity
Authorization: MAC id="h480djs93hd8",
nonce="1336363200:dj83hs9s",
mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM="
.. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01
.. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1
:param token:
:param uri: Request URI.
:param key: MAC given provided by token endpoint.
:param http_method: HTTP Request method.
:param nonce:
:param headers: Request headers as a dictionary.
:param body:
:param ext:
:param hash_algorithm: HMAC algorithm provided by token endpoint.
:param issue_time: Time when the MAC credentials were issued (datetime).
:param draft: MAC authentication specification version.
:return: headers dictionary with the authorization field added.
"""
http_method = http_method.upper()
host, port = utils.host_from_uri(uri)
if hash_algorithm.lower() == 'hmac-sha-1':
h = hashlib.sha1
elif hash_algorithm.lower() == 'hmac-sha-256':
h = hashlib.sha256
else:
raise ValueError('unknown hash algorithm')
if draft == 0:
nonce = nonce or '{0}:{1}'.format(utils.generate_age(issue_time),
common.generate_nonce())
else:
ts = common.generate_timestamp()
nonce = common.generate_nonce()
sch, net, path, par, query, fra = urlparse(uri)
if query:
request_uri = path + '?' + query
else:
request_uri = path
# Hash the body/payload
if body is not None and draft == 0:
body = body.encode('utf-8')
bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8')
else:
bodyhash = ''
# Create the normalized base string
base = []
if draft == 0:
base.append(nonce)
else:
base.append(ts)
base.append(nonce)
base.append(http_method.upper())
base.append(request_uri)
base.append(host)
base.append(port)
if draft == 0:
base.append(bodyhash)
base.append(ext or '')
base_string = '\n'.join(base) + '\n'
# hmac struggles with unicode strings - http://bugs.python.org/issue5285
if isinstance(key, unicode_type):
key = key.encode('utf-8')
sign = hmac.new(key, base_string.encode('utf-8'), h)
sign = b2a_base64(sign.digest())[:-1].decode('utf-8')
header = []
header.append('MAC id="%s"' % token)
if draft != 0:
header.append('ts="%s"' % ts)
header.append('nonce="%s"' % nonce)
if bodyhash:
header.append('bodyhash="%s"' % bodyhash)
if ext:
header.append('ext="%s"' % ext)
header.append('mac="%s"' % sign)
headers = headers or {}
headers['Authorization'] = ', '.join(header)
return headers | python | def prepare_mac_header(token, uri, key, http_method,
nonce=None,
headers=None,
body=None,
ext='',
hash_algorithm='hmac-sha-1',
issue_time=None,
draft=0):
"""Add an `MAC Access Authentication`_ signature to headers.
Unlike OAuth 1, this HMAC signature does not require inclusion of the
request payload/body, neither does it use a combination of client_secret
and token_secret but rather a mac_key provided together with the access
token.
Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256",
`extension algorithms`_ are not supported.
Example MAC Authorization header, linebreaks added for clarity
Authorization: MAC id="h480djs93hd8",
nonce="1336363200:dj83hs9s",
mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM="
.. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01
.. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1
:param token:
:param uri: Request URI.
:param key: MAC given provided by token endpoint.
:param http_method: HTTP Request method.
:param nonce:
:param headers: Request headers as a dictionary.
:param body:
:param ext:
:param hash_algorithm: HMAC algorithm provided by token endpoint.
:param issue_time: Time when the MAC credentials were issued (datetime).
:param draft: MAC authentication specification version.
:return: headers dictionary with the authorization field added.
"""
http_method = http_method.upper()
host, port = utils.host_from_uri(uri)
if hash_algorithm.lower() == 'hmac-sha-1':
h = hashlib.sha1
elif hash_algorithm.lower() == 'hmac-sha-256':
h = hashlib.sha256
else:
raise ValueError('unknown hash algorithm')
if draft == 0:
nonce = nonce or '{0}:{1}'.format(utils.generate_age(issue_time),
common.generate_nonce())
else:
ts = common.generate_timestamp()
nonce = common.generate_nonce()
sch, net, path, par, query, fra = urlparse(uri)
if query:
request_uri = path + '?' + query
else:
request_uri = path
# Hash the body/payload
if body is not None and draft == 0:
body = body.encode('utf-8')
bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8')
else:
bodyhash = ''
# Create the normalized base string
base = []
if draft == 0:
base.append(nonce)
else:
base.append(ts)
base.append(nonce)
base.append(http_method.upper())
base.append(request_uri)
base.append(host)
base.append(port)
if draft == 0:
base.append(bodyhash)
base.append(ext or '')
base_string = '\n'.join(base) + '\n'
# hmac struggles with unicode strings - http://bugs.python.org/issue5285
if isinstance(key, unicode_type):
key = key.encode('utf-8')
sign = hmac.new(key, base_string.encode('utf-8'), h)
sign = b2a_base64(sign.digest())[:-1].decode('utf-8')
header = []
header.append('MAC id="%s"' % token)
if draft != 0:
header.append('ts="%s"' % ts)
header.append('nonce="%s"' % nonce)
if bodyhash:
header.append('bodyhash="%s"' % bodyhash)
if ext:
header.append('ext="%s"' % ext)
header.append('mac="%s"' % sign)
headers = headers or {}
headers['Authorization'] = ', '.join(header)
return headers | [
"def",
"prepare_mac_header",
"(",
"token",
",",
"uri",
",",
"key",
",",
"http_method",
",",
"nonce",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
",",
"ext",
"=",
"''",
",",
"hash_algorithm",
"=",
"'hmac-sha-1'",
",",
"issue_time",
"=",
"None",
",",
"draft",
"=",
"0",
")",
":",
"http_method",
"=",
"http_method",
".",
"upper",
"(",
")",
"host",
",",
"port",
"=",
"utils",
".",
"host_from_uri",
"(",
"uri",
")",
"if",
"hash_algorithm",
".",
"lower",
"(",
")",
"==",
"'hmac-sha-1'",
":",
"h",
"=",
"hashlib",
".",
"sha1",
"elif",
"hash_algorithm",
".",
"lower",
"(",
")",
"==",
"'hmac-sha-256'",
":",
"h",
"=",
"hashlib",
".",
"sha256",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown hash algorithm'",
")",
"if",
"draft",
"==",
"0",
":",
"nonce",
"=",
"nonce",
"or",
"'{0}:{1}'",
".",
"format",
"(",
"utils",
".",
"generate_age",
"(",
"issue_time",
")",
",",
"common",
".",
"generate_nonce",
"(",
")",
")",
"else",
":",
"ts",
"=",
"common",
".",
"generate_timestamp",
"(",
")",
"nonce",
"=",
"common",
".",
"generate_nonce",
"(",
")",
"sch",
",",
"net",
",",
"path",
",",
"par",
",",
"query",
",",
"fra",
"=",
"urlparse",
"(",
"uri",
")",
"if",
"query",
":",
"request_uri",
"=",
"path",
"+",
"'?'",
"+",
"query",
"else",
":",
"request_uri",
"=",
"path",
"# Hash the body/payload",
"if",
"body",
"is",
"not",
"None",
"and",
"draft",
"==",
"0",
":",
"body",
"=",
"body",
".",
"encode",
"(",
"'utf-8'",
")",
"bodyhash",
"=",
"b2a_base64",
"(",
"h",
"(",
"body",
")",
".",
"digest",
"(",
")",
")",
"[",
":",
"-",
"1",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"bodyhash",
"=",
"''",
"# Create the normalized base string",
"base",
"=",
"[",
"]",
"if",
"draft",
"==",
"0",
":",
"base",
".",
"append",
"(",
"nonce",
")",
"else",
":",
"base",
".",
"append",
"(",
"ts",
")",
"base",
".",
"append",
"(",
"nonce",
")",
"base",
".",
"append",
"(",
"http_method",
".",
"upper",
"(",
")",
")",
"base",
".",
"append",
"(",
"request_uri",
")",
"base",
".",
"append",
"(",
"host",
")",
"base",
".",
"append",
"(",
"port",
")",
"if",
"draft",
"==",
"0",
":",
"base",
".",
"append",
"(",
"bodyhash",
")",
"base",
".",
"append",
"(",
"ext",
"or",
"''",
")",
"base_string",
"=",
"'\\n'",
".",
"join",
"(",
"base",
")",
"+",
"'\\n'",
"# hmac struggles with unicode strings - http://bugs.python.org/issue5285",
"if",
"isinstance",
"(",
"key",
",",
"unicode_type",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
"sign",
"=",
"hmac",
".",
"new",
"(",
"key",
",",
"base_string",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"h",
")",
"sign",
"=",
"b2a_base64",
"(",
"sign",
".",
"digest",
"(",
")",
")",
"[",
":",
"-",
"1",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
"header",
"=",
"[",
"]",
"header",
".",
"append",
"(",
"'MAC id=\"%s\"'",
"%",
"token",
")",
"if",
"draft",
"!=",
"0",
":",
"header",
".",
"append",
"(",
"'ts=\"%s\"'",
"%",
"ts",
")",
"header",
".",
"append",
"(",
"'nonce=\"%s\"'",
"%",
"nonce",
")",
"if",
"bodyhash",
":",
"header",
".",
"append",
"(",
"'bodyhash=\"%s\"'",
"%",
"bodyhash",
")",
"if",
"ext",
":",
"header",
".",
"append",
"(",
"'ext=\"%s\"'",
"%",
"ext",
")",
"header",
".",
"append",
"(",
"'mac=\"%s\"'",
"%",
"sign",
")",
"headers",
"=",
"headers",
"or",
"{",
"}",
"headers",
"[",
"'Authorization'",
"]",
"=",
"', '",
".",
"join",
"(",
"header",
")",
"return",
"headers"
] | Add an `MAC Access Authentication`_ signature to headers.
Unlike OAuth 1, this HMAC signature does not require inclusion of the
request payload/body, neither does it use a combination of client_secret
and token_secret but rather a mac_key provided together with the access
token.
Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256",
`extension algorithms`_ are not supported.
Example MAC Authorization header, linebreaks added for clarity
Authorization: MAC id="h480djs93hd8",
nonce="1336363200:dj83hs9s",
mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM="
.. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01
.. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1
:param token:
:param uri: Request URI.
:param key: MAC given provided by token endpoint.
:param http_method: HTTP Request method.
:param nonce:
:param headers: Request headers as a dictionary.
:param body:
:param ext:
:param hash_algorithm: HMAC algorithm provided by token endpoint.
:param issue_time: Time when the MAC credentials were issued (datetime).
:param draft: MAC authentication specification version.
:return: headers dictionary with the authorization field added. | [
"Add",
"an",
"MAC",
"Access",
"Authentication",
"_",
"signature",
"to",
"headers",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L73-L179 |
229,835 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/tokens.py | get_token_from_header | def get_token_from_header(request):
"""
Helper function to extract a token from the request header.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:return: Return the token or None if the Authorization header is malformed.
"""
token = None
if 'Authorization' in request.headers:
split_header = request.headers.get('Authorization').split()
if len(split_header) == 2 and split_header[0] == 'Bearer':
token = split_header[1]
else:
token = request.access_token
return token | python | def get_token_from_header(request):
"""
Helper function to extract a token from the request header.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:return: Return the token or None if the Authorization header is malformed.
"""
token = None
if 'Authorization' in request.headers:
split_header = request.headers.get('Authorization').split()
if len(split_header) == 2 and split_header[0] == 'Bearer':
token = split_header[1]
else:
token = request.access_token
return token | [
"def",
"get_token_from_header",
"(",
"request",
")",
":",
"token",
"=",
"None",
"if",
"'Authorization'",
"in",
"request",
".",
"headers",
":",
"split_header",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Authorization'",
")",
".",
"split",
"(",
")",
"if",
"len",
"(",
"split_header",
")",
"==",
"2",
"and",
"split_header",
"[",
"0",
"]",
"==",
"'Bearer'",
":",
"token",
"=",
"split_header",
"[",
"1",
"]",
"else",
":",
"token",
"=",
"request",
".",
"access_token",
"return",
"token"
] | Helper function to extract a token from the request header.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:return: Return the token or None if the Authorization header is malformed. | [
"Helper",
"function",
"to",
"extract",
"a",
"token",
"from",
"the",
"request",
"header",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L245-L262 |
229,836 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/tokens.py | BearerToken.create_token | def create_token(self, request, refresh_token=False, **kwargs):
"""
Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token:
"""
if "save_token" in kwargs:
warnings.warn("`save_token` has been deprecated, it was not called internally."
"If you do, call `request_validator.save_token()` instead.",
DeprecationWarning)
if callable(self.expires_in):
expires_in = self.expires_in(request)
else:
expires_in = self.expires_in
request.expires_in = expires_in
token = {
'access_token': self.token_generator(request),
'expires_in': expires_in,
'token_type': 'Bearer',
}
# If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but
# there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so
# all tokens issued are for the entire set of requested scopes.
if request.scopes is not None:
token['scope'] = ' '.join(request.scopes)
if refresh_token:
if (request.refresh_token and
not self.request_validator.rotate_refresh_token(request)):
token['refresh_token'] = request.refresh_token
else:
token['refresh_token'] = self.refresh_token_generator(request)
token.update(request.extra_credentials or {})
return OAuth2Token(token) | python | def create_token(self, request, refresh_token=False, **kwargs):
"""
Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token:
"""
if "save_token" in kwargs:
warnings.warn("`save_token` has been deprecated, it was not called internally."
"If you do, call `request_validator.save_token()` instead.",
DeprecationWarning)
if callable(self.expires_in):
expires_in = self.expires_in(request)
else:
expires_in = self.expires_in
request.expires_in = expires_in
token = {
'access_token': self.token_generator(request),
'expires_in': expires_in,
'token_type': 'Bearer',
}
# If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but
# there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so
# all tokens issued are for the entire set of requested scopes.
if request.scopes is not None:
token['scope'] = ' '.join(request.scopes)
if refresh_token:
if (request.refresh_token and
not self.request_validator.rotate_refresh_token(request)):
token['refresh_token'] = request.refresh_token
else:
token['refresh_token'] = self.refresh_token_generator(request)
token.update(request.extra_credentials or {})
return OAuth2Token(token) | [
"def",
"create_token",
"(",
"self",
",",
"request",
",",
"refresh_token",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"save_token\"",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"`save_token` has been deprecated, it was not called internally.\"",
"\"If you do, call `request_validator.save_token()` instead.\"",
",",
"DeprecationWarning",
")",
"if",
"callable",
"(",
"self",
".",
"expires_in",
")",
":",
"expires_in",
"=",
"self",
".",
"expires_in",
"(",
"request",
")",
"else",
":",
"expires_in",
"=",
"self",
".",
"expires_in",
"request",
".",
"expires_in",
"=",
"expires_in",
"token",
"=",
"{",
"'access_token'",
":",
"self",
".",
"token_generator",
"(",
"request",
")",
",",
"'expires_in'",
":",
"expires_in",
",",
"'token_type'",
":",
"'Bearer'",
",",
"}",
"# If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but",
"# there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so",
"# all tokens issued are for the entire set of requested scopes.",
"if",
"request",
".",
"scopes",
"is",
"not",
"None",
":",
"token",
"[",
"'scope'",
"]",
"=",
"' '",
".",
"join",
"(",
"request",
".",
"scopes",
")",
"if",
"refresh_token",
":",
"if",
"(",
"request",
".",
"refresh_token",
"and",
"not",
"self",
".",
"request_validator",
".",
"rotate_refresh_token",
"(",
"request",
")",
")",
":",
"token",
"[",
"'refresh_token'",
"]",
"=",
"request",
".",
"refresh_token",
"else",
":",
"token",
"[",
"'refresh_token'",
"]",
"=",
"self",
".",
"refresh_token_generator",
"(",
"request",
")",
"token",
".",
"update",
"(",
"request",
".",
"extra_credentials",
"or",
"{",
"}",
")",
"return",
"OAuth2Token",
"(",
"token",
")"
] | Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token: | [
"Create",
"a",
"BearerToken",
"by",
"default",
"without",
"refresh",
"token",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L300-L340 |
229,837 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/utils.py | list_to_scope | def list_to_scope(scope):
"""Convert a list of scopes to a space separated string."""
if isinstance(scope, unicode_type) or scope is None:
return scope
elif isinstance(scope, (set, tuple, list)):
return " ".join([unicode_type(s) for s in scope])
else:
raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope) | python | def list_to_scope(scope):
"""Convert a list of scopes to a space separated string."""
if isinstance(scope, unicode_type) or scope is None:
return scope
elif isinstance(scope, (set, tuple, list)):
return " ".join([unicode_type(s) for s in scope])
else:
raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope) | [
"def",
"list_to_scope",
"(",
"scope",
")",
":",
"if",
"isinstance",
"(",
"scope",
",",
"unicode_type",
")",
"or",
"scope",
"is",
"None",
":",
"return",
"scope",
"elif",
"isinstance",
"(",
"scope",
",",
"(",
"set",
",",
"tuple",
",",
"list",
")",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"[",
"unicode_type",
"(",
"s",
")",
"for",
"s",
"in",
"scope",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid scope (%s), must be string, tuple, set, or list.\"",
"%",
"scope",
")"
] | Convert a list of scopes to a space separated string. | [
"Convert",
"a",
"list",
"of",
"scopes",
"to",
"a",
"space",
"separated",
"string",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L25-L32 |
229,838 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/utils.py | scope_to_list | def scope_to_list(scope):
"""Convert a space separated string to a list of scopes."""
if isinstance(scope, (tuple, list, set)):
return [unicode_type(s) for s in scope]
elif scope is None:
return None
else:
return scope.strip().split(" ") | python | def scope_to_list(scope):
"""Convert a space separated string to a list of scopes."""
if isinstance(scope, (tuple, list, set)):
return [unicode_type(s) for s in scope]
elif scope is None:
return None
else:
return scope.strip().split(" ") | [
"def",
"scope_to_list",
"(",
"scope",
")",
":",
"if",
"isinstance",
"(",
"scope",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"return",
"[",
"unicode_type",
"(",
"s",
")",
"for",
"s",
"in",
"scope",
"]",
"elif",
"scope",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"scope",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")"
] | Convert a space separated string to a list of scopes. | [
"Convert",
"a",
"space",
"separated",
"string",
"to",
"a",
"list",
"of",
"scopes",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L35-L42 |
229,839 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/utils.py | host_from_uri | def host_from_uri(uri):
"""Extract hostname and port from URI.
Will use default port for HTTP and HTTPS if none is present in the URI.
"""
default_ports = {
'HTTP': '80',
'HTTPS': '443',
}
sch, netloc, path, par, query, fra = urlparse(uri)
if ':' in netloc:
netloc, port = netloc.split(':', 1)
else:
port = default_ports.get(sch.upper())
return netloc, port | python | def host_from_uri(uri):
"""Extract hostname and port from URI.
Will use default port for HTTP and HTTPS if none is present in the URI.
"""
default_ports = {
'HTTP': '80',
'HTTPS': '443',
}
sch, netloc, path, par, query, fra = urlparse(uri)
if ':' in netloc:
netloc, port = netloc.split(':', 1)
else:
port = default_ports.get(sch.upper())
return netloc, port | [
"def",
"host_from_uri",
"(",
"uri",
")",
":",
"default_ports",
"=",
"{",
"'HTTP'",
":",
"'80'",
",",
"'HTTPS'",
":",
"'443'",
",",
"}",
"sch",
",",
"netloc",
",",
"path",
",",
"par",
",",
"query",
",",
"fra",
"=",
"urlparse",
"(",
"uri",
")",
"if",
"':'",
"in",
"netloc",
":",
"netloc",
",",
"port",
"=",
"netloc",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else",
":",
"port",
"=",
"default_ports",
".",
"get",
"(",
"sch",
".",
"upper",
"(",
")",
")",
"return",
"netloc",
",",
"port"
] | Extract hostname and port from URI.
Will use default port for HTTP and HTTPS if none is present in the URI. | [
"Extract",
"hostname",
"and",
"port",
"from",
"URI",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L52-L68 |
229,840 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/utils.py | escape | def escape(u):
"""Escape a string in an OAuth-compatible fashion.
TODO: verify whether this can in fact be used for OAuth 2
"""
if not isinstance(u, unicode_type):
raise ValueError('Only unicode objects are escapable.')
return quote(u.encode('utf-8'), safe=b'~') | python | def escape(u):
"""Escape a string in an OAuth-compatible fashion.
TODO: verify whether this can in fact be used for OAuth 2
"""
if not isinstance(u, unicode_type):
raise ValueError('Only unicode objects are escapable.')
return quote(u.encode('utf-8'), safe=b'~') | [
"def",
"escape",
"(",
"u",
")",
":",
"if",
"not",
"isinstance",
"(",
"u",
",",
"unicode_type",
")",
":",
"raise",
"ValueError",
"(",
"'Only unicode objects are escapable.'",
")",
"return",
"quote",
"(",
"u",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"b'~'",
")"
] | Escape a string in an OAuth-compatible fashion.
TODO: verify whether this can in fact be used for OAuth 2 | [
"Escape",
"a",
"string",
"in",
"an",
"OAuth",
"-",
"compatible",
"fashion",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L71-L79 |
229,841 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/utils.py | generate_age | def generate_age(issue_time):
"""Generate a age parameter for MAC authentication draft 00."""
td = datetime.datetime.now() - issue_time
age = (td.microseconds + (td.seconds + td.days * 24 * 3600)
* 10 ** 6) / 10 ** 6
return unicode_type(age) | python | def generate_age(issue_time):
"""Generate a age parameter for MAC authentication draft 00."""
td = datetime.datetime.now() - issue_time
age = (td.microseconds + (td.seconds + td.days * 24 * 3600)
* 10 ** 6) / 10 ** 6
return unicode_type(age) | [
"def",
"generate_age",
"(",
"issue_time",
")",
":",
"td",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"issue_time",
"age",
"=",
"(",
"td",
".",
"microseconds",
"+",
"(",
"td",
".",
"seconds",
"+",
"td",
".",
"days",
"*",
"24",
"*",
"3600",
")",
"*",
"10",
"**",
"6",
")",
"/",
"10",
"**",
"6",
"return",
"unicode_type",
"(",
"age",
")"
] | Generate a age parameter for MAC authentication draft 00. | [
"Generate",
"a",
"age",
"parameter",
"for",
"MAC",
"authentication",
"draft",
"00",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L82-L87 |
229,842 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/grant_types/implicit.py | ImplicitGrant.create_token_response | def create_token_response(self, request, token_handler):
"""Return token or error embedded in the URI fragment.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token_handler: A token handler instance, for example of type
oauthlib.oauth2.BearerToken.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format, per
`Appendix B`_:
access_token
REQUIRED. The access token issued by the authorization server.
token_type
REQUIRED. The type of the token issued as described in
`Section 7.1`_. Value is case insensitive.
expires_in
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
scope
OPTIONAL, if identical to the scope requested by the client;
otherwise, REQUIRED. The scope of the access token as
described by `Section 3.3`_.
state
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
The authorization server MUST NOT issue a refresh token.
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
"""
try:
self.validate_token_request(request)
# If the request fails due to a missing, invalid, or mismatching
# redirection URI, or if the client identifier is missing or invalid,
# the authorization server SHOULD inform the resource owner of the
# error and MUST NOT automatically redirect the user-agent to the
# invalid redirection URI.
except errors.FatalClientError as e:
log.debug('Fatal client error during validation of %r. %r.',
request, e)
raise
# If the resource owner denies the access request or if the request
# fails for reasons other than a missing or invalid redirection URI,
# the authorization server informs the client by adding the following
# parameters to the fragment component of the redirection URI using the
# "application/x-www-form-urlencoded" format, per Appendix B:
# https://tools.ietf.org/html/rfc6749#appendix-B
except errors.OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples,
fragment=True)}, None, 302
# In OIDC implicit flow it is possible to have a request_type that does not include the access_token!
# "id_token token" - return the access token and the id token
# "id_token" - don't return the access token
if "token" in request.response_type.split():
token = token_handler.create_token(request, refresh_token=False)
else:
token = {}
if request.state is not None:
token['state'] = request.state
for modifier in self._token_modifiers:
token = modifier(token, token_handler, request)
# In OIDC implicit flow it is possible to have a request_type that does
# not include the access_token! In this case there is no need to save a token.
if "token" in request.response_type.split():
self.request_validator.save_token(token, request)
return self.prepare_authorization_response(
request, token, {}, None, 302) | python | def create_token_response(self, request, token_handler):
"""Return token or error embedded in the URI fragment.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token_handler: A token handler instance, for example of type
oauthlib.oauth2.BearerToken.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format, per
`Appendix B`_:
access_token
REQUIRED. The access token issued by the authorization server.
token_type
REQUIRED. The type of the token issued as described in
`Section 7.1`_. Value is case insensitive.
expires_in
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
scope
OPTIONAL, if identical to the scope requested by the client;
otherwise, REQUIRED. The scope of the access token as
described by `Section 3.3`_.
state
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
The authorization server MUST NOT issue a refresh token.
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
"""
try:
self.validate_token_request(request)
# If the request fails due to a missing, invalid, or mismatching
# redirection URI, or if the client identifier is missing or invalid,
# the authorization server SHOULD inform the resource owner of the
# error and MUST NOT automatically redirect the user-agent to the
# invalid redirection URI.
except errors.FatalClientError as e:
log.debug('Fatal client error during validation of %r. %r.',
request, e)
raise
# If the resource owner denies the access request or if the request
# fails for reasons other than a missing or invalid redirection URI,
# the authorization server informs the client by adding the following
# parameters to the fragment component of the redirection URI using the
# "application/x-www-form-urlencoded" format, per Appendix B:
# https://tools.ietf.org/html/rfc6749#appendix-B
except errors.OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples,
fragment=True)}, None, 302
# In OIDC implicit flow it is possible to have a request_type that does not include the access_token!
# "id_token token" - return the access token and the id token
# "id_token" - don't return the access token
if "token" in request.response_type.split():
token = token_handler.create_token(request, refresh_token=False)
else:
token = {}
if request.state is not None:
token['state'] = request.state
for modifier in self._token_modifiers:
token = modifier(token, token_handler, request)
# In OIDC implicit flow it is possible to have a request_type that does
# not include the access_token! In this case there is no need to save a token.
if "token" in request.response_type.split():
self.request_validator.save_token(token, request)
return self.prepare_authorization_response(
request, token, {}, None, 302) | [
"def",
"create_token_response",
"(",
"self",
",",
"request",
",",
"token_handler",
")",
":",
"try",
":",
"self",
".",
"validate_token_request",
"(",
"request",
")",
"# If the request fails due to a missing, invalid, or mismatching",
"# redirection URI, or if the client identifier is missing or invalid,",
"# the authorization server SHOULD inform the resource owner of the",
"# error and MUST NOT automatically redirect the user-agent to the",
"# invalid redirection URI.",
"except",
"errors",
".",
"FatalClientError",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'Fatal client error during validation of %r. %r.'",
",",
"request",
",",
"e",
")",
"raise",
"# If the resource owner denies the access request or if the request",
"# fails for reasons other than a missing or invalid redirection URI,",
"# the authorization server informs the client by adding the following",
"# parameters to the fragment component of the redirection URI using the",
"# \"application/x-www-form-urlencoded\" format, per Appendix B:",
"# https://tools.ietf.org/html/rfc6749#appendix-B",
"except",
"errors",
".",
"OAuth2Error",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'Client error during validation of %r. %r.'",
",",
"request",
",",
"e",
")",
"return",
"{",
"'Location'",
":",
"common",
".",
"add_params_to_uri",
"(",
"request",
".",
"redirect_uri",
",",
"e",
".",
"twotuples",
",",
"fragment",
"=",
"True",
")",
"}",
",",
"None",
",",
"302",
"# In OIDC implicit flow it is possible to have a request_type that does not include the access_token!",
"# \"id_token token\" - return the access token and the id token",
"# \"id_token\" - don't return the access token",
"if",
"\"token\"",
"in",
"request",
".",
"response_type",
".",
"split",
"(",
")",
":",
"token",
"=",
"token_handler",
".",
"create_token",
"(",
"request",
",",
"refresh_token",
"=",
"False",
")",
"else",
":",
"token",
"=",
"{",
"}",
"if",
"request",
".",
"state",
"is",
"not",
"None",
":",
"token",
"[",
"'state'",
"]",
"=",
"request",
".",
"state",
"for",
"modifier",
"in",
"self",
".",
"_token_modifiers",
":",
"token",
"=",
"modifier",
"(",
"token",
",",
"token_handler",
",",
"request",
")",
"# In OIDC implicit flow it is possible to have a request_type that does",
"# not include the access_token! In this case there is no need to save a token.",
"if",
"\"token\"",
"in",
"request",
".",
"response_type",
".",
"split",
"(",
")",
":",
"self",
".",
"request_validator",
".",
"save_token",
"(",
"token",
",",
"request",
")",
"return",
"self",
".",
"prepare_authorization_response",
"(",
"request",
",",
"token",
",",
"{",
"}",
",",
"None",
",",
"302",
")"
] | Return token or error embedded in the URI fragment.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token_handler: A token handler instance, for example of type
oauthlib.oauth2.BearerToken.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format, per
`Appendix B`_:
access_token
REQUIRED. The access token issued by the authorization server.
token_type
REQUIRED. The type of the token issued as described in
`Section 7.1`_. Value is case insensitive.
expires_in
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
scope
OPTIONAL, if identical to the scope requested by the client;
otherwise, REQUIRED. The scope of the access token as
described by `Section 3.3`_.
state
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
The authorization server MUST NOT issue a refresh token.
.. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B
.. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
.. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 | [
"Return",
"token",
"or",
"error",
"embedded",
"in",
"the",
"URI",
"fragment",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/implicit.py#L168-L256 |
229,843 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/grant_types/implicit.py | ImplicitGrant.validate_token_request | def validate_token_request(self, request):
"""Check the token request for normal and fatal errors.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
This method is very similar to validate_authorization_request in
the AuthorizationCodeGrant but differ in a few subtle areas.
A normal error could be a missing response_type parameter or the client
attempting to access scope it is not allowed to ask authorization for.
Normal errors can safely be included in the redirection URI and
sent back to the client.
Fatal errors occur when the client_id or redirect_uri is invalid or
missing. These must be caught by the provider and handled, how this
is done is outside of the scope of OAuthLib but showing an error
page describing the issue is a good idea.
"""
# First check for fatal errors
# If the request fails due to a missing, invalid, or mismatching
# redirection URI, or if the client identifier is missing or invalid,
# the authorization server SHOULD inform the resource owner of the
# error and MUST NOT automatically redirect the user-agent to the
# invalid redirection URI.
# First check duplicate parameters
for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'):
try:
duplicate_params = request.duplicate_params
except ValueError:
raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request)
if param in duplicate_params:
raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request)
# REQUIRED. The client identifier as described in Section 2.2.
# https://tools.ietf.org/html/rfc6749#section-2.2
if not request.client_id:
raise errors.MissingClientIdError(request=request)
if not self.request_validator.validate_client_id(request.client_id, request):
raise errors.InvalidClientIdError(request=request)
# OPTIONAL. As described in Section 3.1.2.
# https://tools.ietf.org/html/rfc6749#section-3.1.2
self._handle_redirects(request)
# Then check for normal errors.
request_info = self._run_custom_validators(request,
self.custom_validators.all_pre)
# If the resource owner denies the access request or if the request
# fails for reasons other than a missing or invalid redirection URI,
# the authorization server informs the client by adding the following
# parameters to the fragment component of the redirection URI using the
# "application/x-www-form-urlencoded" format, per Appendix B.
# https://tools.ietf.org/html/rfc6749#appendix-B
# Note that the correct parameters to be added are automatically
# populated through the use of specific exceptions
# REQUIRED.
if request.response_type is None:
raise errors.MissingResponseTypeError(request=request)
# Value MUST be one of our registered types: "token" by default or if using OIDC "id_token" or "id_token token"
elif not set(request.response_type.split()).issubset(self.response_types):
raise errors.UnsupportedResponseTypeError(request=request)
log.debug('Validating use of response_type token for client %r (%r).',
request.client_id, request.client)
if not self.request_validator.validate_response_type(request.client_id,
request.response_type,
request.client, request):
log.debug('Client %s is not authorized to use response_type %s.',
request.client_id, request.response_type)
raise errors.UnauthorizedClientError(request=request)
# OPTIONAL. The scope of the access request as described by Section 3.3
# https://tools.ietf.org/html/rfc6749#section-3.3
self.validate_scopes(request)
request_info.update({
'client_id': request.client_id,
'redirect_uri': request.redirect_uri,
'response_type': request.response_type,
'state': request.state,
'request': request,
})
request_info = self._run_custom_validators(
request,
self.custom_validators.all_post,
request_info
)
return request.scopes, request_info | python | def validate_token_request(self, request):
"""Check the token request for normal and fatal errors.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
This method is very similar to validate_authorization_request in
the AuthorizationCodeGrant but differ in a few subtle areas.
A normal error could be a missing response_type parameter or the client
attempting to access scope it is not allowed to ask authorization for.
Normal errors can safely be included in the redirection URI and
sent back to the client.
Fatal errors occur when the client_id or redirect_uri is invalid or
missing. These must be caught by the provider and handled, how this
is done is outside of the scope of OAuthLib but showing an error
page describing the issue is a good idea.
"""
# First check for fatal errors
# If the request fails due to a missing, invalid, or mismatching
# redirection URI, or if the client identifier is missing or invalid,
# the authorization server SHOULD inform the resource owner of the
# error and MUST NOT automatically redirect the user-agent to the
# invalid redirection URI.
# First check duplicate parameters
for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'):
try:
duplicate_params = request.duplicate_params
except ValueError:
raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request)
if param in duplicate_params:
raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request)
# REQUIRED. The client identifier as described in Section 2.2.
# https://tools.ietf.org/html/rfc6749#section-2.2
if not request.client_id:
raise errors.MissingClientIdError(request=request)
if not self.request_validator.validate_client_id(request.client_id, request):
raise errors.InvalidClientIdError(request=request)
# OPTIONAL. As described in Section 3.1.2.
# https://tools.ietf.org/html/rfc6749#section-3.1.2
self._handle_redirects(request)
# Then check for normal errors.
request_info = self._run_custom_validators(request,
self.custom_validators.all_pre)
# If the resource owner denies the access request or if the request
# fails for reasons other than a missing or invalid redirection URI,
# the authorization server informs the client by adding the following
# parameters to the fragment component of the redirection URI using the
# "application/x-www-form-urlencoded" format, per Appendix B.
# https://tools.ietf.org/html/rfc6749#appendix-B
# Note that the correct parameters to be added are automatically
# populated through the use of specific exceptions
# REQUIRED.
if request.response_type is None:
raise errors.MissingResponseTypeError(request=request)
# Value MUST be one of our registered types: "token" by default or if using OIDC "id_token" or "id_token token"
elif not set(request.response_type.split()).issubset(self.response_types):
raise errors.UnsupportedResponseTypeError(request=request)
log.debug('Validating use of response_type token for client %r (%r).',
request.client_id, request.client)
if not self.request_validator.validate_response_type(request.client_id,
request.response_type,
request.client, request):
log.debug('Client %s is not authorized to use response_type %s.',
request.client_id, request.response_type)
raise errors.UnauthorizedClientError(request=request)
# OPTIONAL. The scope of the access request as described by Section 3.3
# https://tools.ietf.org/html/rfc6749#section-3.3
self.validate_scopes(request)
request_info.update({
'client_id': request.client_id,
'redirect_uri': request.redirect_uri,
'response_type': request.response_type,
'state': request.state,
'request': request,
})
request_info = self._run_custom_validators(
request,
self.custom_validators.all_post,
request_info
)
return request.scopes, request_info | [
"def",
"validate_token_request",
"(",
"self",
",",
"request",
")",
":",
"# First check for fatal errors",
"# If the request fails due to a missing, invalid, or mismatching",
"# redirection URI, or if the client identifier is missing or invalid,",
"# the authorization server SHOULD inform the resource owner of the",
"# error and MUST NOT automatically redirect the user-agent to the",
"# invalid redirection URI.",
"# First check duplicate parameters",
"for",
"param",
"in",
"(",
"'client_id'",
",",
"'response_type'",
",",
"'redirect_uri'",
",",
"'scope'",
",",
"'state'",
")",
":",
"try",
":",
"duplicate_params",
"=",
"request",
".",
"duplicate_params",
"except",
"ValueError",
":",
"raise",
"errors",
".",
"InvalidRequestFatalError",
"(",
"description",
"=",
"'Unable to parse query string'",
",",
"request",
"=",
"request",
")",
"if",
"param",
"in",
"duplicate_params",
":",
"raise",
"errors",
".",
"InvalidRequestFatalError",
"(",
"description",
"=",
"'Duplicate %s parameter.'",
"%",
"param",
",",
"request",
"=",
"request",
")",
"# REQUIRED. The client identifier as described in Section 2.2.",
"# https://tools.ietf.org/html/rfc6749#section-2.2",
"if",
"not",
"request",
".",
"client_id",
":",
"raise",
"errors",
".",
"MissingClientIdError",
"(",
"request",
"=",
"request",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_client_id",
"(",
"request",
".",
"client_id",
",",
"request",
")",
":",
"raise",
"errors",
".",
"InvalidClientIdError",
"(",
"request",
"=",
"request",
")",
"# OPTIONAL. As described in Section 3.1.2.",
"# https://tools.ietf.org/html/rfc6749#section-3.1.2",
"self",
".",
"_handle_redirects",
"(",
"request",
")",
"# Then check for normal errors.",
"request_info",
"=",
"self",
".",
"_run_custom_validators",
"(",
"request",
",",
"self",
".",
"custom_validators",
".",
"all_pre",
")",
"# If the resource owner denies the access request or if the request",
"# fails for reasons other than a missing or invalid redirection URI,",
"# the authorization server informs the client by adding the following",
"# parameters to the fragment component of the redirection URI using the",
"# \"application/x-www-form-urlencoded\" format, per Appendix B.",
"# https://tools.ietf.org/html/rfc6749#appendix-B",
"# Note that the correct parameters to be added are automatically",
"# populated through the use of specific exceptions",
"# REQUIRED.",
"if",
"request",
".",
"response_type",
"is",
"None",
":",
"raise",
"errors",
".",
"MissingResponseTypeError",
"(",
"request",
"=",
"request",
")",
"# Value MUST be one of our registered types: \"token\" by default or if using OIDC \"id_token\" or \"id_token token\"",
"elif",
"not",
"set",
"(",
"request",
".",
"response_type",
".",
"split",
"(",
")",
")",
".",
"issubset",
"(",
"self",
".",
"response_types",
")",
":",
"raise",
"errors",
".",
"UnsupportedResponseTypeError",
"(",
"request",
"=",
"request",
")",
"log",
".",
"debug",
"(",
"'Validating use of response_type token for client %r (%r).'",
",",
"request",
".",
"client_id",
",",
"request",
".",
"client",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_response_type",
"(",
"request",
".",
"client_id",
",",
"request",
".",
"response_type",
",",
"request",
".",
"client",
",",
"request",
")",
":",
"log",
".",
"debug",
"(",
"'Client %s is not authorized to use response_type %s.'",
",",
"request",
".",
"client_id",
",",
"request",
".",
"response_type",
")",
"raise",
"errors",
".",
"UnauthorizedClientError",
"(",
"request",
"=",
"request",
")",
"# OPTIONAL. The scope of the access request as described by Section 3.3",
"# https://tools.ietf.org/html/rfc6749#section-3.3",
"self",
".",
"validate_scopes",
"(",
"request",
")",
"request_info",
".",
"update",
"(",
"{",
"'client_id'",
":",
"request",
".",
"client_id",
",",
"'redirect_uri'",
":",
"request",
".",
"redirect_uri",
",",
"'response_type'",
":",
"request",
".",
"response_type",
",",
"'state'",
":",
"request",
".",
"state",
",",
"'request'",
":",
"request",
",",
"}",
")",
"request_info",
"=",
"self",
".",
"_run_custom_validators",
"(",
"request",
",",
"self",
".",
"custom_validators",
".",
"all_post",
",",
"request_info",
")",
"return",
"request",
".",
"scopes",
",",
"request_info"
] | Check the token request for normal and fatal errors.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
This method is very similar to validate_authorization_request in
the AuthorizationCodeGrant but differ in a few subtle areas.
A normal error could be a missing response_type parameter or the client
attempting to access scope it is not allowed to ask authorization for.
Normal errors can safely be included in the redirection URI and
sent back to the client.
Fatal errors occur when the client_id or redirect_uri is invalid or
missing. These must be caught by the provider and handled, how this
is done is outside of the scope of OAuthLib but showing an error
page describing the issue is a good idea. | [
"Check",
"the",
"token",
"request",
"for",
"normal",
"and",
"fatal",
"errors",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/implicit.py#L265-L364 |
229,844 | oauthlib/oauthlib | oauthlib/openid/connect/core/grant_types/base.py | GrantTypeBase.validate_authorization_request | def validate_authorization_request(self, request):
"""Validates the OpenID Connect authorization request parameters.
:returns: (list of scopes, dict of request info)
"""
# If request.prompt is 'none' then no login/authorization form should
# be presented to the user. Instead, a silent login/authorization
# should be performed.
if request.prompt == 'none':
raise OIDCNoPrompt()
else:
return self.proxy_target.validate_authorization_request(request) | python | def validate_authorization_request(self, request):
"""Validates the OpenID Connect authorization request parameters.
:returns: (list of scopes, dict of request info)
"""
# If request.prompt is 'none' then no login/authorization form should
# be presented to the user. Instead, a silent login/authorization
# should be performed.
if request.prompt == 'none':
raise OIDCNoPrompt()
else:
return self.proxy_target.validate_authorization_request(request) | [
"def",
"validate_authorization_request",
"(",
"self",
",",
"request",
")",
":",
"# If request.prompt is 'none' then no login/authorization form should",
"# be presented to the user. Instead, a silent login/authorization",
"# should be performed.",
"if",
"request",
".",
"prompt",
"==",
"'none'",
":",
"raise",
"OIDCNoPrompt",
"(",
")",
"else",
":",
"return",
"self",
".",
"proxy_target",
".",
"validate_authorization_request",
"(",
"request",
")"
] | Validates the OpenID Connect authorization request parameters.
:returns: (list of scopes, dict of request info) | [
"Validates",
"the",
"OpenID",
"Connect",
"authorization",
"request",
"parameters",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/base.py#L27-L38 |
229,845 | oauthlib/oauthlib | oauthlib/openid/connect/core/grant_types/base.py | GrantTypeBase.openid_authorization_validator | def openid_authorization_validator(self, request):
"""Perform OpenID Connect specific authorization request validation.
nonce
OPTIONAL. String value used to associate a Client session with
an ID Token, and to mitigate replay attacks. The value is
passed through unmodified from the Authentication Request to
the ID Token. Sufficient entropy MUST be present in the nonce
values used to prevent attackers from guessing values
display
OPTIONAL. ASCII string value that specifies how the
Authorization Server displays the authentication and consent
user interface pages to the End-User. The defined values are:
page - The Authorization Server SHOULD display the
authentication and consent UI consistent with a full User
Agent page view. If the display parameter is not specified,
this is the default display mode.
popup - The Authorization Server SHOULD display the
authentication and consent UI consistent with a popup User
Agent window. The popup User Agent window should be of an
appropriate size for a login-focused dialog and should not
obscure the entire window that it is popping up over.
touch - The Authorization Server SHOULD display the
authentication and consent UI consistent with a device that
leverages a touch interface.
wap - The Authorization Server SHOULD display the
authentication and consent UI consistent with a "feature
phone" type display.
The Authorization Server MAY also attempt to detect the
capabilities of the User Agent and present an appropriate
display.
prompt
OPTIONAL. Space delimited, case sensitive list of ASCII string
values that specifies whether the Authorization Server prompts
the End-User for reauthentication and consent. The defined
values are:
none - The Authorization Server MUST NOT display any
authentication or consent user interface pages. An error is
returned if an End-User is not already authenticated or the
Client does not have pre-configured consent for the
requested Claims or does not fulfill other conditions for
processing the request. The error code will typically be
login_required, interaction_required, or another code
defined in Section 3.1.2.6. This can be used as a method to
check for existing authentication and/or consent.
login - The Authorization Server SHOULD prompt the End-User
for reauthentication. If it cannot reauthenticate the
End-User, it MUST return an error, typically
login_required.
consent - The Authorization Server SHOULD prompt the
End-User for consent before returning information to the
Client. If it cannot obtain consent, it MUST return an
error, typically consent_required.
select_account - The Authorization Server SHOULD prompt the
End-User to select a user account. This enables an End-User
who has multiple accounts at the Authorization Server to
select amongst the multiple accounts that they might have
current sessions for. If it cannot obtain an account
selection choice made by the End-User, it MUST return an
error, typically account_selection_required.
The prompt parameter can be used by the Client to make sure
that the End-User is still present for the current session or
to bring attention to the request. If this parameter contains
none with any other value, an error is returned.
max_age
OPTIONAL. Maximum Authentication Age. Specifies the allowable
elapsed time in seconds since the last time the End-User was
actively authenticated by the OP. If the elapsed time is
greater than this value, the OP MUST attempt to actively
re-authenticate the End-User. (The max_age request parameter
corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age
request parameter.) When max_age is used, the ID Token returned
MUST include an auth_time Claim Value.
ui_locales
OPTIONAL. End-User's preferred languages and scripts for the
user interface, represented as a space-separated list of BCP47
[RFC5646] language tag values, ordered by preference. For
instance, the value "fr-CA fr en" represents a preference for
French as spoken in Canada, then French (without a region
designation), followed by English (without a region
designation). An error SHOULD NOT result if some or all of the
requested locales are not supported by the OpenID Provider.
id_token_hint
OPTIONAL. ID Token previously issued by the Authorization
Server being passed as a hint about the End-User's current or
past authenticated session with the Client. If the End-User
identified by the ID Token is logged in or is logged in by the
request, then the Authorization Server returns a positive
response; otherwise, it SHOULD return an error, such as
login_required. When possible, an id_token_hint SHOULD be
present when prompt=none is used and an invalid_request error
MAY be returned if it is not; however, the server SHOULD
respond successfully when possible, even if it is not present.
The Authorization Server need not be listed as an audience of
the ID Token when it is used as an id_token_hint value. If the
ID Token received by the RP from the OP is encrypted, to use it
as an id_token_hint, the Client MUST decrypt the signed ID
Token contained within the encrypted ID Token. The Client MAY
re-encrypt the signed ID token to the Authentication Server
using a key that enables the server to decrypt the ID Token,
and use the re-encrypted ID token as the id_token_hint value.
login_hint
OPTIONAL. Hint to the Authorization Server about the login
identifier the End-User might use to log in (if necessary).
This hint can be used by an RP if it first asks the End-User
for their e-mail address (or other identifier) and then wants
to pass that value as a hint to the discovered authorization
service. It is RECOMMENDED that the hint value match the value
used for discovery. This value MAY also be a phone number in
the format specified for the phone_number Claim. The use of
this parameter is left to the OP's discretion.
acr_values
OPTIONAL. Requested Authentication Context Class Reference
values. Space-separated string that specifies the acr values
that the Authorization Server is being requested to use for
processing this Authentication Request, with the values
appearing in order of preference. The Authentication Context
Class satisfied by the authentication performed is returned as
the acr Claim Value, as specified in Section 2. The acr Claim
is requested as a Voluntary Claim by this parameter.
"""
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return {}
prompt = request.prompt if request.prompt else []
if hasattr(prompt, 'split'):
prompt = prompt.strip().split()
prompt = set(prompt)
if 'none' in prompt:
if len(prompt) > 1:
msg = "Prompt none is mutually exclusive with other values."
raise InvalidRequestError(request=request, description=msg)
if not self.request_validator.validate_silent_login(request):
raise LoginRequired(request=request)
if not self.request_validator.validate_silent_authorization(request):
raise ConsentRequired(request=request)
self._inflate_claims(request)
if not self.request_validator.validate_user_match(
request.id_token_hint, request.scopes, request.claims, request):
msg = "Session user does not match client supplied user."
raise LoginRequired(request=request, description=msg)
request_info = {
'display': request.display,
'nonce': request.nonce,
'prompt': prompt,
'ui_locales': request.ui_locales.split() if request.ui_locales else [],
'id_token_hint': request.id_token_hint,
'login_hint': request.login_hint,
'claims': request.claims
}
return request_info | python | def openid_authorization_validator(self, request):
"""Perform OpenID Connect specific authorization request validation.
nonce
OPTIONAL. String value used to associate a Client session with
an ID Token, and to mitigate replay attacks. The value is
passed through unmodified from the Authentication Request to
the ID Token. Sufficient entropy MUST be present in the nonce
values used to prevent attackers from guessing values
display
OPTIONAL. ASCII string value that specifies how the
Authorization Server displays the authentication and consent
user interface pages to the End-User. The defined values are:
page - The Authorization Server SHOULD display the
authentication and consent UI consistent with a full User
Agent page view. If the display parameter is not specified,
this is the default display mode.
popup - The Authorization Server SHOULD display the
authentication and consent UI consistent with a popup User
Agent window. The popup User Agent window should be of an
appropriate size for a login-focused dialog and should not
obscure the entire window that it is popping up over.
touch - The Authorization Server SHOULD display the
authentication and consent UI consistent with a device that
leverages a touch interface.
wap - The Authorization Server SHOULD display the
authentication and consent UI consistent with a "feature
phone" type display.
The Authorization Server MAY also attempt to detect the
capabilities of the User Agent and present an appropriate
display.
prompt
OPTIONAL. Space delimited, case sensitive list of ASCII string
values that specifies whether the Authorization Server prompts
the End-User for reauthentication and consent. The defined
values are:
none - The Authorization Server MUST NOT display any
authentication or consent user interface pages. An error is
returned if an End-User is not already authenticated or the
Client does not have pre-configured consent for the
requested Claims or does not fulfill other conditions for
processing the request. The error code will typically be
login_required, interaction_required, or another code
defined in Section 3.1.2.6. This can be used as a method to
check for existing authentication and/or consent.
login - The Authorization Server SHOULD prompt the End-User
for reauthentication. If it cannot reauthenticate the
End-User, it MUST return an error, typically
login_required.
consent - The Authorization Server SHOULD prompt the
End-User for consent before returning information to the
Client. If it cannot obtain consent, it MUST return an
error, typically consent_required.
select_account - The Authorization Server SHOULD prompt the
End-User to select a user account. This enables an End-User
who has multiple accounts at the Authorization Server to
select amongst the multiple accounts that they might have
current sessions for. If it cannot obtain an account
selection choice made by the End-User, it MUST return an
error, typically account_selection_required.
The prompt parameter can be used by the Client to make sure
that the End-User is still present for the current session or
to bring attention to the request. If this parameter contains
none with any other value, an error is returned.
max_age
OPTIONAL. Maximum Authentication Age. Specifies the allowable
elapsed time in seconds since the last time the End-User was
actively authenticated by the OP. If the elapsed time is
greater than this value, the OP MUST attempt to actively
re-authenticate the End-User. (The max_age request parameter
corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age
request parameter.) When max_age is used, the ID Token returned
MUST include an auth_time Claim Value.
ui_locales
OPTIONAL. End-User's preferred languages and scripts for the
user interface, represented as a space-separated list of BCP47
[RFC5646] language tag values, ordered by preference. For
instance, the value "fr-CA fr en" represents a preference for
French as spoken in Canada, then French (without a region
designation), followed by English (without a region
designation). An error SHOULD NOT result if some or all of the
requested locales are not supported by the OpenID Provider.
id_token_hint
OPTIONAL. ID Token previously issued by the Authorization
Server being passed as a hint about the End-User's current or
past authenticated session with the Client. If the End-User
identified by the ID Token is logged in or is logged in by the
request, then the Authorization Server returns a positive
response; otherwise, it SHOULD return an error, such as
login_required. When possible, an id_token_hint SHOULD be
present when prompt=none is used and an invalid_request error
MAY be returned if it is not; however, the server SHOULD
respond successfully when possible, even if it is not present.
The Authorization Server need not be listed as an audience of
the ID Token when it is used as an id_token_hint value. If the
ID Token received by the RP from the OP is encrypted, to use it
as an id_token_hint, the Client MUST decrypt the signed ID
Token contained within the encrypted ID Token. The Client MAY
re-encrypt the signed ID token to the Authentication Server
using a key that enables the server to decrypt the ID Token,
and use the re-encrypted ID token as the id_token_hint value.
login_hint
OPTIONAL. Hint to the Authorization Server about the login
identifier the End-User might use to log in (if necessary).
This hint can be used by an RP if it first asks the End-User
for their e-mail address (or other identifier) and then wants
to pass that value as a hint to the discovered authorization
service. It is RECOMMENDED that the hint value match the value
used for discovery. This value MAY also be a phone number in
the format specified for the phone_number Claim. The use of
this parameter is left to the OP's discretion.
acr_values
OPTIONAL. Requested Authentication Context Class Reference
values. Space-separated string that specifies the acr values
that the Authorization Server is being requested to use for
processing this Authentication Request, with the values
appearing in order of preference. The Authentication Context
Class satisfied by the authentication performed is returned as
the acr Claim Value, as specified in Section 2. The acr Claim
is requested as a Voluntary Claim by this parameter.
"""
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return {}
prompt = request.prompt if request.prompt else []
if hasattr(prompt, 'split'):
prompt = prompt.strip().split()
prompt = set(prompt)
if 'none' in prompt:
if len(prompt) > 1:
msg = "Prompt none is mutually exclusive with other values."
raise InvalidRequestError(request=request, description=msg)
if not self.request_validator.validate_silent_login(request):
raise LoginRequired(request=request)
if not self.request_validator.validate_silent_authorization(request):
raise ConsentRequired(request=request)
self._inflate_claims(request)
if not self.request_validator.validate_user_match(
request.id_token_hint, request.scopes, request.claims, request):
msg = "Session user does not match client supplied user."
raise LoginRequired(request=request, description=msg)
request_info = {
'display': request.display,
'nonce': request.nonce,
'prompt': prompt,
'ui_locales': request.ui_locales.split() if request.ui_locales else [],
'id_token_hint': request.id_token_hint,
'login_hint': request.login_hint,
'claims': request.claims
}
return request_info | [
"def",
"openid_authorization_validator",
"(",
"self",
",",
"request",
")",
":",
"# Treat it as normal OAuth 2 auth code request if openid is not present",
"if",
"not",
"request",
".",
"scopes",
"or",
"'openid'",
"not",
"in",
"request",
".",
"scopes",
":",
"return",
"{",
"}",
"prompt",
"=",
"request",
".",
"prompt",
"if",
"request",
".",
"prompt",
"else",
"[",
"]",
"if",
"hasattr",
"(",
"prompt",
",",
"'split'",
")",
":",
"prompt",
"=",
"prompt",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"prompt",
"=",
"set",
"(",
"prompt",
")",
"if",
"'none'",
"in",
"prompt",
":",
"if",
"len",
"(",
"prompt",
")",
">",
"1",
":",
"msg",
"=",
"\"Prompt none is mutually exclusive with other values.\"",
"raise",
"InvalidRequestError",
"(",
"request",
"=",
"request",
",",
"description",
"=",
"msg",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_silent_login",
"(",
"request",
")",
":",
"raise",
"LoginRequired",
"(",
"request",
"=",
"request",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_silent_authorization",
"(",
"request",
")",
":",
"raise",
"ConsentRequired",
"(",
"request",
"=",
"request",
")",
"self",
".",
"_inflate_claims",
"(",
"request",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_user_match",
"(",
"request",
".",
"id_token_hint",
",",
"request",
".",
"scopes",
",",
"request",
".",
"claims",
",",
"request",
")",
":",
"msg",
"=",
"\"Session user does not match client supplied user.\"",
"raise",
"LoginRequired",
"(",
"request",
"=",
"request",
",",
"description",
"=",
"msg",
")",
"request_info",
"=",
"{",
"'display'",
":",
"request",
".",
"display",
",",
"'nonce'",
":",
"request",
".",
"nonce",
",",
"'prompt'",
":",
"prompt",
",",
"'ui_locales'",
":",
"request",
".",
"ui_locales",
".",
"split",
"(",
")",
"if",
"request",
".",
"ui_locales",
"else",
"[",
"]",
",",
"'id_token_hint'",
":",
"request",
".",
"id_token_hint",
",",
"'login_hint'",
":",
"request",
".",
"login_hint",
",",
"'claims'",
":",
"request",
".",
"claims",
"}",
"return",
"request_info"
] | Perform OpenID Connect specific authorization request validation.
nonce
OPTIONAL. String value used to associate a Client session with
an ID Token, and to mitigate replay attacks. The value is
passed through unmodified from the Authentication Request to
the ID Token. Sufficient entropy MUST be present in the nonce
values used to prevent attackers from guessing values
display
OPTIONAL. ASCII string value that specifies how the
Authorization Server displays the authentication and consent
user interface pages to the End-User. The defined values are:
page - The Authorization Server SHOULD display the
authentication and consent UI consistent with a full User
Agent page view. If the display parameter is not specified,
this is the default display mode.
popup - The Authorization Server SHOULD display the
authentication and consent UI consistent with a popup User
Agent window. The popup User Agent window should be of an
appropriate size for a login-focused dialog and should not
obscure the entire window that it is popping up over.
touch - The Authorization Server SHOULD display the
authentication and consent UI consistent with a device that
leverages a touch interface.
wap - The Authorization Server SHOULD display the
authentication and consent UI consistent with a "feature
phone" type display.
The Authorization Server MAY also attempt to detect the
capabilities of the User Agent and present an appropriate
display.
prompt
OPTIONAL. Space delimited, case sensitive list of ASCII string
values that specifies whether the Authorization Server prompts
the End-User for reauthentication and consent. The defined
values are:
none - The Authorization Server MUST NOT display any
authentication or consent user interface pages. An error is
returned if an End-User is not already authenticated or the
Client does not have pre-configured consent for the
requested Claims or does not fulfill other conditions for
processing the request. The error code will typically be
login_required, interaction_required, or another code
defined in Section 3.1.2.6. This can be used as a method to
check for existing authentication and/or consent.
login - The Authorization Server SHOULD prompt the End-User
for reauthentication. If it cannot reauthenticate the
End-User, it MUST return an error, typically
login_required.
consent - The Authorization Server SHOULD prompt the
End-User for consent before returning information to the
Client. If it cannot obtain consent, it MUST return an
error, typically consent_required.
select_account - The Authorization Server SHOULD prompt the
End-User to select a user account. This enables an End-User
who has multiple accounts at the Authorization Server to
select amongst the multiple accounts that they might have
current sessions for. If it cannot obtain an account
selection choice made by the End-User, it MUST return an
error, typically account_selection_required.
The prompt parameter can be used by the Client to make sure
that the End-User is still present for the current session or
to bring attention to the request. If this parameter contains
none with any other value, an error is returned.
max_age
OPTIONAL. Maximum Authentication Age. Specifies the allowable
elapsed time in seconds since the last time the End-User was
actively authenticated by the OP. If the elapsed time is
greater than this value, the OP MUST attempt to actively
re-authenticate the End-User. (The max_age request parameter
corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age
request parameter.) When max_age is used, the ID Token returned
MUST include an auth_time Claim Value.
ui_locales
OPTIONAL. End-User's preferred languages and scripts for the
user interface, represented as a space-separated list of BCP47
[RFC5646] language tag values, ordered by preference. For
instance, the value "fr-CA fr en" represents a preference for
French as spoken in Canada, then French (without a region
designation), followed by English (without a region
designation). An error SHOULD NOT result if some or all of the
requested locales are not supported by the OpenID Provider.
id_token_hint
OPTIONAL. ID Token previously issued by the Authorization
Server being passed as a hint about the End-User's current or
past authenticated session with the Client. If the End-User
identified by the ID Token is logged in or is logged in by the
request, then the Authorization Server returns a positive
response; otherwise, it SHOULD return an error, such as
login_required. When possible, an id_token_hint SHOULD be
present when prompt=none is used and an invalid_request error
MAY be returned if it is not; however, the server SHOULD
respond successfully when possible, even if it is not present.
The Authorization Server need not be listed as an audience of
the ID Token when it is used as an id_token_hint value. If the
ID Token received by the RP from the OP is encrypted, to use it
as an id_token_hint, the Client MUST decrypt the signed ID
Token contained within the encrypted ID Token. The Client MAY
re-encrypt the signed ID token to the Authentication Server
using a key that enables the server to decrypt the ID Token,
and use the re-encrypted ID token as the id_token_hint value.
login_hint
OPTIONAL. Hint to the Authorization Server about the login
identifier the End-User might use to log in (if necessary).
This hint can be used by an RP if it first asks the End-User
for their e-mail address (or other identifier) and then wants
to pass that value as a hint to the discovered authorization
service. It is RECOMMENDED that the hint value match the value
used for discovery. This value MAY also be a phone number in
the format specified for the phone_number Claim. The use of
this parameter is left to the OP's discretion.
acr_values
OPTIONAL. Requested Authentication Context Class Reference
values. Space-separated string that specifies the acr values
that the Authorization Server is being requested to use for
processing this Authentication Request, with the values
appearing in order of preference. The Authentication Context
Class satisfied by the authentication performed is returned as
the acr Claim Value, as specified in Section 2. The acr Claim
is requested as a Voluntary Claim by this parameter. | [
"Perform",
"OpenID",
"Connect",
"specific",
"authorization",
"request",
"validation",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/base.py#L71-L248 |
229,846 | oauthlib/oauthlib | oauthlib/openid/connect/core/grant_types/hybrid.py | HybridGrant.openid_authorization_validator | def openid_authorization_validator(self, request):
"""Additional validation when following the Authorization Code flow.
"""
request_info = super(HybridGrant, self).openid_authorization_validator(request)
if not request_info: # returns immediately if OAuth2.0
return request_info
# REQUIRED if the Response Type of the request is `code
# id_token` or `code id_token token` and OPTIONAL when the
# Response Type of the request is `code token`. It is a string
# value used to associate a Client session with an ID Token,
# and to mitigate replay attacks. The value is passed through
# unmodified from the Authentication Request to the ID
# Token. Sufficient entropy MUST be present in the `nonce`
# values used to prevent attackers from guessing values. For
# implementation notes, see Section 15.5.2.
if request.response_type in ["code id_token", "code id_token token"]:
if not request.nonce:
raise InvalidRequestError(
request=request,
description='Request is missing mandatory nonce parameter.'
)
return request_info | python | def openid_authorization_validator(self, request):
"""Additional validation when following the Authorization Code flow.
"""
request_info = super(HybridGrant, self).openid_authorization_validator(request)
if not request_info: # returns immediately if OAuth2.0
return request_info
# REQUIRED if the Response Type of the request is `code
# id_token` or `code id_token token` and OPTIONAL when the
# Response Type of the request is `code token`. It is a string
# value used to associate a Client session with an ID Token,
# and to mitigate replay attacks. The value is passed through
# unmodified from the Authentication Request to the ID
# Token. Sufficient entropy MUST be present in the `nonce`
# values used to prevent attackers from guessing values. For
# implementation notes, see Section 15.5.2.
if request.response_type in ["code id_token", "code id_token token"]:
if not request.nonce:
raise InvalidRequestError(
request=request,
description='Request is missing mandatory nonce parameter.'
)
return request_info | [
"def",
"openid_authorization_validator",
"(",
"self",
",",
"request",
")",
":",
"request_info",
"=",
"super",
"(",
"HybridGrant",
",",
"self",
")",
".",
"openid_authorization_validator",
"(",
"request",
")",
"if",
"not",
"request_info",
":",
"# returns immediately if OAuth2.0",
"return",
"request_info",
"# REQUIRED if the Response Type of the request is `code",
"# id_token` or `code id_token token` and OPTIONAL when the",
"# Response Type of the request is `code token`. It is a string",
"# value used to associate a Client session with an ID Token,",
"# and to mitigate replay attacks. The value is passed through",
"# unmodified from the Authentication Request to the ID",
"# Token. Sufficient entropy MUST be present in the `nonce`",
"# values used to prevent attackers from guessing values. For",
"# implementation notes, see Section 15.5.2.",
"if",
"request",
".",
"response_type",
"in",
"[",
"\"code id_token\"",
",",
"\"code id_token token\"",
"]",
":",
"if",
"not",
"request",
".",
"nonce",
":",
"raise",
"InvalidRequestError",
"(",
"request",
"=",
"request",
",",
"description",
"=",
"'Request is missing mandatory nonce parameter.'",
")",
"return",
"request_info"
] | Additional validation when following the Authorization Code flow. | [
"Additional",
"validation",
"when",
"following",
"the",
"Authorization",
"Code",
"flow",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/hybrid.py#L39-L61 |
229,847 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/utils.py | filter_oauth_params | def filter_oauth_params(params):
"""Removes all non oauth parameters from a dict or a list of params."""
is_oauth = lambda kv: kv[0].startswith("oauth_")
if isinstance(params, dict):
return list(filter(is_oauth, list(params.items())))
else:
return list(filter(is_oauth, params)) | python | def filter_oauth_params(params):
"""Removes all non oauth parameters from a dict or a list of params."""
is_oauth = lambda kv: kv[0].startswith("oauth_")
if isinstance(params, dict):
return list(filter(is_oauth, list(params.items())))
else:
return list(filter(is_oauth, params)) | [
"def",
"filter_oauth_params",
"(",
"params",
")",
":",
"is_oauth",
"=",
"lambda",
"kv",
":",
"kv",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"oauth_\"",
")",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"is_oauth",
",",
"list",
"(",
"params",
".",
"items",
"(",
")",
")",
")",
")",
"else",
":",
"return",
"list",
"(",
"filter",
"(",
"is_oauth",
",",
"params",
")",
")"
] | Removes all non oauth parameters from a dict or a list of params. | [
"Removes",
"all",
"non",
"oauth",
"parameters",
"from",
"a",
"dict",
"or",
"a",
"list",
"of",
"params",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/utils.py#L38-L44 |
229,848 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/utils.py | parse_authorization_header | def parse_authorization_header(authorization_header):
"""Parse an OAuth authorization header into a list of 2-tuples"""
auth_scheme = 'OAuth '.lower()
if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme):
items = parse_http_list(authorization_header[len(auth_scheme):])
try:
return list(parse_keqv_list(items).items())
except (IndexError, ValueError):
pass
raise ValueError('Malformed authorization header') | python | def parse_authorization_header(authorization_header):
"""Parse an OAuth authorization header into a list of 2-tuples"""
auth_scheme = 'OAuth '.lower()
if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme):
items = parse_http_list(authorization_header[len(auth_scheme):])
try:
return list(parse_keqv_list(items).items())
except (IndexError, ValueError):
pass
raise ValueError('Malformed authorization header') | [
"def",
"parse_authorization_header",
"(",
"authorization_header",
")",
":",
"auth_scheme",
"=",
"'OAuth '",
".",
"lower",
"(",
")",
"if",
"authorization_header",
"[",
":",
"len",
"(",
"auth_scheme",
")",
"]",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"auth_scheme",
")",
":",
"items",
"=",
"parse_http_list",
"(",
"authorization_header",
"[",
"len",
"(",
"auth_scheme",
")",
":",
"]",
")",
"try",
":",
"return",
"list",
"(",
"parse_keqv_list",
"(",
"items",
")",
".",
"items",
"(",
")",
")",
"except",
"(",
"IndexError",
",",
"ValueError",
")",
":",
"pass",
"raise",
"ValueError",
"(",
"'Malformed authorization header'",
")"
] | Parse an OAuth authorization header into a list of 2-tuples | [
"Parse",
"an",
"OAuth",
"authorization",
"header",
"into",
"a",
"list",
"of",
"2",
"-",
"tuples"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/utils.py#L81-L90 |
229,849 | oauthlib/oauthlib | oauthlib/openid/connect/core/grant_types/implicit.py | ImplicitGrant.openid_authorization_validator | def openid_authorization_validator(self, request):
"""Additional validation when following the implicit flow.
"""
request_info = super(ImplicitGrant, self).openid_authorization_validator(request)
if not request_info: # returns immediately if OAuth2.0
return request_info
# REQUIRED. String value used to associate a Client session with an ID
# Token, and to mitigate replay attacks. The value is passed through
# unmodified from the Authentication Request to the ID Token.
# Sufficient entropy MUST be present in the nonce values used to
# prevent attackers from guessing values. For implementation notes, see
# Section 15.5.2.
if not request.nonce:
raise InvalidRequestError(
request=request,
description='Request is missing mandatory nonce parameter.'
)
return request_info | python | def openid_authorization_validator(self, request):
"""Additional validation when following the implicit flow.
"""
request_info = super(ImplicitGrant, self).openid_authorization_validator(request)
if not request_info: # returns immediately if OAuth2.0
return request_info
# REQUIRED. String value used to associate a Client session with an ID
# Token, and to mitigate replay attacks. The value is passed through
# unmodified from the Authentication Request to the ID Token.
# Sufficient entropy MUST be present in the nonce values used to
# prevent attackers from guessing values. For implementation notes, see
# Section 15.5.2.
if not request.nonce:
raise InvalidRequestError(
request=request,
description='Request is missing mandatory nonce parameter.'
)
return request_info | [
"def",
"openid_authorization_validator",
"(",
"self",
",",
"request",
")",
":",
"request_info",
"=",
"super",
"(",
"ImplicitGrant",
",",
"self",
")",
".",
"openid_authorization_validator",
"(",
"request",
")",
"if",
"not",
"request_info",
":",
"# returns immediately if OAuth2.0",
"return",
"request_info",
"# REQUIRED. String value used to associate a Client session with an ID",
"# Token, and to mitigate replay attacks. The value is passed through",
"# unmodified from the Authentication Request to the ID Token.",
"# Sufficient entropy MUST be present in the nonce values used to",
"# prevent attackers from guessing values. For implementation notes, see",
"# Section 15.5.2.",
"if",
"not",
"request",
".",
"nonce",
":",
"raise",
"InvalidRequestError",
"(",
"request",
"=",
"request",
",",
"description",
"=",
"'Request is missing mandatory nonce parameter.'",
")",
"return",
"request_info"
] | Additional validation when following the implicit flow. | [
"Additional",
"validation",
"when",
"following",
"the",
"implicit",
"flow",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/implicit.py#L34-L52 |
229,850 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/access_token.py | AccessTokenEndpoint.create_access_token | def create_access_token(self, request, credentials):
"""Create and save a new access token.
Similar to OAuth 2, indication of granted scopes will be included as a
space separated list in ``oauth_authorized_realms``.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:returns: The token as an urlencoded string.
"""
request.realms = self.request_validator.get_realms(
request.resource_owner_key, request)
token = {
'oauth_token': self.token_generator(),
'oauth_token_secret': self.token_generator(),
# Backport the authorized scopes indication used in OAuth2
'oauth_authorized_realms': ' '.join(request.realms)
}
token.update(credentials)
self.request_validator.save_access_token(token, request)
return urlencode(token.items()) | python | def create_access_token(self, request, credentials):
"""Create and save a new access token.
Similar to OAuth 2, indication of granted scopes will be included as a
space separated list in ``oauth_authorized_realms``.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:returns: The token as an urlencoded string.
"""
request.realms = self.request_validator.get_realms(
request.resource_owner_key, request)
token = {
'oauth_token': self.token_generator(),
'oauth_token_secret': self.token_generator(),
# Backport the authorized scopes indication used in OAuth2
'oauth_authorized_realms': ' '.join(request.realms)
}
token.update(credentials)
self.request_validator.save_access_token(token, request)
return urlencode(token.items()) | [
"def",
"create_access_token",
"(",
"self",
",",
"request",
",",
"credentials",
")",
":",
"request",
".",
"realms",
"=",
"self",
".",
"request_validator",
".",
"get_realms",
"(",
"request",
".",
"resource_owner_key",
",",
"request",
")",
"token",
"=",
"{",
"'oauth_token'",
":",
"self",
".",
"token_generator",
"(",
")",
",",
"'oauth_token_secret'",
":",
"self",
".",
"token_generator",
"(",
")",
",",
"# Backport the authorized scopes indication used in OAuth2",
"'oauth_authorized_realms'",
":",
"' '",
".",
"join",
"(",
"request",
".",
"realms",
")",
"}",
"token",
".",
"update",
"(",
"credentials",
")",
"self",
".",
"request_validator",
".",
"save_access_token",
"(",
"token",
",",
"request",
")",
"return",
"urlencode",
"(",
"token",
".",
"items",
"(",
")",
")"
] | Create and save a new access token.
Similar to OAuth 2, indication of granted scopes will be included as a
space separated list in ``oauth_authorized_realms``.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:returns: The token as an urlencoded string. | [
"Create",
"and",
"save",
"a",
"new",
"access",
"token",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/access_token.py#L34-L54 |
229,851 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/access_token.py | AccessTokenEndpoint.create_access_token_response | def create_access_token_response(self, uri, http_method='GET', body=None,
headers=None, credentials=None):
"""Create an access token response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:param credentials: A list of extra credentials to include in the token.
:returns: A tuple of 3 elements.
1. A dict of headers to set on the response.
2. The response body as a string.
3. The response status code as an integer.
An example of a valid request::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import AccessTokenEndpoint
>>> endpoint = AccessTokenEndpoint(your_validator)
>>> h, b, s = endpoint.create_access_token_response(
... 'https://your.provider/access_token?foo=bar',
... headers={
... 'Authorization': 'OAuth oauth_token=234lsdkf....'
... },
... credentials={
... 'my_specific': 'argument',
... })
>>> h
{'Content-Type': 'application/x-www-form-urlencoded'}
>>> b
'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_authorized_realms=movies+pics&my_specific=argument'
>>> s
200
An response to invalid request would have a different body and status::
>>> b
'error=invalid_request&description=missing+resource+owner+key'
>>> s
400
The same goes for an an unauthorized request:
>>> b
''
>>> s
401
"""
resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
try:
request = self._create_request(uri, http_method, body, headers)
valid, processed_request = self.validate_access_token_request(
request)
if valid:
token = self.create_access_token(request, credentials or {})
self.request_validator.invalidate_request_token(
request.client_key,
request.resource_owner_key,
request)
return resp_headers, token, 200
else:
return {}, None, 401
except errors.OAuth1Error as e:
return resp_headers, e.urlencoded, e.status_code | python | def create_access_token_response(self, uri, http_method='GET', body=None,
headers=None, credentials=None):
"""Create an access token response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:param credentials: A list of extra credentials to include in the token.
:returns: A tuple of 3 elements.
1. A dict of headers to set on the response.
2. The response body as a string.
3. The response status code as an integer.
An example of a valid request::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import AccessTokenEndpoint
>>> endpoint = AccessTokenEndpoint(your_validator)
>>> h, b, s = endpoint.create_access_token_response(
... 'https://your.provider/access_token?foo=bar',
... headers={
... 'Authorization': 'OAuth oauth_token=234lsdkf....'
... },
... credentials={
... 'my_specific': 'argument',
... })
>>> h
{'Content-Type': 'application/x-www-form-urlencoded'}
>>> b
'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_authorized_realms=movies+pics&my_specific=argument'
>>> s
200
An response to invalid request would have a different body and status::
>>> b
'error=invalid_request&description=missing+resource+owner+key'
>>> s
400
The same goes for an an unauthorized request:
>>> b
''
>>> s
401
"""
resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
try:
request = self._create_request(uri, http_method, body, headers)
valid, processed_request = self.validate_access_token_request(
request)
if valid:
token = self.create_access_token(request, credentials or {})
self.request_validator.invalidate_request_token(
request.client_key,
request.resource_owner_key,
request)
return resp_headers, token, 200
else:
return {}, None, 401
except errors.OAuth1Error as e:
return resp_headers, e.urlencoded, e.status_code | [
"def",
"create_access_token_response",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"credentials",
"=",
"None",
")",
":",
"resp_headers",
"=",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
"}",
"try",
":",
"request",
"=",
"self",
".",
"_create_request",
"(",
"uri",
",",
"http_method",
",",
"body",
",",
"headers",
")",
"valid",
",",
"processed_request",
"=",
"self",
".",
"validate_access_token_request",
"(",
"request",
")",
"if",
"valid",
":",
"token",
"=",
"self",
".",
"create_access_token",
"(",
"request",
",",
"credentials",
"or",
"{",
"}",
")",
"self",
".",
"request_validator",
".",
"invalidate_request_token",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"resource_owner_key",
",",
"request",
")",
"return",
"resp_headers",
",",
"token",
",",
"200",
"else",
":",
"return",
"{",
"}",
",",
"None",
",",
"401",
"except",
"errors",
".",
"OAuth1Error",
"as",
"e",
":",
"return",
"resp_headers",
",",
"e",
".",
"urlencoded",
",",
"e",
".",
"status_code"
] | Create an access token response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:param credentials: A list of extra credentials to include in the token.
:returns: A tuple of 3 elements.
1. A dict of headers to set on the response.
2. The response body as a string.
3. The response status code as an integer.
An example of a valid request::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import AccessTokenEndpoint
>>> endpoint = AccessTokenEndpoint(your_validator)
>>> h, b, s = endpoint.create_access_token_response(
... 'https://your.provider/access_token?foo=bar',
... headers={
... 'Authorization': 'OAuth oauth_token=234lsdkf....'
... },
... credentials={
... 'my_specific': 'argument',
... })
>>> h
{'Content-Type': 'application/x-www-form-urlencoded'}
>>> b
'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_authorized_realms=movies+pics&my_specific=argument'
>>> s
200
An response to invalid request would have a different body and status::
>>> b
'error=invalid_request&description=missing+resource+owner+key'
>>> s
400
The same goes for an an unauthorized request:
>>> b
''
>>> s
401 | [
"Create",
"an",
"access",
"token",
"response",
"with",
"a",
"new",
"request",
"token",
"if",
"valid",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/access_token.py#L56-L119 |
229,852 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/access_token.py | AccessTokenEndpoint.validate_access_token_request | def validate_access_token_request(self, request):
"""Validate an access token request.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object.
"""
self._check_transport_security(request)
self._check_mandatory_parameters(request)
if not request.resource_owner_key:
raise errors.InvalidRequestError(
description='Missing resource owner.')
if not self.request_validator.check_request_token(
request.resource_owner_key):
raise errors.InvalidRequestError(
description='Invalid resource owner key format.')
if not request.verifier:
raise errors.InvalidRequestError(
description='Missing verifier.')
if not self.request_validator.check_verifier(request.verifier):
raise errors.InvalidRequestError(
description='Invalid verifier format.')
if not self.request_validator.validate_timestamp_and_nonce(
request.client_key, request.timestamp, request.nonce, request,
request_token=request.resource_owner_key):
return False, request
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid client credentials.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy client is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable client enumeration
valid_client = self.request_validator.validate_client_key(
request.client_key, request)
if not valid_client:
request.client_key = self.request_validator.dummy_client
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid or expired token.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy token is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable resource owner enumeration
valid_resource_owner = self.request_validator.validate_request_token(
request.client_key, request.resource_owner_key, request)
if not valid_resource_owner:
request.resource_owner_key = self.request_validator.dummy_request_token
# The server MUST verify (Section 3.2) the validity of the request,
# ensure that the resource owner has authorized the provisioning of
# token credentials to the client, and ensure that the temporary
# credentials have not expired or been used before. The server MUST
# also verify the verification code received from the client.
# .. _`Section 3.2`: https://tools.ietf.org/html/rfc5849#section-3.2
#
# Note that early exit would enable resource owner authorization
# verifier enumertion.
valid_verifier = self.request_validator.validate_verifier(
request.client_key,
request.resource_owner_key,
request.verifier,
request)
valid_signature = self._check_signature(request, is_token_request=True)
# log the results to the validator_log
# this lets us handle internal reporting and analysis
request.validator_log['client'] = valid_client
request.validator_log['resource_owner'] = valid_resource_owner
request.validator_log['verifier'] = valid_verifier
request.validator_log['signature'] = valid_signature
# We delay checking validity until the very end, using dummy values for
# calculations and fetching secrets/keys to ensure the flow of every
# request remains almost identical regardless of whether valid values
# have been supplied. This ensures near constant time execution and
# prevents malicious users from guessing sensitive information
v = all((valid_client, valid_resource_owner, valid_verifier,
valid_signature))
if not v:
log.info("[Failure] request verification failed.")
log.info("Valid client:, %s", valid_client)
log.info("Valid token:, %s", valid_resource_owner)
log.info("Valid verifier:, %s", valid_verifier)
log.info("Valid signature:, %s", valid_signature)
return v, request | python | def validate_access_token_request(self, request):
"""Validate an access token request.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object.
"""
self._check_transport_security(request)
self._check_mandatory_parameters(request)
if not request.resource_owner_key:
raise errors.InvalidRequestError(
description='Missing resource owner.')
if not self.request_validator.check_request_token(
request.resource_owner_key):
raise errors.InvalidRequestError(
description='Invalid resource owner key format.')
if not request.verifier:
raise errors.InvalidRequestError(
description='Missing verifier.')
if not self.request_validator.check_verifier(request.verifier):
raise errors.InvalidRequestError(
description='Invalid verifier format.')
if not self.request_validator.validate_timestamp_and_nonce(
request.client_key, request.timestamp, request.nonce, request,
request_token=request.resource_owner_key):
return False, request
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid client credentials.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy client is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable client enumeration
valid_client = self.request_validator.validate_client_key(
request.client_key, request)
if not valid_client:
request.client_key = self.request_validator.dummy_client
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid or expired token.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy token is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable resource owner enumeration
valid_resource_owner = self.request_validator.validate_request_token(
request.client_key, request.resource_owner_key, request)
if not valid_resource_owner:
request.resource_owner_key = self.request_validator.dummy_request_token
# The server MUST verify (Section 3.2) the validity of the request,
# ensure that the resource owner has authorized the provisioning of
# token credentials to the client, and ensure that the temporary
# credentials have not expired or been used before. The server MUST
# also verify the verification code received from the client.
# .. _`Section 3.2`: https://tools.ietf.org/html/rfc5849#section-3.2
#
# Note that early exit would enable resource owner authorization
# verifier enumertion.
valid_verifier = self.request_validator.validate_verifier(
request.client_key,
request.resource_owner_key,
request.verifier,
request)
valid_signature = self._check_signature(request, is_token_request=True)
# log the results to the validator_log
# this lets us handle internal reporting and analysis
request.validator_log['client'] = valid_client
request.validator_log['resource_owner'] = valid_resource_owner
request.validator_log['verifier'] = valid_verifier
request.validator_log['signature'] = valid_signature
# We delay checking validity until the very end, using dummy values for
# calculations and fetching secrets/keys to ensure the flow of every
# request remains almost identical regardless of whether valid values
# have been supplied. This ensures near constant time execution and
# prevents malicious users from guessing sensitive information
v = all((valid_client, valid_resource_owner, valid_verifier,
valid_signature))
if not v:
log.info("[Failure] request verification failed.")
log.info("Valid client:, %s", valid_client)
log.info("Valid token:, %s", valid_resource_owner)
log.info("Valid verifier:, %s", valid_verifier)
log.info("Valid signature:, %s", valid_signature)
return v, request | [
"def",
"validate_access_token_request",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_check_transport_security",
"(",
"request",
")",
"self",
".",
"_check_mandatory_parameters",
"(",
"request",
")",
"if",
"not",
"request",
".",
"resource_owner_key",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Missing resource owner.'",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"check_request_token",
"(",
"request",
".",
"resource_owner_key",
")",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Invalid resource owner key format.'",
")",
"if",
"not",
"request",
".",
"verifier",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Missing verifier.'",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"check_verifier",
"(",
"request",
".",
"verifier",
")",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Invalid verifier format.'",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_timestamp_and_nonce",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"timestamp",
",",
"request",
".",
"nonce",
",",
"request",
",",
"request_token",
"=",
"request",
".",
"resource_owner_key",
")",
":",
"return",
"False",
",",
"request",
"# The server SHOULD return a 401 (Unauthorized) status code when",
"# receiving a request with invalid client credentials.",
"# Note: This is postponed in order to avoid timing attacks, instead",
"# a dummy client is assigned and used to maintain near constant",
"# time request verification.",
"#",
"# Note that early exit would enable client enumeration",
"valid_client",
"=",
"self",
".",
"request_validator",
".",
"validate_client_key",
"(",
"request",
".",
"client_key",
",",
"request",
")",
"if",
"not",
"valid_client",
":",
"request",
".",
"client_key",
"=",
"self",
".",
"request_validator",
".",
"dummy_client",
"# The server SHOULD return a 401 (Unauthorized) status code when",
"# receiving a request with invalid or expired token.",
"# Note: This is postponed in order to avoid timing attacks, instead",
"# a dummy token is assigned and used to maintain near constant",
"# time request verification.",
"#",
"# Note that early exit would enable resource owner enumeration",
"valid_resource_owner",
"=",
"self",
".",
"request_validator",
".",
"validate_request_token",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"resource_owner_key",
",",
"request",
")",
"if",
"not",
"valid_resource_owner",
":",
"request",
".",
"resource_owner_key",
"=",
"self",
".",
"request_validator",
".",
"dummy_request_token",
"# The server MUST verify (Section 3.2) the validity of the request,",
"# ensure that the resource owner has authorized the provisioning of",
"# token credentials to the client, and ensure that the temporary",
"# credentials have not expired or been used before. The server MUST",
"# also verify the verification code received from the client.",
"# .. _`Section 3.2`: https://tools.ietf.org/html/rfc5849#section-3.2",
"#",
"# Note that early exit would enable resource owner authorization",
"# verifier enumertion.",
"valid_verifier",
"=",
"self",
".",
"request_validator",
".",
"validate_verifier",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"resource_owner_key",
",",
"request",
".",
"verifier",
",",
"request",
")",
"valid_signature",
"=",
"self",
".",
"_check_signature",
"(",
"request",
",",
"is_token_request",
"=",
"True",
")",
"# log the results to the validator_log",
"# this lets us handle internal reporting and analysis",
"request",
".",
"validator_log",
"[",
"'client'",
"]",
"=",
"valid_client",
"request",
".",
"validator_log",
"[",
"'resource_owner'",
"]",
"=",
"valid_resource_owner",
"request",
".",
"validator_log",
"[",
"'verifier'",
"]",
"=",
"valid_verifier",
"request",
".",
"validator_log",
"[",
"'signature'",
"]",
"=",
"valid_signature",
"# We delay checking validity until the very end, using dummy values for",
"# calculations and fetching secrets/keys to ensure the flow of every",
"# request remains almost identical regardless of whether valid values",
"# have been supplied. This ensures near constant time execution and",
"# prevents malicious users from guessing sensitive information",
"v",
"=",
"all",
"(",
"(",
"valid_client",
",",
"valid_resource_owner",
",",
"valid_verifier",
",",
"valid_signature",
")",
")",
"if",
"not",
"v",
":",
"log",
".",
"info",
"(",
"\"[Failure] request verification failed.\"",
")",
"log",
".",
"info",
"(",
"\"Valid client:, %s\"",
",",
"valid_client",
")",
"log",
".",
"info",
"(",
"\"Valid token:, %s\"",
",",
"valid_resource_owner",
")",
"log",
".",
"info",
"(",
"\"Valid verifier:, %s\"",
",",
"valid_verifier",
")",
"log",
".",
"info",
"(",
"\"Valid signature:, %s\"",
",",
"valid_signature",
")",
"return",
"v",
",",
"request"
] | Validate an access token request.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object. | [
"Validate",
"an",
"access",
"token",
"request",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/access_token.py#L121-L217 |
229,853 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/resource.py | ResourceEndpoint.verify_request | def verify_request(self, uri, http_method='GET', body=None, headers=None,
scopes=None):
"""Validate client, code etc, return body + headers"""
request = Request(uri, http_method, body, headers)
request.token_type = self.find_token_type(request)
request.scopes = scopes
token_type_handler = self.tokens.get(request.token_type,
self.default_token_type_handler)
log.debug('Dispatching token_type %s request to %r.',
request.token_type, token_type_handler)
return token_type_handler.validate_request(request), request | python | def verify_request(self, uri, http_method='GET', body=None, headers=None,
scopes=None):
"""Validate client, code etc, return body + headers"""
request = Request(uri, http_method, body, headers)
request.token_type = self.find_token_type(request)
request.scopes = scopes
token_type_handler = self.tokens.get(request.token_type,
self.default_token_type_handler)
log.debug('Dispatching token_type %s request to %r.',
request.token_type, token_type_handler)
return token_type_handler.validate_request(request), request | [
"def",
"verify_request",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"scopes",
"=",
"None",
")",
":",
"request",
"=",
"Request",
"(",
"uri",
",",
"http_method",
",",
"body",
",",
"headers",
")",
"request",
".",
"token_type",
"=",
"self",
".",
"find_token_type",
"(",
"request",
")",
"request",
".",
"scopes",
"=",
"scopes",
"token_type_handler",
"=",
"self",
".",
"tokens",
".",
"get",
"(",
"request",
".",
"token_type",
",",
"self",
".",
"default_token_type_handler",
")",
"log",
".",
"debug",
"(",
"'Dispatching token_type %s request to %r.'",
",",
"request",
".",
"token_type",
",",
"token_type_handler",
")",
"return",
"token_type_handler",
".",
"validate_request",
"(",
"request",
")",
",",
"request"
] | Validate client, code etc, return body + headers | [
"Validate",
"client",
"code",
"etc",
"return",
"body",
"+",
"headers"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/resource.py#L65-L75 |
229,854 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/resource.py | ResourceEndpoint.find_token_type | def find_token_type(self, request):
"""Token type identification.
RFC 6749 does not provide a method for easily differentiating between
different token types during protected resource access. We estimate
the most likely token type (if any) by asking each known token type
to give an estimation based on the request.
"""
estimates = sorted(((t.estimate_type(request), n)
for n, t in self.tokens.items()), reverse=True)
return estimates[0][1] if len(estimates) else None | python | def find_token_type(self, request):
"""Token type identification.
RFC 6749 does not provide a method for easily differentiating between
different token types during protected resource access. We estimate
the most likely token type (if any) by asking each known token type
to give an estimation based on the request.
"""
estimates = sorted(((t.estimate_type(request), n)
for n, t in self.tokens.items()), reverse=True)
return estimates[0][1] if len(estimates) else None | [
"def",
"find_token_type",
"(",
"self",
",",
"request",
")",
":",
"estimates",
"=",
"sorted",
"(",
"(",
"(",
"t",
".",
"estimate_type",
"(",
"request",
")",
",",
"n",
")",
"for",
"n",
",",
"t",
"in",
"self",
".",
"tokens",
".",
"items",
"(",
")",
")",
",",
"reverse",
"=",
"True",
")",
"return",
"estimates",
"[",
"0",
"]",
"[",
"1",
"]",
"if",
"len",
"(",
"estimates",
")",
"else",
"None"
] | Token type identification.
RFC 6749 does not provide a method for easily differentiating between
different token types during protected resource access. We estimate
the most likely token type (if any) by asking each known token type
to give an estimation based on the request. | [
"Token",
"type",
"identification",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/resource.py#L77-L87 |
229,855 | beelit94/python-terraform | python_terraform/tfstate.py | Tfstate.load_file | def load_file(file_path):
"""
Read the tfstate file and load its contents, parses then as JSON and put the result into the object
"""
log.debug('read data from {0}'.format(file_path))
if os.path.exists(file_path):
with open(file_path) as f:
json_data = json.load(f)
tf_state = Tfstate(json_data)
tf_state.tfstate_file = file_path
return tf_state
log.debug('{0} is not exist'.format(file_path))
return Tfstate() | python | def load_file(file_path):
"""
Read the tfstate file and load its contents, parses then as JSON and put the result into the object
"""
log.debug('read data from {0}'.format(file_path))
if os.path.exists(file_path):
with open(file_path) as f:
json_data = json.load(f)
tf_state = Tfstate(json_data)
tf_state.tfstate_file = file_path
return tf_state
log.debug('{0} is not exist'.format(file_path))
return Tfstate() | [
"def",
"load_file",
"(",
"file_path",
")",
":",
"log",
".",
"debug",
"(",
"'read data from {0}'",
".",
"format",
"(",
"file_path",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"json_data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"tf_state",
"=",
"Tfstate",
"(",
"json_data",
")",
"tf_state",
".",
"tfstate_file",
"=",
"file_path",
"return",
"tf_state",
"log",
".",
"debug",
"(",
"'{0} is not exist'",
".",
"format",
"(",
"file_path",
")",
")",
"return",
"Tfstate",
"(",
")"
] | Read the tfstate file and load its contents, parses then as JSON and put the result into the object | [
"Read",
"the",
"tfstate",
"file",
"and",
"load",
"its",
"contents",
"parses",
"then",
"as",
"JSON",
"and",
"put",
"the",
"result",
"into",
"the",
"object"
] | 99950cb03c37abadb0d7e136452e43f4f17dd4e1 | https://github.com/beelit94/python-terraform/blob/99950cb03c37abadb0d7e136452e43f4f17dd4e1/python_terraform/tfstate.py#L19-L34 |
229,856 | beelit94/python-terraform | python_terraform/__init__.py | Terraform.generate_cmd_string | def generate_cmd_string(self, cmd, *args, **kwargs):
"""
for any generate_cmd_string doesn't written as public method of terraform
examples:
1. call import command,
ref to https://www.terraform.io/docs/commands/import.html
--> generate_cmd_string call:
terraform import -input=true aws_instance.foo i-abcd1234
--> python call:
tf.generate_cmd_string('import', 'aws_instance.foo', 'i-abcd1234', input=True)
2. call apply command,
--> generate_cmd_string call:
terraform apply -var='a=b' -var='c=d' -no-color the_folder
--> python call:
tf.generate_cmd_string('apply', the_folder, no_color=IsFlagged, var={'a':'b', 'c':'d'})
:param cmd: command and sub-command of terraform, seperated with space
refer to https://www.terraform.io/docs/commands/index.html
:param args: arguments of a command
:param kwargs: same as kwags in method 'cmd'
:return: string of valid terraform command
"""
cmds = cmd.split()
cmds = [self.terraform_bin_path] + cmds
for option, value in kwargs.items():
if '_' in option:
option = option.replace('_', '-')
if type(value) is list:
for sub_v in value:
cmds += ['-{k}={v}'.format(k=option, v=sub_v)]
continue
if type(value) is dict:
if 'backend-config' in option:
for bk, bv in value.items():
cmds += ['-backend-config={k}={v}'.format(k=bk, v=bv)]
continue
# since map type sent in string won't work, create temp var file for
# variables, and clean it up later
else:
filename = self.temp_var_files.create(value)
cmds += ['-var-file={0}'.format(filename)]
continue
# simple flag,
if value is IsFlagged:
cmds += ['-{k}'.format(k=option)]
continue
if value is None or value is IsNotFlagged:
continue
if type(value) is bool:
value = 'true' if value else 'false'
cmds += ['-{k}={v}'.format(k=option, v=value)]
cmds += args
return cmds | python | def generate_cmd_string(self, cmd, *args, **kwargs):
"""
for any generate_cmd_string doesn't written as public method of terraform
examples:
1. call import command,
ref to https://www.terraform.io/docs/commands/import.html
--> generate_cmd_string call:
terraform import -input=true aws_instance.foo i-abcd1234
--> python call:
tf.generate_cmd_string('import', 'aws_instance.foo', 'i-abcd1234', input=True)
2. call apply command,
--> generate_cmd_string call:
terraform apply -var='a=b' -var='c=d' -no-color the_folder
--> python call:
tf.generate_cmd_string('apply', the_folder, no_color=IsFlagged, var={'a':'b', 'c':'d'})
:param cmd: command and sub-command of terraform, seperated with space
refer to https://www.terraform.io/docs/commands/index.html
:param args: arguments of a command
:param kwargs: same as kwags in method 'cmd'
:return: string of valid terraform command
"""
cmds = cmd.split()
cmds = [self.terraform_bin_path] + cmds
for option, value in kwargs.items():
if '_' in option:
option = option.replace('_', '-')
if type(value) is list:
for sub_v in value:
cmds += ['-{k}={v}'.format(k=option, v=sub_v)]
continue
if type(value) is dict:
if 'backend-config' in option:
for bk, bv in value.items():
cmds += ['-backend-config={k}={v}'.format(k=bk, v=bv)]
continue
# since map type sent in string won't work, create temp var file for
# variables, and clean it up later
else:
filename = self.temp_var_files.create(value)
cmds += ['-var-file={0}'.format(filename)]
continue
# simple flag,
if value is IsFlagged:
cmds += ['-{k}'.format(k=option)]
continue
if value is None or value is IsNotFlagged:
continue
if type(value) is bool:
value = 'true' if value else 'false'
cmds += ['-{k}={v}'.format(k=option, v=value)]
cmds += args
return cmds | [
"def",
"generate_cmd_string",
"(",
"self",
",",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cmds",
"=",
"cmd",
".",
"split",
"(",
")",
"cmds",
"=",
"[",
"self",
".",
"terraform_bin_path",
"]",
"+",
"cmds",
"for",
"option",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"'_'",
"in",
"option",
":",
"option",
"=",
"option",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"type",
"(",
"value",
")",
"is",
"list",
":",
"for",
"sub_v",
"in",
"value",
":",
"cmds",
"+=",
"[",
"'-{k}={v}'",
".",
"format",
"(",
"k",
"=",
"option",
",",
"v",
"=",
"sub_v",
")",
"]",
"continue",
"if",
"type",
"(",
"value",
")",
"is",
"dict",
":",
"if",
"'backend-config'",
"in",
"option",
":",
"for",
"bk",
",",
"bv",
"in",
"value",
".",
"items",
"(",
")",
":",
"cmds",
"+=",
"[",
"'-backend-config={k}={v}'",
".",
"format",
"(",
"k",
"=",
"bk",
",",
"v",
"=",
"bv",
")",
"]",
"continue",
"# since map type sent in string won't work, create temp var file for",
"# variables, and clean it up later",
"else",
":",
"filename",
"=",
"self",
".",
"temp_var_files",
".",
"create",
"(",
"value",
")",
"cmds",
"+=",
"[",
"'-var-file={0}'",
".",
"format",
"(",
"filename",
")",
"]",
"continue",
"# simple flag,",
"if",
"value",
"is",
"IsFlagged",
":",
"cmds",
"+=",
"[",
"'-{k}'",
".",
"format",
"(",
"k",
"=",
"option",
")",
"]",
"continue",
"if",
"value",
"is",
"None",
"or",
"value",
"is",
"IsNotFlagged",
":",
"continue",
"if",
"type",
"(",
"value",
")",
"is",
"bool",
":",
"value",
"=",
"'true'",
"if",
"value",
"else",
"'false'",
"cmds",
"+=",
"[",
"'-{k}={v}'",
".",
"format",
"(",
"k",
"=",
"option",
",",
"v",
"=",
"value",
")",
"]",
"cmds",
"+=",
"args",
"return",
"cmds"
] | for any generate_cmd_string doesn't written as public method of terraform
examples:
1. call import command,
ref to https://www.terraform.io/docs/commands/import.html
--> generate_cmd_string call:
terraform import -input=true aws_instance.foo i-abcd1234
--> python call:
tf.generate_cmd_string('import', 'aws_instance.foo', 'i-abcd1234', input=True)
2. call apply command,
--> generate_cmd_string call:
terraform apply -var='a=b' -var='c=d' -no-color the_folder
--> python call:
tf.generate_cmd_string('apply', the_folder, no_color=IsFlagged, var={'a':'b', 'c':'d'})
:param cmd: command and sub-command of terraform, seperated with space
refer to https://www.terraform.io/docs/commands/index.html
:param args: arguments of a command
:param kwargs: same as kwags in method 'cmd'
:return: string of valid terraform command | [
"for",
"any",
"generate_cmd_string",
"doesn",
"t",
"written",
"as",
"public",
"method",
"of",
"terraform"
] | 99950cb03c37abadb0d7e136452e43f4f17dd4e1 | https://github.com/beelit94/python-terraform/blob/99950cb03c37abadb0d7e136452e43f4f17dd4e1/python_terraform/__init__.py#L181-L244 |
229,857 | onelogin/python-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.get_nameid_data | def get_nameid_data(self):
"""
Gets the NameID Data provided by the SAML Response from the IdP
:returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
:rtype: dict
"""
nameid = None
nameid_data = {}
encrypted_id_data_nodes = self.__query_assertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData')
if encrypted_id_data_nodes:
encrypted_data = encrypted_id_data_nodes[0]
key = self.__settings.get_sp_key()
nameid = OneLogin_Saml2_Utils.decrypt_element(encrypted_data, key)
else:
nameid_nodes = self.__query_assertion('/saml:Subject/saml:NameID')
if nameid_nodes:
nameid = nameid_nodes[0]
is_strict = self.__settings.is_strict()
want_nameid = self.__settings.get_security_data().get('wantNameId', True)
if nameid is None:
if is_strict and want_nameid:
raise OneLogin_Saml2_ValidationError(
'NameID not found in the assertion of the Response',
OneLogin_Saml2_ValidationError.NO_NAMEID
)
else:
if is_strict and want_nameid and not OneLogin_Saml2_Utils.element_text(nameid):
raise OneLogin_Saml2_ValidationError(
'An empty NameID value found',
OneLogin_Saml2_ValidationError.EMPTY_NAMEID
)
nameid_data = {'Value': OneLogin_Saml2_Utils.element_text(nameid)}
for attr in ['Format', 'SPNameQualifier', 'NameQualifier']:
value = nameid.get(attr, None)
if value:
if is_strict and attr == 'SPNameQualifier':
sp_data = self.__settings.get_sp_data()
sp_entity_id = sp_data.get('entityId', '')
if sp_entity_id != value:
raise OneLogin_Saml2_ValidationError(
'The SPNameQualifier value mistmatch the SP entityID value.',
OneLogin_Saml2_ValidationError.SP_NAME_QUALIFIER_NAME_MISMATCH
)
nameid_data[attr] = value
return nameid_data | python | def get_nameid_data(self):
"""
Gets the NameID Data provided by the SAML Response from the IdP
:returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
:rtype: dict
"""
nameid = None
nameid_data = {}
encrypted_id_data_nodes = self.__query_assertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData')
if encrypted_id_data_nodes:
encrypted_data = encrypted_id_data_nodes[0]
key = self.__settings.get_sp_key()
nameid = OneLogin_Saml2_Utils.decrypt_element(encrypted_data, key)
else:
nameid_nodes = self.__query_assertion('/saml:Subject/saml:NameID')
if nameid_nodes:
nameid = nameid_nodes[0]
is_strict = self.__settings.is_strict()
want_nameid = self.__settings.get_security_data().get('wantNameId', True)
if nameid is None:
if is_strict and want_nameid:
raise OneLogin_Saml2_ValidationError(
'NameID not found in the assertion of the Response',
OneLogin_Saml2_ValidationError.NO_NAMEID
)
else:
if is_strict and want_nameid and not OneLogin_Saml2_Utils.element_text(nameid):
raise OneLogin_Saml2_ValidationError(
'An empty NameID value found',
OneLogin_Saml2_ValidationError.EMPTY_NAMEID
)
nameid_data = {'Value': OneLogin_Saml2_Utils.element_text(nameid)}
for attr in ['Format', 'SPNameQualifier', 'NameQualifier']:
value = nameid.get(attr, None)
if value:
if is_strict and attr == 'SPNameQualifier':
sp_data = self.__settings.get_sp_data()
sp_entity_id = sp_data.get('entityId', '')
if sp_entity_id != value:
raise OneLogin_Saml2_ValidationError(
'The SPNameQualifier value mistmatch the SP entityID value.',
OneLogin_Saml2_ValidationError.SP_NAME_QUALIFIER_NAME_MISMATCH
)
nameid_data[attr] = value
return nameid_data | [
"def",
"get_nameid_data",
"(",
"self",
")",
":",
"nameid",
"=",
"None",
"nameid_data",
"=",
"{",
"}",
"encrypted_id_data_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:Subject/saml:EncryptedID/xenc:EncryptedData'",
")",
"if",
"encrypted_id_data_nodes",
":",
"encrypted_data",
"=",
"encrypted_id_data_nodes",
"[",
"0",
"]",
"key",
"=",
"self",
".",
"__settings",
".",
"get_sp_key",
"(",
")",
"nameid",
"=",
"OneLogin_Saml2_Utils",
".",
"decrypt_element",
"(",
"encrypted_data",
",",
"key",
")",
"else",
":",
"nameid_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:Subject/saml:NameID'",
")",
"if",
"nameid_nodes",
":",
"nameid",
"=",
"nameid_nodes",
"[",
"0",
"]",
"is_strict",
"=",
"self",
".",
"__settings",
".",
"is_strict",
"(",
")",
"want_nameid",
"=",
"self",
".",
"__settings",
".",
"get_security_data",
"(",
")",
".",
"get",
"(",
"'wantNameId'",
",",
"True",
")",
"if",
"nameid",
"is",
"None",
":",
"if",
"is_strict",
"and",
"want_nameid",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'NameID not found in the assertion of the Response'",
",",
"OneLogin_Saml2_ValidationError",
".",
"NO_NAMEID",
")",
"else",
":",
"if",
"is_strict",
"and",
"want_nameid",
"and",
"not",
"OneLogin_Saml2_Utils",
".",
"element_text",
"(",
"nameid",
")",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'An empty NameID value found'",
",",
"OneLogin_Saml2_ValidationError",
".",
"EMPTY_NAMEID",
")",
"nameid_data",
"=",
"{",
"'Value'",
":",
"OneLogin_Saml2_Utils",
".",
"element_text",
"(",
"nameid",
")",
"}",
"for",
"attr",
"in",
"[",
"'Format'",
",",
"'SPNameQualifier'",
",",
"'NameQualifier'",
"]",
":",
"value",
"=",
"nameid",
".",
"get",
"(",
"attr",
",",
"None",
")",
"if",
"value",
":",
"if",
"is_strict",
"and",
"attr",
"==",
"'SPNameQualifier'",
":",
"sp_data",
"=",
"self",
".",
"__settings",
".",
"get_sp_data",
"(",
")",
"sp_entity_id",
"=",
"sp_data",
".",
"get",
"(",
"'entityId'",
",",
"''",
")",
"if",
"sp_entity_id",
"!=",
"value",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'The SPNameQualifier value mistmatch the SP entityID value.'",
",",
"OneLogin_Saml2_ValidationError",
".",
"SP_NAME_QUALIFIER_NAME_MISMATCH",
")",
"nameid_data",
"[",
"attr",
"]",
"=",
"value",
"return",
"nameid_data"
] | Gets the NameID Data provided by the SAML Response from the IdP
:returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
:rtype: dict | [
"Gets",
"the",
"NameID",
"Data",
"provided",
"by",
"the",
"SAML",
"Response",
"from",
"the",
"IdP"
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/response.py#L438-L487 |
229,858 | onelogin/python-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.validate_signed_elements | def validate_signed_elements(self, signed_elements):
"""
Verifies that the document has the expected signed nodes.
:param signed_elements: The signed elements to be checked
:type signed_elements: list
:param raise_exceptions: Whether to return false on failure or raise an exception
:type raise_exceptions: Boolean
"""
if len(signed_elements) > 2:
return False
response_tag = '{%s}Response' % OneLogin_Saml2_Constants.NS_SAMLP
assertion_tag = '{%s}Assertion' % OneLogin_Saml2_Constants.NS_SAML
if (response_tag in signed_elements and signed_elements.count(response_tag) > 1) or \
(assertion_tag in signed_elements and signed_elements.count(assertion_tag) > 1) or \
(response_tag not in signed_elements and assertion_tag not in signed_elements):
return False
# Check that the signed elements found here, are the ones that will be verified
# by OneLogin_Saml2_Utils.validate_sign
if response_tag in signed_elements:
expected_signature_nodes = OneLogin_Saml2_Utils.query(self.document, OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH)
if len(expected_signature_nodes) != 1:
raise OneLogin_Saml2_ValidationError(
'Unexpected number of Response signatures found. SAML Response rejected.',
OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_RESPONSE
)
if assertion_tag in signed_elements:
expected_signature_nodes = self.__query(OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH)
if len(expected_signature_nodes) != 1:
raise OneLogin_Saml2_ValidationError(
'Unexpected number of Assertion signatures found. SAML Response rejected.',
OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_ASSERTION
)
return True | python | def validate_signed_elements(self, signed_elements):
"""
Verifies that the document has the expected signed nodes.
:param signed_elements: The signed elements to be checked
:type signed_elements: list
:param raise_exceptions: Whether to return false on failure or raise an exception
:type raise_exceptions: Boolean
"""
if len(signed_elements) > 2:
return False
response_tag = '{%s}Response' % OneLogin_Saml2_Constants.NS_SAMLP
assertion_tag = '{%s}Assertion' % OneLogin_Saml2_Constants.NS_SAML
if (response_tag in signed_elements and signed_elements.count(response_tag) > 1) or \
(assertion_tag in signed_elements and signed_elements.count(assertion_tag) > 1) or \
(response_tag not in signed_elements and assertion_tag not in signed_elements):
return False
# Check that the signed elements found here, are the ones that will be verified
# by OneLogin_Saml2_Utils.validate_sign
if response_tag in signed_elements:
expected_signature_nodes = OneLogin_Saml2_Utils.query(self.document, OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH)
if len(expected_signature_nodes) != 1:
raise OneLogin_Saml2_ValidationError(
'Unexpected number of Response signatures found. SAML Response rejected.',
OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_RESPONSE
)
if assertion_tag in signed_elements:
expected_signature_nodes = self.__query(OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH)
if len(expected_signature_nodes) != 1:
raise OneLogin_Saml2_ValidationError(
'Unexpected number of Assertion signatures found. SAML Response rejected.',
OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_ASSERTION
)
return True | [
"def",
"validate_signed_elements",
"(",
"self",
",",
"signed_elements",
")",
":",
"if",
"len",
"(",
"signed_elements",
")",
">",
"2",
":",
"return",
"False",
"response_tag",
"=",
"'{%s}Response'",
"%",
"OneLogin_Saml2_Constants",
".",
"NS_SAMLP",
"assertion_tag",
"=",
"'{%s}Assertion'",
"%",
"OneLogin_Saml2_Constants",
".",
"NS_SAML",
"if",
"(",
"response_tag",
"in",
"signed_elements",
"and",
"signed_elements",
".",
"count",
"(",
"response_tag",
")",
">",
"1",
")",
"or",
"(",
"assertion_tag",
"in",
"signed_elements",
"and",
"signed_elements",
".",
"count",
"(",
"assertion_tag",
")",
">",
"1",
")",
"or",
"(",
"response_tag",
"not",
"in",
"signed_elements",
"and",
"assertion_tag",
"not",
"in",
"signed_elements",
")",
":",
"return",
"False",
"# Check that the signed elements found here, are the ones that will be verified",
"# by OneLogin_Saml2_Utils.validate_sign",
"if",
"response_tag",
"in",
"signed_elements",
":",
"expected_signature_nodes",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"self",
".",
"document",
",",
"OneLogin_Saml2_Utils",
".",
"RESPONSE_SIGNATURE_XPATH",
")",
"if",
"len",
"(",
"expected_signature_nodes",
")",
"!=",
"1",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'Unexpected number of Response signatures found. SAML Response rejected.'",
",",
"OneLogin_Saml2_ValidationError",
".",
"WRONG_NUMBER_OF_SIGNATURES_IN_RESPONSE",
")",
"if",
"assertion_tag",
"in",
"signed_elements",
":",
"expected_signature_nodes",
"=",
"self",
".",
"__query",
"(",
"OneLogin_Saml2_Utils",
".",
"ASSERTION_SIGNATURE_XPATH",
")",
"if",
"len",
"(",
"expected_signature_nodes",
")",
"!=",
"1",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'Unexpected number of Assertion signatures found. SAML Response rejected.'",
",",
"OneLogin_Saml2_ValidationError",
".",
"WRONG_NUMBER_OF_SIGNATURES_IN_ASSERTION",
")",
"return",
"True"
] | Verifies that the document has the expected signed nodes.
:param signed_elements: The signed elements to be checked
:type signed_elements: list
:param raise_exceptions: Whether to return false on failure or raise an exception
:type raise_exceptions: Boolean | [
"Verifies",
"that",
"the",
"document",
"has",
"the",
"expected",
"signed",
"nodes",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/response.py#L677-L716 |
229,859 | onelogin/python-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.__decrypt_assertion | def __decrypt_assertion(self, dom):
"""
Decrypts the Assertion
:raises: Exception if no private key available
:param dom: Encrypted Assertion
:type dom: Element
:returns: Decrypted Assertion
:rtype: Element
"""
key = self.__settings.get_sp_key()
debug = self.__settings.is_debug_active()
if not key:
raise OneLogin_Saml2_Error(
'No private key available to decrypt the assertion, check settings',
OneLogin_Saml2_Error.PRIVATE_KEY_NOT_FOUND
)
encrypted_assertion_nodes = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/saml:EncryptedAssertion')
if encrypted_assertion_nodes:
encrypted_data_nodes = OneLogin_Saml2_Utils.query(encrypted_assertion_nodes[0], '//saml:EncryptedAssertion/xenc:EncryptedData')
if encrypted_data_nodes:
keyinfo = OneLogin_Saml2_Utils.query(encrypted_assertion_nodes[0], '//saml:EncryptedAssertion/xenc:EncryptedData/ds:KeyInfo')
if not keyinfo:
raise OneLogin_Saml2_ValidationError(
'No KeyInfo present, invalid Assertion',
OneLogin_Saml2_ValidationError.KEYINFO_NOT_FOUND_IN_ENCRYPTED_DATA
)
keyinfo = keyinfo[0]
children = keyinfo.getchildren()
if not children:
raise OneLogin_Saml2_ValidationError(
'KeyInfo has no children nodes, invalid Assertion',
OneLogin_Saml2_ValidationError.CHILDREN_NODE_NOT_FOUND_IN_KEYINFO
)
for child in children:
if 'RetrievalMethod' in child.tag:
if child.attrib['Type'] != 'http://www.w3.org/2001/04/xmlenc#EncryptedKey':
raise OneLogin_Saml2_ValidationError(
'Unsupported Retrieval Method found',
OneLogin_Saml2_ValidationError.UNSUPPORTED_RETRIEVAL_METHOD
)
uri = child.attrib['URI']
if not uri.startswith('#'):
break
uri = uri.split('#')[1]
encrypted_key = OneLogin_Saml2_Utils.query(encrypted_assertion_nodes[0], './xenc:EncryptedKey[@Id=$tagid]', None, uri)
if encrypted_key:
keyinfo.append(encrypted_key[0])
encrypted_data = encrypted_data_nodes[0]
decrypted = OneLogin_Saml2_Utils.decrypt_element(encrypted_data, key, debug=debug, inplace=True)
dom.replace(encrypted_assertion_nodes[0], decrypted)
return dom | python | def __decrypt_assertion(self, dom):
"""
Decrypts the Assertion
:raises: Exception if no private key available
:param dom: Encrypted Assertion
:type dom: Element
:returns: Decrypted Assertion
:rtype: Element
"""
key = self.__settings.get_sp_key()
debug = self.__settings.is_debug_active()
if not key:
raise OneLogin_Saml2_Error(
'No private key available to decrypt the assertion, check settings',
OneLogin_Saml2_Error.PRIVATE_KEY_NOT_FOUND
)
encrypted_assertion_nodes = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/saml:EncryptedAssertion')
if encrypted_assertion_nodes:
encrypted_data_nodes = OneLogin_Saml2_Utils.query(encrypted_assertion_nodes[0], '//saml:EncryptedAssertion/xenc:EncryptedData')
if encrypted_data_nodes:
keyinfo = OneLogin_Saml2_Utils.query(encrypted_assertion_nodes[0], '//saml:EncryptedAssertion/xenc:EncryptedData/ds:KeyInfo')
if not keyinfo:
raise OneLogin_Saml2_ValidationError(
'No KeyInfo present, invalid Assertion',
OneLogin_Saml2_ValidationError.KEYINFO_NOT_FOUND_IN_ENCRYPTED_DATA
)
keyinfo = keyinfo[0]
children = keyinfo.getchildren()
if not children:
raise OneLogin_Saml2_ValidationError(
'KeyInfo has no children nodes, invalid Assertion',
OneLogin_Saml2_ValidationError.CHILDREN_NODE_NOT_FOUND_IN_KEYINFO
)
for child in children:
if 'RetrievalMethod' in child.tag:
if child.attrib['Type'] != 'http://www.w3.org/2001/04/xmlenc#EncryptedKey':
raise OneLogin_Saml2_ValidationError(
'Unsupported Retrieval Method found',
OneLogin_Saml2_ValidationError.UNSUPPORTED_RETRIEVAL_METHOD
)
uri = child.attrib['URI']
if not uri.startswith('#'):
break
uri = uri.split('#')[1]
encrypted_key = OneLogin_Saml2_Utils.query(encrypted_assertion_nodes[0], './xenc:EncryptedKey[@Id=$tagid]', None, uri)
if encrypted_key:
keyinfo.append(encrypted_key[0])
encrypted_data = encrypted_data_nodes[0]
decrypted = OneLogin_Saml2_Utils.decrypt_element(encrypted_data, key, debug=debug, inplace=True)
dom.replace(encrypted_assertion_nodes[0], decrypted)
return dom | [
"def",
"__decrypt_assertion",
"(",
"self",
",",
"dom",
")",
":",
"key",
"=",
"self",
".",
"__settings",
".",
"get_sp_key",
"(",
")",
"debug",
"=",
"self",
".",
"__settings",
".",
"is_debug_active",
"(",
")",
"if",
"not",
"key",
":",
"raise",
"OneLogin_Saml2_Error",
"(",
"'No private key available to decrypt the assertion, check settings'",
",",
"OneLogin_Saml2_Error",
".",
"PRIVATE_KEY_NOT_FOUND",
")",
"encrypted_assertion_nodes",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"dom",
",",
"'/samlp:Response/saml:EncryptedAssertion'",
")",
"if",
"encrypted_assertion_nodes",
":",
"encrypted_data_nodes",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"encrypted_assertion_nodes",
"[",
"0",
"]",
",",
"'//saml:EncryptedAssertion/xenc:EncryptedData'",
")",
"if",
"encrypted_data_nodes",
":",
"keyinfo",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"encrypted_assertion_nodes",
"[",
"0",
"]",
",",
"'//saml:EncryptedAssertion/xenc:EncryptedData/ds:KeyInfo'",
")",
"if",
"not",
"keyinfo",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'No KeyInfo present, invalid Assertion'",
",",
"OneLogin_Saml2_ValidationError",
".",
"KEYINFO_NOT_FOUND_IN_ENCRYPTED_DATA",
")",
"keyinfo",
"=",
"keyinfo",
"[",
"0",
"]",
"children",
"=",
"keyinfo",
".",
"getchildren",
"(",
")",
"if",
"not",
"children",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'KeyInfo has no children nodes, invalid Assertion'",
",",
"OneLogin_Saml2_ValidationError",
".",
"CHILDREN_NODE_NOT_FOUND_IN_KEYINFO",
")",
"for",
"child",
"in",
"children",
":",
"if",
"'RetrievalMethod'",
"in",
"child",
".",
"tag",
":",
"if",
"child",
".",
"attrib",
"[",
"'Type'",
"]",
"!=",
"'http://www.w3.org/2001/04/xmlenc#EncryptedKey'",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'Unsupported Retrieval Method found'",
",",
"OneLogin_Saml2_ValidationError",
".",
"UNSUPPORTED_RETRIEVAL_METHOD",
")",
"uri",
"=",
"child",
".",
"attrib",
"[",
"'URI'",
"]",
"if",
"not",
"uri",
".",
"startswith",
"(",
"'#'",
")",
":",
"break",
"uri",
"=",
"uri",
".",
"split",
"(",
"'#'",
")",
"[",
"1",
"]",
"encrypted_key",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"encrypted_assertion_nodes",
"[",
"0",
"]",
",",
"'./xenc:EncryptedKey[@Id=$tagid]'",
",",
"None",
",",
"uri",
")",
"if",
"encrypted_key",
":",
"keyinfo",
".",
"append",
"(",
"encrypted_key",
"[",
"0",
"]",
")",
"encrypted_data",
"=",
"encrypted_data_nodes",
"[",
"0",
"]",
"decrypted",
"=",
"OneLogin_Saml2_Utils",
".",
"decrypt_element",
"(",
"encrypted_data",
",",
"key",
",",
"debug",
"=",
"debug",
",",
"inplace",
"=",
"True",
")",
"dom",
".",
"replace",
"(",
"encrypted_assertion_nodes",
"[",
"0",
"]",
",",
"decrypted",
")",
"return",
"dom"
] | Decrypts the Assertion
:raises: Exception if no private key available
:param dom: Encrypted Assertion
:type dom: Element
:returns: Decrypted Assertion
:rtype: Element | [
"Decrypts",
"the",
"Assertion"
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/response.py#L799-L856 |
229,860 | onelogin/python-saml | src/onelogin/saml2/idp_metadata_parser.py | OneLogin_Saml2_IdPMetadataParser.get_metadata | def get_metadata(url, validate_cert=True):
"""
Gets the metadata XML from the provided URL
:param url: Url where the XML of the Identity Provider Metadata is published.
:type url: string
:param validate_cert: If the url uses https schema, that flag enables or not the verification of the associated certificate.
:type validate_cert: bool
:returns: metadata XML
:rtype: string
"""
valid = False
if validate_cert:
response = urllib2.urlopen(url)
else:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urllib2.urlopen(url, context=ctx)
xml = response.read()
if xml:
try:
dom = fromstring(xml, forbid_dtd=True)
idp_descriptor_nodes = OneLogin_Saml2_Utils.query(dom, '//md:IDPSSODescriptor')
if idp_descriptor_nodes:
valid = True
except Exception:
pass
if not valid:
raise Exception('Not valid IdP XML found from URL: %s' % (url))
return xml | python | def get_metadata(url, validate_cert=True):
"""
Gets the metadata XML from the provided URL
:param url: Url where the XML of the Identity Provider Metadata is published.
:type url: string
:param validate_cert: If the url uses https schema, that flag enables or not the verification of the associated certificate.
:type validate_cert: bool
:returns: metadata XML
:rtype: string
"""
valid = False
if validate_cert:
response = urllib2.urlopen(url)
else:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urllib2.urlopen(url, context=ctx)
xml = response.read()
if xml:
try:
dom = fromstring(xml, forbid_dtd=True)
idp_descriptor_nodes = OneLogin_Saml2_Utils.query(dom, '//md:IDPSSODescriptor')
if idp_descriptor_nodes:
valid = True
except Exception:
pass
if not valid:
raise Exception('Not valid IdP XML found from URL: %s' % (url))
return xml | [
"def",
"get_metadata",
"(",
"url",
",",
"validate_cert",
"=",
"True",
")",
":",
"valid",
"=",
"False",
"if",
"validate_cert",
":",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"else",
":",
"ctx",
"=",
"ssl",
".",
"create_default_context",
"(",
")",
"ctx",
".",
"check_hostname",
"=",
"False",
"ctx",
".",
"verify_mode",
"=",
"ssl",
".",
"CERT_NONE",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
",",
"context",
"=",
"ctx",
")",
"xml",
"=",
"response",
".",
"read",
"(",
")",
"if",
"xml",
":",
"try",
":",
"dom",
"=",
"fromstring",
"(",
"xml",
",",
"forbid_dtd",
"=",
"True",
")",
"idp_descriptor_nodes",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"dom",
",",
"'//md:IDPSSODescriptor'",
")",
"if",
"idp_descriptor_nodes",
":",
"valid",
"=",
"True",
"except",
"Exception",
":",
"pass",
"if",
"not",
"valid",
":",
"raise",
"Exception",
"(",
"'Not valid IdP XML found from URL: %s'",
"%",
"(",
"url",
")",
")",
"return",
"xml"
] | Gets the metadata XML from the provided URL
:param url: Url where the XML of the Identity Provider Metadata is published.
:type url: string
:param validate_cert: If the url uses https schema, that flag enables or not the verification of the associated certificate.
:type validate_cert: bool
:returns: metadata XML
:rtype: string | [
"Gets",
"the",
"metadata",
"XML",
"from",
"the",
"provided",
"URL"
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/idp_metadata_parser.py#L28-L63 |
229,861 | onelogin/python-saml | src/onelogin/saml2/utils.py | print_xmlsec_errors | def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg):
"""
Auxiliary method. It overrides the default xmlsec debug message.
"""
info = []
if error_object != "unknown":
info.append("obj=" + error_object)
if error_subject != "unknown":
info.append("subject=" + error_subject)
if msg.strip():
info.append("msg=" + msg)
if reason != 1:
info.append("errno=%d" % reason)
if info:
print("%s:%d(%s)" % (filename, line, func), " ".join(info)) | python | def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg):
"""
Auxiliary method. It overrides the default xmlsec debug message.
"""
info = []
if error_object != "unknown":
info.append("obj=" + error_object)
if error_subject != "unknown":
info.append("subject=" + error_subject)
if msg.strip():
info.append("msg=" + msg)
if reason != 1:
info.append("errno=%d" % reason)
if info:
print("%s:%d(%s)" % (filename, line, func), " ".join(info)) | [
"def",
"print_xmlsec_errors",
"(",
"filename",
",",
"line",
",",
"func",
",",
"error_object",
",",
"error_subject",
",",
"reason",
",",
"msg",
")",
":",
"info",
"=",
"[",
"]",
"if",
"error_object",
"!=",
"\"unknown\"",
":",
"info",
".",
"append",
"(",
"\"obj=\"",
"+",
"error_object",
")",
"if",
"error_subject",
"!=",
"\"unknown\"",
":",
"info",
".",
"append",
"(",
"\"subject=\"",
"+",
"error_subject",
")",
"if",
"msg",
".",
"strip",
"(",
")",
":",
"info",
".",
"append",
"(",
"\"msg=\"",
"+",
"msg",
")",
"if",
"reason",
"!=",
"1",
":",
"info",
".",
"append",
"(",
"\"errno=%d\"",
"%",
"reason",
")",
"if",
"info",
":",
"print",
"(",
"\"%s:%d(%s)\"",
"%",
"(",
"filename",
",",
"line",
",",
"func",
")",
",",
"\" \"",
".",
"join",
"(",
"info",
")",
")"
] | Auxiliary method. It overrides the default xmlsec debug message. | [
"Auxiliary",
"method",
".",
"It",
"overrides",
"the",
"default",
"xmlsec",
"debug",
"message",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L63-L78 |
229,862 | onelogin/python-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.get_self_host | def get_self_host(request_data):
"""
Returns the current host.
:param request_data: The request as a dict
:type: dict
:return: The current host
:rtype: string
"""
if 'http_host' in request_data:
current_host = request_data['http_host']
elif 'server_name' in request_data:
current_host = request_data['server_name']
else:
raise Exception('No hostname defined')
if ':' in current_host:
current_host_data = current_host.split(':')
possible_port = current_host_data[-1]
try:
possible_port = float(possible_port)
current_host = current_host_data[0]
except ValueError:
current_host = ':'.join(current_host_data)
return current_host | python | def get_self_host(request_data):
"""
Returns the current host.
:param request_data: The request as a dict
:type: dict
:return: The current host
:rtype: string
"""
if 'http_host' in request_data:
current_host = request_data['http_host']
elif 'server_name' in request_data:
current_host = request_data['server_name']
else:
raise Exception('No hostname defined')
if ':' in current_host:
current_host_data = current_host.split(':')
possible_port = current_host_data[-1]
try:
possible_port = float(possible_port)
current_host = current_host_data[0]
except ValueError:
current_host = ':'.join(current_host_data)
return current_host | [
"def",
"get_self_host",
"(",
"request_data",
")",
":",
"if",
"'http_host'",
"in",
"request_data",
":",
"current_host",
"=",
"request_data",
"[",
"'http_host'",
"]",
"elif",
"'server_name'",
"in",
"request_data",
":",
"current_host",
"=",
"request_data",
"[",
"'server_name'",
"]",
"else",
":",
"raise",
"Exception",
"(",
"'No hostname defined'",
")",
"if",
"':'",
"in",
"current_host",
":",
"current_host_data",
"=",
"current_host",
".",
"split",
"(",
"':'",
")",
"possible_port",
"=",
"current_host_data",
"[",
"-",
"1",
"]",
"try",
":",
"possible_port",
"=",
"float",
"(",
"possible_port",
")",
"current_host",
"=",
"current_host_data",
"[",
"0",
"]",
"except",
"ValueError",
":",
"current_host",
"=",
"':'",
".",
"join",
"(",
"current_host_data",
")",
"return",
"current_host"
] | Returns the current host.
:param request_data: The request as a dict
:type: dict
:return: The current host
:rtype: string | [
"Returns",
"the",
"current",
"host",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L315-L341 |
229,863 | onelogin/python-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.parse_duration | def parse_duration(duration, timestamp=None):
"""
Interprets a ISO8601 duration value relative to a given timestamp.
:param duration: The duration, as a string.
:type: string
:param timestamp: The unix timestamp we should apply the duration to.
Optional, default to the current time.
:type: string
:return: The new timestamp, after the duration is applied.
:rtype: int
"""
assert isinstance(duration, basestring)
assert timestamp is None or isinstance(timestamp, int)
timedelta = duration_parser(duration)
if timestamp is None:
data = datetime.utcnow() + timedelta
else:
data = datetime.utcfromtimestamp(timestamp) + timedelta
return calendar.timegm(data.utctimetuple()) | python | def parse_duration(duration, timestamp=None):
"""
Interprets a ISO8601 duration value relative to a given timestamp.
:param duration: The duration, as a string.
:type: string
:param timestamp: The unix timestamp we should apply the duration to.
Optional, default to the current time.
:type: string
:return: The new timestamp, after the duration is applied.
:rtype: int
"""
assert isinstance(duration, basestring)
assert timestamp is None or isinstance(timestamp, int)
timedelta = duration_parser(duration)
if timestamp is None:
data = datetime.utcnow() + timedelta
else:
data = datetime.utcfromtimestamp(timestamp) + timedelta
return calendar.timegm(data.utctimetuple()) | [
"def",
"parse_duration",
"(",
"duration",
",",
"timestamp",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"duration",
",",
"basestring",
")",
"assert",
"timestamp",
"is",
"None",
"or",
"isinstance",
"(",
"timestamp",
",",
"int",
")",
"timedelta",
"=",
"duration_parser",
"(",
"duration",
")",
"if",
"timestamp",
"is",
"None",
":",
"data",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"else",
":",
"data",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"timestamp",
")",
"+",
"timedelta",
"return",
"calendar",
".",
"timegm",
"(",
"data",
".",
"utctimetuple",
"(",
")",
")"
] | Interprets a ISO8601 duration value relative to a given timestamp.
:param duration: The duration, as a string.
:type: string
:param timestamp: The unix timestamp we should apply the duration to.
Optional, default to the current time.
:type: string
:return: The new timestamp, after the duration is applied.
:rtype: int | [
"Interprets",
"a",
"ISO8601",
"duration",
"value",
"relative",
"to",
"a",
"given",
"timestamp",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L477-L499 |
229,864 | onelogin/python-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.get_status | def get_status(dom):
"""
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
"""
status = {}
status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status')
if len(status_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS
)
code_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode', status_entry[0])
if len(code_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status Code on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS_CODE
)
code = code_entry[0].values()[0]
status['code'] = code
status['msg'] = ''
message_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusMessage', status_entry[0])
if len(message_entry) == 0:
subcode_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode', status_entry[0])
if len(subcode_entry) == 1:
status['msg'] = subcode_entry[0].values()[0]
elif len(message_entry) == 1:
status['msg'] = OneLogin_Saml2_Utils.element_text(message_entry[0])
return status | python | def get_status(dom):
"""
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
"""
status = {}
status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status')
if len(status_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS
)
code_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode', status_entry[0])
if len(code_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status Code on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS_CODE
)
code = code_entry[0].values()[0]
status['code'] = code
status['msg'] = ''
message_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusMessage', status_entry[0])
if len(message_entry) == 0:
subcode_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode', status_entry[0])
if len(subcode_entry) == 1:
status['msg'] = subcode_entry[0].values()[0]
elif len(message_entry) == 1:
status['msg'] = OneLogin_Saml2_Utils.element_text(message_entry[0])
return status | [
"def",
"get_status",
"(",
"dom",
")",
":",
"status",
"=",
"{",
"}",
"status_entry",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"dom",
",",
"'/samlp:Response/samlp:Status'",
")",
"if",
"len",
"(",
"status_entry",
")",
"!=",
"1",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'Missing Status on response'",
",",
"OneLogin_Saml2_ValidationError",
".",
"MISSING_STATUS",
")",
"code_entry",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"dom",
",",
"'/samlp:Response/samlp:Status/samlp:StatusCode'",
",",
"status_entry",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"code_entry",
")",
"!=",
"1",
":",
"raise",
"OneLogin_Saml2_ValidationError",
"(",
"'Missing Status Code on response'",
",",
"OneLogin_Saml2_ValidationError",
".",
"MISSING_STATUS_CODE",
")",
"code",
"=",
"code_entry",
"[",
"0",
"]",
".",
"values",
"(",
")",
"[",
"0",
"]",
"status",
"[",
"'code'",
"]",
"=",
"code",
"status",
"[",
"'msg'",
"]",
"=",
"''",
"message_entry",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"dom",
",",
"'/samlp:Response/samlp:Status/samlp:StatusMessage'",
",",
"status_entry",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"message_entry",
")",
"==",
"0",
":",
"subcode_entry",
"=",
"OneLogin_Saml2_Utils",
".",
"query",
"(",
"dom",
",",
"'/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode'",
",",
"status_entry",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"subcode_entry",
")",
"==",
"1",
":",
"status",
"[",
"'msg'",
"]",
"=",
"subcode_entry",
"[",
"0",
"]",
".",
"values",
"(",
")",
"[",
"0",
"]",
"elif",
"len",
"(",
"message_entry",
")",
"==",
"1",
":",
"status",
"[",
"'msg'",
"]",
"=",
"OneLogin_Saml2_Utils",
".",
"element_text",
"(",
"message_entry",
"[",
"0",
"]",
")",
"return",
"status"
] | Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict | [
"Gets",
"Status",
"from",
"a",
"Response",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L734-L771 |
229,865 | onelogin/python-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.write_temp_file | def write_temp_file(content):
"""
Writes some content into a temporary file and returns it.
:param content: The file content
:type: string
:returns: The temporary file
:rtype: file-like object
"""
f_temp = NamedTemporaryFile(delete=True)
f_temp.file.write(content)
f_temp.file.flush()
return f_temp | python | def write_temp_file(content):
"""
Writes some content into a temporary file and returns it.
:param content: The file content
:type: string
:returns: The temporary file
:rtype: file-like object
"""
f_temp = NamedTemporaryFile(delete=True)
f_temp.file.write(content)
f_temp.file.flush()
return f_temp | [
"def",
"write_temp_file",
"(",
"content",
")",
":",
"f_temp",
"=",
"NamedTemporaryFile",
"(",
"delete",
"=",
"True",
")",
"f_temp",
".",
"file",
".",
"write",
"(",
"content",
")",
"f_temp",
".",
"file",
".",
"flush",
"(",
")",
"return",
"f_temp"
] | Writes some content into a temporary file and returns it.
:param content: The file content
:type: string
:returns: The temporary file
:rtype: file-like object | [
"Writes",
"some",
"content",
"into",
"a",
"temporary",
"file",
"and",
"returns",
"it",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/utils.py#L814-L827 |
229,866 | onelogin/python-saml | src/onelogin/saml2/settings.py | OneLogin_Saml2_Settings.__add_default_values | def __add_default_values(self):
"""
Add default values if the settings info is not complete
"""
self.__sp.setdefault('assertionConsumerService', {})
self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST)
self.__sp.setdefault('attributeConsumingService', {})
self.__sp.setdefault('singleLogoutService', {})
self.__sp['singleLogoutService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT)
# Related to nameID
self.__sp.setdefault('NameIDFormat', OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED)
self.__security.setdefault('nameIdEncrypted', False)
# Metadata format
self.__security.setdefault('metadataValidUntil', None) # None means use default
self.__security.setdefault('metadataCacheDuration', None) # None means use default
# Sign provided
self.__security.setdefault('authnRequestsSigned', False)
self.__security.setdefault('logoutRequestSigned', False)
self.__security.setdefault('logoutResponseSigned', False)
self.__security.setdefault('signMetadata', False)
# Sign expected
self.__security.setdefault('wantMessagesSigned', False)
self.__security.setdefault('wantAssertionsSigned', False)
# NameID element expected
self.__security.setdefault('wantNameId', True)
# SAML responses with a InResponseTo attribute not rejected when requestId not passed
self.__security.setdefault('rejectUnsolicitedResponsesWithInResponseTo', False)
# Encrypt expected
self.__security.setdefault('wantAssertionsEncrypted', False)
self.__security.setdefault('wantNameIdEncrypted', False)
# Signature Algorithm
self.__security.setdefault('signatureAlgorithm', OneLogin_Saml2_Constants.RSA_SHA1)
# Digest Algorithm
self.__security.setdefault('digestAlgorithm', OneLogin_Saml2_Constants.SHA1)
# AttributeStatement required by default
self.__security.setdefault('wantAttributeStatement', True)
self.__idp.setdefault('x509cert', '')
self.__idp.setdefault('certFingerprint', '')
self.__idp.setdefault('certFingerprintAlgorithm', 'sha1')
self.__sp.setdefault('x509cert', '')
self.__sp.setdefault('privateKey', '')
self.__security.setdefault('requestedAuthnContext', True)
self.__security.setdefault('failOnAuthnContextMismatch', False) | python | def __add_default_values(self):
"""
Add default values if the settings info is not complete
"""
self.__sp.setdefault('assertionConsumerService', {})
self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST)
self.__sp.setdefault('attributeConsumingService', {})
self.__sp.setdefault('singleLogoutService', {})
self.__sp['singleLogoutService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT)
# Related to nameID
self.__sp.setdefault('NameIDFormat', OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED)
self.__security.setdefault('nameIdEncrypted', False)
# Metadata format
self.__security.setdefault('metadataValidUntil', None) # None means use default
self.__security.setdefault('metadataCacheDuration', None) # None means use default
# Sign provided
self.__security.setdefault('authnRequestsSigned', False)
self.__security.setdefault('logoutRequestSigned', False)
self.__security.setdefault('logoutResponseSigned', False)
self.__security.setdefault('signMetadata', False)
# Sign expected
self.__security.setdefault('wantMessagesSigned', False)
self.__security.setdefault('wantAssertionsSigned', False)
# NameID element expected
self.__security.setdefault('wantNameId', True)
# SAML responses with a InResponseTo attribute not rejected when requestId not passed
self.__security.setdefault('rejectUnsolicitedResponsesWithInResponseTo', False)
# Encrypt expected
self.__security.setdefault('wantAssertionsEncrypted', False)
self.__security.setdefault('wantNameIdEncrypted', False)
# Signature Algorithm
self.__security.setdefault('signatureAlgorithm', OneLogin_Saml2_Constants.RSA_SHA1)
# Digest Algorithm
self.__security.setdefault('digestAlgorithm', OneLogin_Saml2_Constants.SHA1)
# AttributeStatement required by default
self.__security.setdefault('wantAttributeStatement', True)
self.__idp.setdefault('x509cert', '')
self.__idp.setdefault('certFingerprint', '')
self.__idp.setdefault('certFingerprintAlgorithm', 'sha1')
self.__sp.setdefault('x509cert', '')
self.__sp.setdefault('privateKey', '')
self.__security.setdefault('requestedAuthnContext', True)
self.__security.setdefault('failOnAuthnContextMismatch', False) | [
"def",
"__add_default_values",
"(",
"self",
")",
":",
"self",
".",
"__sp",
".",
"setdefault",
"(",
"'assertionConsumerService'",
",",
"{",
"}",
")",
"self",
".",
"__sp",
"[",
"'assertionConsumerService'",
"]",
".",
"setdefault",
"(",
"'binding'",
",",
"OneLogin_Saml2_Constants",
".",
"BINDING_HTTP_POST",
")",
"self",
".",
"__sp",
".",
"setdefault",
"(",
"'attributeConsumingService'",
",",
"{",
"}",
")",
"self",
".",
"__sp",
".",
"setdefault",
"(",
"'singleLogoutService'",
",",
"{",
"}",
")",
"self",
".",
"__sp",
"[",
"'singleLogoutService'",
"]",
".",
"setdefault",
"(",
"'binding'",
",",
"OneLogin_Saml2_Constants",
".",
"BINDING_HTTP_REDIRECT",
")",
"# Related to nameID",
"self",
".",
"__sp",
".",
"setdefault",
"(",
"'NameIDFormat'",
",",
"OneLogin_Saml2_Constants",
".",
"NAMEID_UNSPECIFIED",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'nameIdEncrypted'",
",",
"False",
")",
"# Metadata format",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'metadataValidUntil'",
",",
"None",
")",
"# None means use default",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'metadataCacheDuration'",
",",
"None",
")",
"# None means use default",
"# Sign provided",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'authnRequestsSigned'",
",",
"False",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'logoutRequestSigned'",
",",
"False",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'logoutResponseSigned'",
",",
"False",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'signMetadata'",
",",
"False",
")",
"# Sign expected",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'wantMessagesSigned'",
",",
"False",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'wantAssertionsSigned'",
",",
"False",
")",
"# NameID element expected",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'wantNameId'",
",",
"True",
")",
"# SAML responses with a InResponseTo attribute not rejected when requestId not passed",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'rejectUnsolicitedResponsesWithInResponseTo'",
",",
"False",
")",
"# Encrypt expected",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'wantAssertionsEncrypted'",
",",
"False",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'wantNameIdEncrypted'",
",",
"False",
")",
"# Signature Algorithm",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'signatureAlgorithm'",
",",
"OneLogin_Saml2_Constants",
".",
"RSA_SHA1",
")",
"# Digest Algorithm",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'digestAlgorithm'",
",",
"OneLogin_Saml2_Constants",
".",
"SHA1",
")",
"# AttributeStatement required by default",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'wantAttributeStatement'",
",",
"True",
")",
"self",
".",
"__idp",
".",
"setdefault",
"(",
"'x509cert'",
",",
"''",
")",
"self",
".",
"__idp",
".",
"setdefault",
"(",
"'certFingerprint'",
",",
"''",
")",
"self",
".",
"__idp",
".",
"setdefault",
"(",
"'certFingerprintAlgorithm'",
",",
"'sha1'",
")",
"self",
".",
"__sp",
".",
"setdefault",
"(",
"'x509cert'",
",",
"''",
")",
"self",
".",
"__sp",
".",
"setdefault",
"(",
"'privateKey'",
",",
"''",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'requestedAuthnContext'",
",",
"True",
")",
"self",
".",
"__security",
".",
"setdefault",
"(",
"'failOnAuthnContextMismatch'",
",",
"False",
")"
] | Add default values if the settings info is not complete | [
"Add",
"default",
"values",
"if",
"the",
"settings",
"info",
"is",
"not",
"complete"
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/settings.py#L250-L307 |
229,867 | onelogin/python-saml | src/onelogin/saml2/auth.py | OneLogin_Saml2_Auth.login | def login(self, return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None):
"""
Initiates the SSO process.
:param return_to: Optional argument. The target URL the user should be redirected to after login.
:type return_to: string
:param force_authn: Optional argument. When true the AuthNRequest will set the ForceAuthn='true'.
:type force_authn: bool
:param is_passive: Optional argument. When true the AuthNRequest will set the Ispassive='true'.
:type is_passive: bool
:param set_nameid_policy: Optional argument. When true the AuthNRequest will set a nameIdPolicy element.
:type set_nameid_policy: bool
:param name_id_value_req: Optional argument. Indicates to the IdP the subject that should be authenticated
:type name_id_value_req: string
:returns: Redirection URL
:rtype: string
"""
authn_request = OneLogin_Saml2_Authn_Request(self.__settings, force_authn, is_passive, set_nameid_policy, name_id_value_req)
self.__last_request = authn_request.get_xml()
self.__last_request_id = authn_request.get_id()
saml_request = authn_request.get_request()
parameters = {'SAMLRequest': saml_request}
if return_to is not None:
parameters['RelayState'] = return_to
else:
parameters['RelayState'] = OneLogin_Saml2_Utils.get_self_url_no_query(self.__request_data)
security = self.__settings.get_security_data()
if security.get('authnRequestsSigned', False):
parameters['SigAlg'] = security['signatureAlgorithm']
parameters['Signature'] = self.build_request_signature(saml_request, parameters['RelayState'], security['signatureAlgorithm'])
return self.redirect_to(self.get_sso_url(), parameters) | python | def login(self, return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None):
"""
Initiates the SSO process.
:param return_to: Optional argument. The target URL the user should be redirected to after login.
:type return_to: string
:param force_authn: Optional argument. When true the AuthNRequest will set the ForceAuthn='true'.
:type force_authn: bool
:param is_passive: Optional argument. When true the AuthNRequest will set the Ispassive='true'.
:type is_passive: bool
:param set_nameid_policy: Optional argument. When true the AuthNRequest will set a nameIdPolicy element.
:type set_nameid_policy: bool
:param name_id_value_req: Optional argument. Indicates to the IdP the subject that should be authenticated
:type name_id_value_req: string
:returns: Redirection URL
:rtype: string
"""
authn_request = OneLogin_Saml2_Authn_Request(self.__settings, force_authn, is_passive, set_nameid_policy, name_id_value_req)
self.__last_request = authn_request.get_xml()
self.__last_request_id = authn_request.get_id()
saml_request = authn_request.get_request()
parameters = {'SAMLRequest': saml_request}
if return_to is not None:
parameters['RelayState'] = return_to
else:
parameters['RelayState'] = OneLogin_Saml2_Utils.get_self_url_no_query(self.__request_data)
security = self.__settings.get_security_data()
if security.get('authnRequestsSigned', False):
parameters['SigAlg'] = security['signatureAlgorithm']
parameters['Signature'] = self.build_request_signature(saml_request, parameters['RelayState'], security['signatureAlgorithm'])
return self.redirect_to(self.get_sso_url(), parameters) | [
"def",
"login",
"(",
"self",
",",
"return_to",
"=",
"None",
",",
"force_authn",
"=",
"False",
",",
"is_passive",
"=",
"False",
",",
"set_nameid_policy",
"=",
"True",
",",
"name_id_value_req",
"=",
"None",
")",
":",
"authn_request",
"=",
"OneLogin_Saml2_Authn_Request",
"(",
"self",
".",
"__settings",
",",
"force_authn",
",",
"is_passive",
",",
"set_nameid_policy",
",",
"name_id_value_req",
")",
"self",
".",
"__last_request",
"=",
"authn_request",
".",
"get_xml",
"(",
")",
"self",
".",
"__last_request_id",
"=",
"authn_request",
".",
"get_id",
"(",
")",
"saml_request",
"=",
"authn_request",
".",
"get_request",
"(",
")",
"parameters",
"=",
"{",
"'SAMLRequest'",
":",
"saml_request",
"}",
"if",
"return_to",
"is",
"not",
"None",
":",
"parameters",
"[",
"'RelayState'",
"]",
"=",
"return_to",
"else",
":",
"parameters",
"[",
"'RelayState'",
"]",
"=",
"OneLogin_Saml2_Utils",
".",
"get_self_url_no_query",
"(",
"self",
".",
"__request_data",
")",
"security",
"=",
"self",
".",
"__settings",
".",
"get_security_data",
"(",
")",
"if",
"security",
".",
"get",
"(",
"'authnRequestsSigned'",
",",
"False",
")",
":",
"parameters",
"[",
"'SigAlg'",
"]",
"=",
"security",
"[",
"'signatureAlgorithm'",
"]",
"parameters",
"[",
"'Signature'",
"]",
"=",
"self",
".",
"build_request_signature",
"(",
"saml_request",
",",
"parameters",
"[",
"'RelayState'",
"]",
",",
"security",
"[",
"'signatureAlgorithm'",
"]",
")",
"return",
"self",
".",
"redirect_to",
"(",
"self",
".",
"get_sso_url",
"(",
")",
",",
"parameters",
")"
] | Initiates the SSO process.
:param return_to: Optional argument. The target URL the user should be redirected to after login.
:type return_to: string
:param force_authn: Optional argument. When true the AuthNRequest will set the ForceAuthn='true'.
:type force_authn: bool
:param is_passive: Optional argument. When true the AuthNRequest will set the Ispassive='true'.
:type is_passive: bool
:param set_nameid_policy: Optional argument. When true the AuthNRequest will set a nameIdPolicy element.
:type set_nameid_policy: bool
:param name_id_value_req: Optional argument. Indicates to the IdP the subject that should be authenticated
:type name_id_value_req: string
:returns: Redirection URL
:rtype: string | [
"Initiates",
"the",
"SSO",
"process",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/auth.py#L326-L363 |
229,868 | onelogin/python-saml | src/onelogin/saml2/auth.py | OneLogin_Saml2_Auth.logout | def logout(self, return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None):
"""
Initiates the SLO process.
:param return_to: Optional argument. The target URL the user should be redirected to after logout.
:type return_to: string
:param name_id: The NameID that will be set in the LogoutRequest.
:type name_id: string
:param session_index: SessionIndex that identifies the session of the user.
:type session_index: string
:param nq: IDP Name Qualifier
:type: string
:param name_id_format: The NameID Format that will be set in the LogoutRequest.
:type: string
:returns: Redirection url
"""
slo_url = self.get_slo_url()
if slo_url is None:
raise OneLogin_Saml2_Error(
'The IdP does not support Single Log Out',
OneLogin_Saml2_Error.SAML_SINGLE_LOGOUT_NOT_SUPPORTED
)
if name_id is None and self.__nameid is not None:
name_id = self.__nameid
if name_id_format is None and self.__nameid_format is not None:
name_id_format = self.__nameid_format
logout_request = OneLogin_Saml2_Logout_Request(
self.__settings,
name_id=name_id,
session_index=session_index,
nq=nq,
name_id_format=name_id_format
)
self.__last_request = logout_request.get_xml()
self.__last_request_id = logout_request.id
saml_request = logout_request.get_request()
parameters = {'SAMLRequest': logout_request.get_request()}
if return_to is not None:
parameters['RelayState'] = return_to
else:
parameters['RelayState'] = OneLogin_Saml2_Utils.get_self_url_no_query(self.__request_data)
security = self.__settings.get_security_data()
if security.get('logoutRequestSigned', False):
parameters['SigAlg'] = security['signatureAlgorithm']
parameters['Signature'] = self.build_request_signature(saml_request, parameters['RelayState'], security['signatureAlgorithm'])
return self.redirect_to(slo_url, parameters) | python | def logout(self, return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None):
"""
Initiates the SLO process.
:param return_to: Optional argument. The target URL the user should be redirected to after logout.
:type return_to: string
:param name_id: The NameID that will be set in the LogoutRequest.
:type name_id: string
:param session_index: SessionIndex that identifies the session of the user.
:type session_index: string
:param nq: IDP Name Qualifier
:type: string
:param name_id_format: The NameID Format that will be set in the LogoutRequest.
:type: string
:returns: Redirection url
"""
slo_url = self.get_slo_url()
if slo_url is None:
raise OneLogin_Saml2_Error(
'The IdP does not support Single Log Out',
OneLogin_Saml2_Error.SAML_SINGLE_LOGOUT_NOT_SUPPORTED
)
if name_id is None and self.__nameid is not None:
name_id = self.__nameid
if name_id_format is None and self.__nameid_format is not None:
name_id_format = self.__nameid_format
logout_request = OneLogin_Saml2_Logout_Request(
self.__settings,
name_id=name_id,
session_index=session_index,
nq=nq,
name_id_format=name_id_format
)
self.__last_request = logout_request.get_xml()
self.__last_request_id = logout_request.id
saml_request = logout_request.get_request()
parameters = {'SAMLRequest': logout_request.get_request()}
if return_to is not None:
parameters['RelayState'] = return_to
else:
parameters['RelayState'] = OneLogin_Saml2_Utils.get_self_url_no_query(self.__request_data)
security = self.__settings.get_security_data()
if security.get('logoutRequestSigned', False):
parameters['SigAlg'] = security['signatureAlgorithm']
parameters['Signature'] = self.build_request_signature(saml_request, parameters['RelayState'], security['signatureAlgorithm'])
return self.redirect_to(slo_url, parameters) | [
"def",
"logout",
"(",
"self",
",",
"return_to",
"=",
"None",
",",
"name_id",
"=",
"None",
",",
"session_index",
"=",
"None",
",",
"nq",
"=",
"None",
",",
"name_id_format",
"=",
"None",
")",
":",
"slo_url",
"=",
"self",
".",
"get_slo_url",
"(",
")",
"if",
"slo_url",
"is",
"None",
":",
"raise",
"OneLogin_Saml2_Error",
"(",
"'The IdP does not support Single Log Out'",
",",
"OneLogin_Saml2_Error",
".",
"SAML_SINGLE_LOGOUT_NOT_SUPPORTED",
")",
"if",
"name_id",
"is",
"None",
"and",
"self",
".",
"__nameid",
"is",
"not",
"None",
":",
"name_id",
"=",
"self",
".",
"__nameid",
"if",
"name_id_format",
"is",
"None",
"and",
"self",
".",
"__nameid_format",
"is",
"not",
"None",
":",
"name_id_format",
"=",
"self",
".",
"__nameid_format",
"logout_request",
"=",
"OneLogin_Saml2_Logout_Request",
"(",
"self",
".",
"__settings",
",",
"name_id",
"=",
"name_id",
",",
"session_index",
"=",
"session_index",
",",
"nq",
"=",
"nq",
",",
"name_id_format",
"=",
"name_id_format",
")",
"self",
".",
"__last_request",
"=",
"logout_request",
".",
"get_xml",
"(",
")",
"self",
".",
"__last_request_id",
"=",
"logout_request",
".",
"id",
"saml_request",
"=",
"logout_request",
".",
"get_request",
"(",
")",
"parameters",
"=",
"{",
"'SAMLRequest'",
":",
"logout_request",
".",
"get_request",
"(",
")",
"}",
"if",
"return_to",
"is",
"not",
"None",
":",
"parameters",
"[",
"'RelayState'",
"]",
"=",
"return_to",
"else",
":",
"parameters",
"[",
"'RelayState'",
"]",
"=",
"OneLogin_Saml2_Utils",
".",
"get_self_url_no_query",
"(",
"self",
".",
"__request_data",
")",
"security",
"=",
"self",
".",
"__settings",
".",
"get_security_data",
"(",
")",
"if",
"security",
".",
"get",
"(",
"'logoutRequestSigned'",
",",
"False",
")",
":",
"parameters",
"[",
"'SigAlg'",
"]",
"=",
"security",
"[",
"'signatureAlgorithm'",
"]",
"parameters",
"[",
"'Signature'",
"]",
"=",
"self",
".",
"build_request_signature",
"(",
"saml_request",
",",
"parameters",
"[",
"'RelayState'",
"]",
",",
"security",
"[",
"'signatureAlgorithm'",
"]",
")",
"return",
"self",
".",
"redirect_to",
"(",
"slo_url",
",",
"parameters",
")"
] | Initiates the SLO process.
:param return_to: Optional argument. The target URL the user should be redirected to after logout.
:type return_to: string
:param name_id: The NameID that will be set in the LogoutRequest.
:type name_id: string
:param session_index: SessionIndex that identifies the session of the user.
:type session_index: string
:param nq: IDP Name Qualifier
:type: string
:param name_id_format: The NameID Format that will be set in the LogoutRequest.
:type: string
:returns: Redirection url | [
"Initiates",
"the",
"SLO",
"process",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/auth.py#L365-L419 |
229,869 | onelogin/python-saml | src/onelogin/saml2/auth.py | OneLogin_Saml2_Auth.get_slo_url | def get_slo_url(self):
"""
Gets the SLO URL.
:returns: An URL, the SLO endpoint of the IdP
:rtype: string
"""
url = None
idp_data = self.__settings.get_idp_data()
if 'singleLogoutService' in idp_data.keys() and 'url' in idp_data['singleLogoutService']:
url = idp_data['singleLogoutService']['url']
return url | python | def get_slo_url(self):
"""
Gets the SLO URL.
:returns: An URL, the SLO endpoint of the IdP
:rtype: string
"""
url = None
idp_data = self.__settings.get_idp_data()
if 'singleLogoutService' in idp_data.keys() and 'url' in idp_data['singleLogoutService']:
url = idp_data['singleLogoutService']['url']
return url | [
"def",
"get_slo_url",
"(",
"self",
")",
":",
"url",
"=",
"None",
"idp_data",
"=",
"self",
".",
"__settings",
".",
"get_idp_data",
"(",
")",
"if",
"'singleLogoutService'",
"in",
"idp_data",
".",
"keys",
"(",
")",
"and",
"'url'",
"in",
"idp_data",
"[",
"'singleLogoutService'",
"]",
":",
"url",
"=",
"idp_data",
"[",
"'singleLogoutService'",
"]",
"[",
"'url'",
"]",
"return",
"url"
] | Gets the SLO URL.
:returns: An URL, the SLO endpoint of the IdP
:rtype: string | [
"Gets",
"the",
"SLO",
"URL",
"."
] | 9fe7a72da5b4caa1529c1640b52d2649447ce49b | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/auth.py#L431-L442 |
229,870 | sryza/spark-timeseries | python/sparkts/utils.py | add_pyspark_path | def add_pyspark_path():
"""Add PySpark to the library path based on the value of SPARK_HOME. """
try:
spark_home = os.environ['SPARK_HOME']
sys.path.append(os.path.join(spark_home, 'python'))
py4j_src_zip = glob(os.path.join(spark_home, 'python',
'lib', 'py4j-*-src.zip'))
if len(py4j_src_zip) == 0:
raise ValueError('py4j source archive not found in %s'
% os.path.join(spark_home, 'python', 'lib'))
else:
py4j_src_zip = sorted(py4j_src_zip)[::-1]
sys.path.append(py4j_src_zip[0])
except KeyError:
logging.error("""SPARK_HOME was not set. please set it. e.g.
SPARK_HOME='/home/...' ./bin/pyspark [program]""")
exit(-1)
except ValueError as e:
logging.error(str(e))
exit(-1) | python | def add_pyspark_path():
"""Add PySpark to the library path based on the value of SPARK_HOME. """
try:
spark_home = os.environ['SPARK_HOME']
sys.path.append(os.path.join(spark_home, 'python'))
py4j_src_zip = glob(os.path.join(spark_home, 'python',
'lib', 'py4j-*-src.zip'))
if len(py4j_src_zip) == 0:
raise ValueError('py4j source archive not found in %s'
% os.path.join(spark_home, 'python', 'lib'))
else:
py4j_src_zip = sorted(py4j_src_zip)[::-1]
sys.path.append(py4j_src_zip[0])
except KeyError:
logging.error("""SPARK_HOME was not set. please set it. e.g.
SPARK_HOME='/home/...' ./bin/pyspark [program]""")
exit(-1)
except ValueError as e:
logging.error(str(e))
exit(-1) | [
"def",
"add_pyspark_path",
"(",
")",
":",
"try",
":",
"spark_home",
"=",
"os",
".",
"environ",
"[",
"'SPARK_HOME'",
"]",
"sys",
".",
"path",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"spark_home",
",",
"'python'",
")",
")",
"py4j_src_zip",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"spark_home",
",",
"'python'",
",",
"'lib'",
",",
"'py4j-*-src.zip'",
")",
")",
"if",
"len",
"(",
"py4j_src_zip",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'py4j source archive not found in %s'",
"%",
"os",
".",
"path",
".",
"join",
"(",
"spark_home",
",",
"'python'",
",",
"'lib'",
")",
")",
"else",
":",
"py4j_src_zip",
"=",
"sorted",
"(",
"py4j_src_zip",
")",
"[",
":",
":",
"-",
"1",
"]",
"sys",
".",
"path",
".",
"append",
"(",
"py4j_src_zip",
"[",
"0",
"]",
")",
"except",
"KeyError",
":",
"logging",
".",
"error",
"(",
"\"\"\"SPARK_HOME was not set. please set it. e.g.\n SPARK_HOME='/home/...' ./bin/pyspark [program]\"\"\"",
")",
"exit",
"(",
"-",
"1",
")",
"except",
"ValueError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"exit",
"(",
"-",
"1",
")"
] | Add PySpark to the library path based on the value of SPARK_HOME. | [
"Add",
"PySpark",
"to",
"the",
"library",
"path",
"based",
"on",
"the",
"value",
"of",
"SPARK_HOME",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/utils.py#L9-L30 |
229,871 | sryza/spark-timeseries | python/sparkts/utils.py | datetime_to_nanos | def datetime_to_nanos(dt):
"""
Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch.
"""
if isinstance(dt, pd.Timestamp):
return dt.value
elif isinstance(dt, str):
return pd.Timestamp(dt).value
elif isinstance(dt, long):
return dt
elif isinstance(dt, datetime):
return long(dt.strftime("%s%f")) * 1000
raise ValueError | python | def datetime_to_nanos(dt):
"""
Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch.
"""
if isinstance(dt, pd.Timestamp):
return dt.value
elif isinstance(dt, str):
return pd.Timestamp(dt).value
elif isinstance(dt, long):
return dt
elif isinstance(dt, datetime):
return long(dt.strftime("%s%f")) * 1000
raise ValueError | [
"def",
"datetime_to_nanos",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"pd",
".",
"Timestamp",
")",
":",
"return",
"dt",
".",
"value",
"elif",
"isinstance",
"(",
"dt",
",",
"str",
")",
":",
"return",
"pd",
".",
"Timestamp",
"(",
"dt",
")",
".",
"value",
"elif",
"isinstance",
"(",
"dt",
",",
"long",
")",
":",
"return",
"dt",
"elif",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
":",
"return",
"long",
"(",
"dt",
".",
"strftime",
"(",
"\"%s%f\"",
")",
")",
"*",
"1000",
"raise",
"ValueError"
] | Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch. | [
"Accepts",
"a",
"string",
"Pandas",
"Timestamp",
"or",
"long",
"and",
"returns",
"nanos",
"since",
"the",
"epoch",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/utils.py#L37-L50 |
229,872 | sryza/spark-timeseries | python/sparkts/datetimeindex.py | uniform | def uniform(start, end=None, periods=None, freq=None, sc=None):
"""
Instantiates a uniform DateTimeIndex.
Either end or periods must be specified.
Parameters
----------
start : string, long (nanos from epoch), or Pandas Timestamp
end : string, long (nanos from epoch), or Pandas Timestamp
periods : int
freq : a frequency object
sc : SparkContext
"""
dtmodule = sc._jvm.com.cloudera.sparkts.__getattr__('DateTimeIndex$').__getattr__('MODULE$')
if freq is None:
raise ValueError("Missing frequency")
elif end is None and periods == None:
raise ValueError("Need an end date or number of periods")
elif end is not None:
return DateTimeIndex(dtmodule.uniformFromInterval( \
datetime_to_nanos(start), datetime_to_nanos(end), freq._jfreq))
else:
return DateTimeIndex(dtmodule.uniform( \
datetime_to_nanos(start), periods, freq._jfreq)) | python | def uniform(start, end=None, periods=None, freq=None, sc=None):
"""
Instantiates a uniform DateTimeIndex.
Either end or periods must be specified.
Parameters
----------
start : string, long (nanos from epoch), or Pandas Timestamp
end : string, long (nanos from epoch), or Pandas Timestamp
periods : int
freq : a frequency object
sc : SparkContext
"""
dtmodule = sc._jvm.com.cloudera.sparkts.__getattr__('DateTimeIndex$').__getattr__('MODULE$')
if freq is None:
raise ValueError("Missing frequency")
elif end is None and periods == None:
raise ValueError("Need an end date or number of periods")
elif end is not None:
return DateTimeIndex(dtmodule.uniformFromInterval( \
datetime_to_nanos(start), datetime_to_nanos(end), freq._jfreq))
else:
return DateTimeIndex(dtmodule.uniform( \
datetime_to_nanos(start), periods, freq._jfreq)) | [
"def",
"uniform",
"(",
"start",
",",
"end",
"=",
"None",
",",
"periods",
"=",
"None",
",",
"freq",
"=",
"None",
",",
"sc",
"=",
"None",
")",
":",
"dtmodule",
"=",
"sc",
".",
"_jvm",
".",
"com",
".",
"cloudera",
".",
"sparkts",
".",
"__getattr__",
"(",
"'DateTimeIndex$'",
")",
".",
"__getattr__",
"(",
"'MODULE$'",
")",
"if",
"freq",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Missing frequency\"",
")",
"elif",
"end",
"is",
"None",
"and",
"periods",
"==",
"None",
":",
"raise",
"ValueError",
"(",
"\"Need an end date or number of periods\"",
")",
"elif",
"end",
"is",
"not",
"None",
":",
"return",
"DateTimeIndex",
"(",
"dtmodule",
".",
"uniformFromInterval",
"(",
"datetime_to_nanos",
"(",
"start",
")",
",",
"datetime_to_nanos",
"(",
"end",
")",
",",
"freq",
".",
"_jfreq",
")",
")",
"else",
":",
"return",
"DateTimeIndex",
"(",
"dtmodule",
".",
"uniform",
"(",
"datetime_to_nanos",
"(",
"start",
")",
",",
"periods",
",",
"freq",
".",
"_jfreq",
")",
")"
] | Instantiates a uniform DateTimeIndex.
Either end or periods must be specified.
Parameters
----------
start : string, long (nanos from epoch), or Pandas Timestamp
end : string, long (nanos from epoch), or Pandas Timestamp
periods : int
freq : a frequency object
sc : SparkContext | [
"Instantiates",
"a",
"uniform",
"DateTimeIndex",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L129-L153 |
229,873 | sryza/spark-timeseries | python/sparkts/datetimeindex.py | DateTimeIndex._zdt_to_nanos | def _zdt_to_nanos(self, zdt):
"""Extracts nanoseconds from a ZonedDateTime"""
instant = zdt.toInstant()
return instant.getNano() + instant.getEpochSecond() * 1000000000 | python | def _zdt_to_nanos(self, zdt):
"""Extracts nanoseconds from a ZonedDateTime"""
instant = zdt.toInstant()
return instant.getNano() + instant.getEpochSecond() * 1000000000 | [
"def",
"_zdt_to_nanos",
"(",
"self",
",",
"zdt",
")",
":",
"instant",
"=",
"zdt",
".",
"toInstant",
"(",
")",
"return",
"instant",
".",
"getNano",
"(",
")",
"+",
"instant",
".",
"getEpochSecond",
"(",
")",
"*",
"1000000000"
] | Extracts nanoseconds from a ZonedDateTime | [
"Extracts",
"nanoseconds",
"from",
"a",
"ZonedDateTime"
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L24-L27 |
229,874 | sryza/spark-timeseries | python/sparkts/datetimeindex.py | DateTimeIndex.datetime_at_loc | def datetime_at_loc(self, loc):
"""Returns the timestamp at the given integer location as a Pandas Timestamp."""
return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc))) | python | def datetime_at_loc(self, loc):
"""Returns the timestamp at the given integer location as a Pandas Timestamp."""
return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc))) | [
"def",
"datetime_at_loc",
"(",
"self",
",",
"loc",
")",
":",
"return",
"pd",
".",
"Timestamp",
"(",
"self",
".",
"_zdt_to_nanos",
"(",
"self",
".",
"_jdt_index",
".",
"dateTimeAtLoc",
"(",
"loc",
")",
")",
")"
] | Returns the timestamp at the given integer location as a Pandas Timestamp. | [
"Returns",
"the",
"timestamp",
"at",
"the",
"given",
"integer",
"location",
"as",
"a",
"Pandas",
"Timestamp",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L37-L39 |
229,875 | sryza/spark-timeseries | python/sparkts/datetimeindex.py | DateTimeIndex.islice | def islice(self, start, end):
"""
Returns a new DateTimeIndex, containing a subslice of the timestamps in this index,
as specified by the given integer start and end locations.
Parameters
----------
start : int
The location of the start of the range, inclusive.
end : int
The location of the end of the range, exclusive.
"""
jdt_index = self._jdt_index.islice(start, end)
return DateTimeIndex(jdt_index=jdt_index) | python | def islice(self, start, end):
"""
Returns a new DateTimeIndex, containing a subslice of the timestamps in this index,
as specified by the given integer start and end locations.
Parameters
----------
start : int
The location of the start of the range, inclusive.
end : int
The location of the end of the range, exclusive.
"""
jdt_index = self._jdt_index.islice(start, end)
return DateTimeIndex(jdt_index=jdt_index) | [
"def",
"islice",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"jdt_index",
"=",
"self",
".",
"_jdt_index",
".",
"islice",
"(",
"start",
",",
"end",
")",
"return",
"DateTimeIndex",
"(",
"jdt_index",
"=",
"jdt_index",
")"
] | Returns a new DateTimeIndex, containing a subslice of the timestamps in this index,
as specified by the given integer start and end locations.
Parameters
----------
start : int
The location of the start of the range, inclusive.
end : int
The location of the end of the range, exclusive. | [
"Returns",
"a",
"new",
"DateTimeIndex",
"containing",
"a",
"subslice",
"of",
"the",
"timestamps",
"in",
"this",
"index",
"as",
"specified",
"by",
"the",
"given",
"integer",
"start",
"and",
"end",
"locations",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/datetimeindex.py#L51-L64 |
229,876 | sryza/spark-timeseries | python/sparkts/models/AutoregressionX.py | fit_model | def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None):
"""
Fit an autoregressive model with additional exogenous variables. The model predicts a value
at time t of a dependent variable, Y, as a function of previous values of Y, and a combination
of previous values of exogenous regressors X_i, and current values of exogenous regressors X_i.
This is a generalization of an AR model, which is simply an ARX with no exogenous regressors.
The fitting procedure here is the same, using least squares. Note that all lags up to the
maxlag are included. In the case of the dependent variable the max lag is 'yMaxLag', while
for the exogenous variables the max lag is 'xMaxLag', with which each column in the original
matrix provided is lagged accordingly.
Parameters
----------
y:
the dependent variable, time series as a Numpy array
x:
a matrix of exogenous variables as a Numpy array
yMaxLag:
the maximum lag order for the dependent variable
xMaxLag:
the maximum lag order for exogenous variables
includesOriginalX:
a boolean flag indicating if the non-lagged exogenous variables should
be included. Default is true
noIntercept:
a boolean flag indicating if the intercept should be dropped. Default is
false
Returns an ARXModel, which is an autoregressive model with exogenous variables.
"""
assert sc != None, "Missing SparkContext"
jvm = sc._jvm
jmodel = jvm.com.cloudera.sparkts.models.AutoregressionX.fitModel(_nparray2breezevector(sc, y.toArray()), _nparray2breezematrix(sc, x.toArray()), yMaxLag, xMaxLag, includesOriginalX, noIntercept)
return ARXModel(jmodel=jmodel, sc=sc) | python | def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None):
"""
Fit an autoregressive model with additional exogenous variables. The model predicts a value
at time t of a dependent variable, Y, as a function of previous values of Y, and a combination
of previous values of exogenous regressors X_i, and current values of exogenous regressors X_i.
This is a generalization of an AR model, which is simply an ARX with no exogenous regressors.
The fitting procedure here is the same, using least squares. Note that all lags up to the
maxlag are included. In the case of the dependent variable the max lag is 'yMaxLag', while
for the exogenous variables the max lag is 'xMaxLag', with which each column in the original
matrix provided is lagged accordingly.
Parameters
----------
y:
the dependent variable, time series as a Numpy array
x:
a matrix of exogenous variables as a Numpy array
yMaxLag:
the maximum lag order for the dependent variable
xMaxLag:
the maximum lag order for exogenous variables
includesOriginalX:
a boolean flag indicating if the non-lagged exogenous variables should
be included. Default is true
noIntercept:
a boolean flag indicating if the intercept should be dropped. Default is
false
Returns an ARXModel, which is an autoregressive model with exogenous variables.
"""
assert sc != None, "Missing SparkContext"
jvm = sc._jvm
jmodel = jvm.com.cloudera.sparkts.models.AutoregressionX.fitModel(_nparray2breezevector(sc, y.toArray()), _nparray2breezematrix(sc, x.toArray()), yMaxLag, xMaxLag, includesOriginalX, noIntercept)
return ARXModel(jmodel=jmodel, sc=sc) | [
"def",
"fit_model",
"(",
"y",
",",
"x",
",",
"yMaxLag",
",",
"xMaxLag",
",",
"includesOriginalX",
"=",
"True",
",",
"noIntercept",
"=",
"False",
",",
"sc",
"=",
"None",
")",
":",
"assert",
"sc",
"!=",
"None",
",",
"\"Missing SparkContext\"",
"jvm",
"=",
"sc",
".",
"_jvm",
"jmodel",
"=",
"jvm",
".",
"com",
".",
"cloudera",
".",
"sparkts",
".",
"models",
".",
"AutoregressionX",
".",
"fitModel",
"(",
"_nparray2breezevector",
"(",
"sc",
",",
"y",
".",
"toArray",
"(",
")",
")",
",",
"_nparray2breezematrix",
"(",
"sc",
",",
"x",
".",
"toArray",
"(",
")",
")",
",",
"yMaxLag",
",",
"xMaxLag",
",",
"includesOriginalX",
",",
"noIntercept",
")",
"return",
"ARXModel",
"(",
"jmodel",
"=",
"jmodel",
",",
"sc",
"=",
"sc",
")"
] | Fit an autoregressive model with additional exogenous variables. The model predicts a value
at time t of a dependent variable, Y, as a function of previous values of Y, and a combination
of previous values of exogenous regressors X_i, and current values of exogenous regressors X_i.
This is a generalization of an AR model, which is simply an ARX with no exogenous regressors.
The fitting procedure here is the same, using least squares. Note that all lags up to the
maxlag are included. In the case of the dependent variable the max lag is 'yMaxLag', while
for the exogenous variables the max lag is 'xMaxLag', with which each column in the original
matrix provided is lagged accordingly.
Parameters
----------
y:
the dependent variable, time series as a Numpy array
x:
a matrix of exogenous variables as a Numpy array
yMaxLag:
the maximum lag order for the dependent variable
xMaxLag:
the maximum lag order for exogenous variables
includesOriginalX:
a boolean flag indicating if the non-lagged exogenous variables should
be included. Default is true
noIntercept:
a boolean flag indicating if the intercept should be dropped. Default is
false
Returns an ARXModel, which is an autoregressive model with exogenous variables. | [
"Fit",
"an",
"autoregressive",
"model",
"with",
"additional",
"exogenous",
"variables",
".",
"The",
"model",
"predicts",
"a",
"value",
"at",
"time",
"t",
"of",
"a",
"dependent",
"variable",
"Y",
"as",
"a",
"function",
"of",
"previous",
"values",
"of",
"Y",
"and",
"a",
"combination",
"of",
"previous",
"values",
"of",
"exogenous",
"regressors",
"X_i",
"and",
"current",
"values",
"of",
"exogenous",
"regressors",
"X_i",
".",
"This",
"is",
"a",
"generalization",
"of",
"an",
"AR",
"model",
"which",
"is",
"simply",
"an",
"ARX",
"with",
"no",
"exogenous",
"regressors",
".",
"The",
"fitting",
"procedure",
"here",
"is",
"the",
"same",
"using",
"least",
"squares",
".",
"Note",
"that",
"all",
"lags",
"up",
"to",
"the",
"maxlag",
"are",
"included",
".",
"In",
"the",
"case",
"of",
"the",
"dependent",
"variable",
"the",
"max",
"lag",
"is",
"yMaxLag",
"while",
"for",
"the",
"exogenous",
"variables",
"the",
"max",
"lag",
"is",
"xMaxLag",
"with",
"which",
"each",
"column",
"in",
"the",
"original",
"matrix",
"provided",
"is",
"lagged",
"accordingly",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/models/AutoregressionX.py#L11-L45 |
229,877 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | time_series_rdd_from_pandas_series_rdd | def time_series_rdd_from_pandas_series_rdd(series_rdd):
"""
Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects.
The series in the RDD are all expected to have the same DatetimeIndex.
Parameters
----------
series_rdd : RDD of (string, pandas.Series) tuples
sc : SparkContext
"""
first = series_rdd.first()
dt_index = irregular(first[1].index, series_rdd.ctx)
return TimeSeriesRDD(dt_index, series_rdd.mapValues(lambda x: x.values)) | python | def time_series_rdd_from_pandas_series_rdd(series_rdd):
"""
Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects.
The series in the RDD are all expected to have the same DatetimeIndex.
Parameters
----------
series_rdd : RDD of (string, pandas.Series) tuples
sc : SparkContext
"""
first = series_rdd.first()
dt_index = irregular(first[1].index, series_rdd.ctx)
return TimeSeriesRDD(dt_index, series_rdd.mapValues(lambda x: x.values)) | [
"def",
"time_series_rdd_from_pandas_series_rdd",
"(",
"series_rdd",
")",
":",
"first",
"=",
"series_rdd",
".",
"first",
"(",
")",
"dt_index",
"=",
"irregular",
"(",
"first",
"[",
"1",
"]",
".",
"index",
",",
"series_rdd",
".",
"ctx",
")",
"return",
"TimeSeriesRDD",
"(",
"dt_index",
",",
"series_rdd",
".",
"mapValues",
"(",
"lambda",
"x",
":",
"x",
".",
"values",
")",
")"
] | Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects.
The series in the RDD are all expected to have the same DatetimeIndex.
Parameters
----------
series_rdd : RDD of (string, pandas.Series) tuples
sc : SparkContext | [
"Instantiates",
"a",
"TimeSeriesRDD",
"from",
"an",
"RDD",
"of",
"Pandas",
"Series",
"objects",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L201-L214 |
229,878 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | time_series_rdd_from_observations | def time_series_rdd_from_observations(dt_index, df, ts_col, key_col, val_col):
"""
Instantiates a TimeSeriesRDD from a DataFrame of observations.
An observation is a row containing a timestamp, a string key, and float value.
Parameters
----------
dt_index : DateTimeIndex
The index of the RDD to create. Observations not contained in this index will be ignored.
df : DataFrame
ts_col : string
The name of the column in the DataFrame containing the timestamps.
key_col : string
The name of the column in the DataFrame containing the keys.
val_col : string
The name of the column in the DataFrame containing the values.
"""
jvm = df._sc._jvm
jtsrdd = jvm.com.cloudera.sparkts.api.java.JavaTimeSeriesRDDFactory.timeSeriesRDDFromObservations( \
dt_index._jdt_index, df._jdf, ts_col, key_col, val_col)
return TimeSeriesRDD(None, None, jtsrdd, df._sc) | python | def time_series_rdd_from_observations(dt_index, df, ts_col, key_col, val_col):
"""
Instantiates a TimeSeriesRDD from a DataFrame of observations.
An observation is a row containing a timestamp, a string key, and float value.
Parameters
----------
dt_index : DateTimeIndex
The index of the RDD to create. Observations not contained in this index will be ignored.
df : DataFrame
ts_col : string
The name of the column in the DataFrame containing the timestamps.
key_col : string
The name of the column in the DataFrame containing the keys.
val_col : string
The name of the column in the DataFrame containing the values.
"""
jvm = df._sc._jvm
jtsrdd = jvm.com.cloudera.sparkts.api.java.JavaTimeSeriesRDDFactory.timeSeriesRDDFromObservations( \
dt_index._jdt_index, df._jdf, ts_col, key_col, val_col)
return TimeSeriesRDD(None, None, jtsrdd, df._sc) | [
"def",
"time_series_rdd_from_observations",
"(",
"dt_index",
",",
"df",
",",
"ts_col",
",",
"key_col",
",",
"val_col",
")",
":",
"jvm",
"=",
"df",
".",
"_sc",
".",
"_jvm",
"jtsrdd",
"=",
"jvm",
".",
"com",
".",
"cloudera",
".",
"sparkts",
".",
"api",
".",
"java",
".",
"JavaTimeSeriesRDDFactory",
".",
"timeSeriesRDDFromObservations",
"(",
"dt_index",
".",
"_jdt_index",
",",
"df",
".",
"_jdf",
",",
"ts_col",
",",
"key_col",
",",
"val_col",
")",
"return",
"TimeSeriesRDD",
"(",
"None",
",",
"None",
",",
"jtsrdd",
",",
"df",
".",
"_sc",
")"
] | Instantiates a TimeSeriesRDD from a DataFrame of observations.
An observation is a row containing a timestamp, a string key, and float value.
Parameters
----------
dt_index : DateTimeIndex
The index of the RDD to create. Observations not contained in this index will be ignored.
df : DataFrame
ts_col : string
The name of the column in the DataFrame containing the timestamps.
key_col : string
The name of the column in the DataFrame containing the keys.
val_col : string
The name of the column in the DataFrame containing the values. | [
"Instantiates",
"a",
"TimeSeriesRDD",
"from",
"a",
"DataFrame",
"of",
"observations",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L216-L237 |
229,879 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | TimeSeriesRDD.map_series | def map_series(self, fn, dt_index = None):
"""
Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD.
Either the series produced by the given function should conform to this TimeSeriesRDD's
index, or a new DateTimeIndex should be given that they conform to.
Parameters
----------
fn : function
A function that maps arrays of floats to arrays of floats.
dt_index : DateTimeIndex
A DateTimeIndex for the produced TimeseriesRDD.
"""
if dt_index == None:
dt_index = self.index()
return TimeSeriesRDD(dt_index, self.map(fn)) | python | def map_series(self, fn, dt_index = None):
"""
Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD.
Either the series produced by the given function should conform to this TimeSeriesRDD's
index, or a new DateTimeIndex should be given that they conform to.
Parameters
----------
fn : function
A function that maps arrays of floats to arrays of floats.
dt_index : DateTimeIndex
A DateTimeIndex for the produced TimeseriesRDD.
"""
if dt_index == None:
dt_index = self.index()
return TimeSeriesRDD(dt_index, self.map(fn)) | [
"def",
"map_series",
"(",
"self",
",",
"fn",
",",
"dt_index",
"=",
"None",
")",
":",
"if",
"dt_index",
"==",
"None",
":",
"dt_index",
"=",
"self",
".",
"index",
"(",
")",
"return",
"TimeSeriesRDD",
"(",
"dt_index",
",",
"self",
".",
"map",
"(",
"fn",
")",
")"
] | Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD.
Either the series produced by the given function should conform to this TimeSeriesRDD's
index, or a new DateTimeIndex should be given that they conform to.
Parameters
----------
fn : function
A function that maps arrays of floats to arrays of floats.
dt_index : DateTimeIndex
A DateTimeIndex for the produced TimeseriesRDD. | [
"Returns",
"a",
"TimeSeriesRDD",
"with",
"a",
"transformation",
"applied",
"to",
"all",
"the",
"series",
"in",
"this",
"RDD",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L77-L93 |
229,880 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | TimeSeriesRDD.to_instants | def to_instants(self):
"""
Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and
a numpy array containing all the observations that occurred at that time.
"""
jrdd = self._jtsrdd.toInstants(-1).map( \
self.ctx._jvm.com.cloudera.sparkts.InstantToBytes())
return RDD(jrdd, self.ctx, _InstantDeserializer()) | python | def to_instants(self):
"""
Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and
a numpy array containing all the observations that occurred at that time.
"""
jrdd = self._jtsrdd.toInstants(-1).map( \
self.ctx._jvm.com.cloudera.sparkts.InstantToBytes())
return RDD(jrdd, self.ctx, _InstantDeserializer()) | [
"def",
"to_instants",
"(",
"self",
")",
":",
"jrdd",
"=",
"self",
".",
"_jtsrdd",
".",
"toInstants",
"(",
"-",
"1",
")",
".",
"map",
"(",
"self",
".",
"ctx",
".",
"_jvm",
".",
"com",
".",
"cloudera",
".",
"sparkts",
".",
"InstantToBytes",
"(",
")",
")",
"return",
"RDD",
"(",
"jrdd",
",",
"self",
".",
"ctx",
",",
"_InstantDeserializer",
"(",
")",
")"
] | Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and
a numpy array containing all the observations that occurred at that time. | [
"Returns",
"an",
"RDD",
"of",
"instants",
"each",
"a",
"horizontal",
"slice",
"of",
"this",
"TimeSeriesRDD",
"at",
"a",
"time",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L95-L104 |
229,881 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | TimeSeriesRDD.to_instants_dataframe | def to_instants_dataframe(self, sql_ctx):
"""
Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD.
"""
ssql_ctx = sql_ctx._ssql_ctx
jdf = self._jtsrdd.toInstantsDataFrame(ssql_ctx, -1)
return DataFrame(jdf, sql_ctx) | python | def to_instants_dataframe(self, sql_ctx):
"""
Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD.
"""
ssql_ctx = sql_ctx._ssql_ctx
jdf = self._jtsrdd.toInstantsDataFrame(ssql_ctx, -1)
return DataFrame(jdf, sql_ctx) | [
"def",
"to_instants_dataframe",
"(",
"self",
",",
"sql_ctx",
")",
":",
"ssql_ctx",
"=",
"sql_ctx",
".",
"_ssql_ctx",
"jdf",
"=",
"self",
".",
"_jtsrdd",
".",
"toInstantsDataFrame",
"(",
"ssql_ctx",
",",
"-",
"1",
")",
"return",
"DataFrame",
"(",
"jdf",
",",
"sql_ctx",
")"
] | Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD. | [
"Returns",
"a",
"DataFrame",
"of",
"instants",
"each",
"a",
"horizontal",
"slice",
"of",
"this",
"TimeSeriesRDD",
"at",
"a",
"time",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L106-L115 |
229,882 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | TimeSeriesRDD.to_observations_dataframe | def to_observations_dataframe(self, sql_ctx, ts_col='timestamp', key_col='key', val_col='value'):
"""
Returns a DataFrame of observations, each containing a timestamp, a key, and a value.
Parameters
----------
sql_ctx : SQLContext
ts_col : string
The name for the timestamp column.
key_col : string
The name for the key column.
val_col : string
The name for the value column.
"""
ssql_ctx = sql_ctx._ssql_ctx
jdf = self._jtsrdd.toObservationsDataFrame(ssql_ctx, ts_col, key_col, val_col)
return DataFrame(jdf, sql_ctx) | python | def to_observations_dataframe(self, sql_ctx, ts_col='timestamp', key_col='key', val_col='value'):
"""
Returns a DataFrame of observations, each containing a timestamp, a key, and a value.
Parameters
----------
sql_ctx : SQLContext
ts_col : string
The name for the timestamp column.
key_col : string
The name for the key column.
val_col : string
The name for the value column.
"""
ssql_ctx = sql_ctx._ssql_ctx
jdf = self._jtsrdd.toObservationsDataFrame(ssql_ctx, ts_col, key_col, val_col)
return DataFrame(jdf, sql_ctx) | [
"def",
"to_observations_dataframe",
"(",
"self",
",",
"sql_ctx",
",",
"ts_col",
"=",
"'timestamp'",
",",
"key_col",
"=",
"'key'",
",",
"val_col",
"=",
"'value'",
")",
":",
"ssql_ctx",
"=",
"sql_ctx",
".",
"_ssql_ctx",
"jdf",
"=",
"self",
".",
"_jtsrdd",
".",
"toObservationsDataFrame",
"(",
"ssql_ctx",
",",
"ts_col",
",",
"key_col",
",",
"val_col",
")",
"return",
"DataFrame",
"(",
"jdf",
",",
"sql_ctx",
")"
] | Returns a DataFrame of observations, each containing a timestamp, a key, and a value.
Parameters
----------
sql_ctx : SQLContext
ts_col : string
The name for the timestamp column.
key_col : string
The name for the key column.
val_col : string
The name for the value column. | [
"Returns",
"a",
"DataFrame",
"of",
"observations",
"each",
"containing",
"a",
"timestamp",
"a",
"key",
"and",
"a",
"value",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L123-L139 |
229,883 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | TimeSeriesRDD.to_pandas_series_rdd | def to_pandas_series_rdd(self):
"""
Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes
"""
pd_index = self.index().to_pandas_index()
return self.map(lambda x: (x[0], pd.Series(x[1], pd_index))) | python | def to_pandas_series_rdd(self):
"""
Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes
"""
pd_index = self.index().to_pandas_index()
return self.map(lambda x: (x[0], pd.Series(x[1], pd_index))) | [
"def",
"to_pandas_series_rdd",
"(",
"self",
")",
":",
"pd_index",
"=",
"self",
".",
"index",
"(",
")",
".",
"to_pandas_index",
"(",
")",
"return",
"self",
".",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
"[",
"0",
"]",
",",
"pd",
".",
"Series",
"(",
"x",
"[",
"1",
"]",
",",
"pd_index",
")",
")",
")"
] | Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes | [
"Returns",
"an",
"RDD",
"of",
"Pandas",
"Series",
"objects",
"indexed",
"with",
"Pandas",
"DatetimeIndexes"
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L141-L146 |
229,884 | sryza/spark-timeseries | python/sparkts/timeseriesrdd.py | TimeSeriesRDD.to_pandas_dataframe | def to_pandas_dataframe(self):
"""
Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame.
Each record in the RDD becomes and column, and the DataFrame is indexed with a
DatetimeIndex generated from this RDD's index.
"""
pd_index = self.index().to_pandas_index()
return pd.DataFrame.from_items(self.collect()).set_index(pd_index) | python | def to_pandas_dataframe(self):
"""
Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame.
Each record in the RDD becomes and column, and the DataFrame is indexed with a
DatetimeIndex generated from this RDD's index.
"""
pd_index = self.index().to_pandas_index()
return pd.DataFrame.from_items(self.collect()).set_index(pd_index) | [
"def",
"to_pandas_dataframe",
"(",
"self",
")",
":",
"pd_index",
"=",
"self",
".",
"index",
"(",
")",
".",
"to_pandas_index",
"(",
")",
"return",
"pd",
".",
"DataFrame",
".",
"from_items",
"(",
"self",
".",
"collect",
"(",
")",
")",
".",
"set_index",
"(",
"pd_index",
")"
] | Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame.
Each record in the RDD becomes and column, and the DataFrame is indexed with a
DatetimeIndex generated from this RDD's index. | [
"Pulls",
"the",
"contents",
"of",
"the",
"RDD",
"to",
"the",
"driver",
"and",
"places",
"them",
"in",
"a",
"Pandas",
"DataFrame",
".",
"Each",
"record",
"in",
"the",
"RDD",
"becomes",
"and",
"column",
"and",
"the",
"DataFrame",
"is",
"indexed",
"with",
"a",
"DatetimeIndex",
"generated",
"from",
"this",
"RDD",
"s",
"index",
"."
] | 280aa887dc08ab114411245268f230fdabb76eec | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/timeseriesrdd.py#L148-L156 |
229,885 | google/textfsm | textfsm/texttable.py | Row._SetHeader | def _SetHeader(self, values):
"""Set the row's header from a list."""
if self._values and len(values) != len(self._values):
raise ValueError('Header values not equal to existing data width.')
if not self._values:
for _ in range(len(values)):
self._values.append(None)
self._keys = list(values)
self._BuildIndex() | python | def _SetHeader(self, values):
"""Set the row's header from a list."""
if self._values and len(values) != len(self._values):
raise ValueError('Header values not equal to existing data width.')
if not self._values:
for _ in range(len(values)):
self._values.append(None)
self._keys = list(values)
self._BuildIndex() | [
"def",
"_SetHeader",
"(",
"self",
",",
"values",
")",
":",
"if",
"self",
".",
"_values",
"and",
"len",
"(",
"values",
")",
"!=",
"len",
"(",
"self",
".",
"_values",
")",
":",
"raise",
"ValueError",
"(",
"'Header values not equal to existing data width.'",
")",
"if",
"not",
"self",
".",
"_values",
":",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"values",
")",
")",
":",
"self",
".",
"_values",
".",
"append",
"(",
"None",
")",
"self",
".",
"_keys",
"=",
"list",
"(",
"values",
")",
"self",
".",
"_BuildIndex",
"(",
")"
] | Set the row's header from a list. | [
"Set",
"the",
"row",
"s",
"header",
"from",
"a",
"list",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L190-L198 |
229,886 | google/textfsm | textfsm/texttable.py | Row._SetValues | def _SetValues(self, values):
"""Set values from supplied dictionary or list.
Args:
values: A Row, dict indexed by column name, or list.
Raises:
TypeError: Argument is not a list or dict, or list is not equal row
length or dictionary keys don't match.
"""
def _ToStr(value):
"""Convert individul list entries to string."""
if isinstance(value, (list, tuple)):
result = []
for val in value:
result.append(str(val))
return result
else:
return str(value)
# Row with identical header can be copied directly.
if isinstance(values, Row):
if self._keys != values.header:
raise TypeError('Attempt to append row with mismatched header.')
self._values = copy.deepcopy(values.values)
elif isinstance(values, dict):
for key in self._keys:
if key not in values:
raise TypeError('Dictionary key mismatch with row.')
for key in self._keys:
self[key] = _ToStr(values[key])
elif isinstance(values, list) or isinstance(values, tuple):
if len(values) != len(self._values):
raise TypeError('Supplied list length != row length')
for (index, value) in enumerate(values):
self._values[index] = _ToStr(value)
else:
raise TypeError('Supplied argument must be Row, dict or list, not %s',
type(values)) | python | def _SetValues(self, values):
"""Set values from supplied dictionary or list.
Args:
values: A Row, dict indexed by column name, or list.
Raises:
TypeError: Argument is not a list or dict, or list is not equal row
length or dictionary keys don't match.
"""
def _ToStr(value):
"""Convert individul list entries to string."""
if isinstance(value, (list, tuple)):
result = []
for val in value:
result.append(str(val))
return result
else:
return str(value)
# Row with identical header can be copied directly.
if isinstance(values, Row):
if self._keys != values.header:
raise TypeError('Attempt to append row with mismatched header.')
self._values = copy.deepcopy(values.values)
elif isinstance(values, dict):
for key in self._keys:
if key not in values:
raise TypeError('Dictionary key mismatch with row.')
for key in self._keys:
self[key] = _ToStr(values[key])
elif isinstance(values, list) or isinstance(values, tuple):
if len(values) != len(self._values):
raise TypeError('Supplied list length != row length')
for (index, value) in enumerate(values):
self._values[index] = _ToStr(value)
else:
raise TypeError('Supplied argument must be Row, dict or list, not %s',
type(values)) | [
"def",
"_SetValues",
"(",
"self",
",",
"values",
")",
":",
"def",
"_ToStr",
"(",
"value",
")",
":",
"\"\"\"Convert individul list entries to string.\"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"result",
"=",
"[",
"]",
"for",
"val",
"in",
"value",
":",
"result",
".",
"append",
"(",
"str",
"(",
"val",
")",
")",
"return",
"result",
"else",
":",
"return",
"str",
"(",
"value",
")",
"# Row with identical header can be copied directly.",
"if",
"isinstance",
"(",
"values",
",",
"Row",
")",
":",
"if",
"self",
".",
"_keys",
"!=",
"values",
".",
"header",
":",
"raise",
"TypeError",
"(",
"'Attempt to append row with mismatched header.'",
")",
"self",
".",
"_values",
"=",
"copy",
".",
"deepcopy",
"(",
"values",
".",
"values",
")",
"elif",
"isinstance",
"(",
"values",
",",
"dict",
")",
":",
"for",
"key",
"in",
"self",
".",
"_keys",
":",
"if",
"key",
"not",
"in",
"values",
":",
"raise",
"TypeError",
"(",
"'Dictionary key mismatch with row.'",
")",
"for",
"key",
"in",
"self",
".",
"_keys",
":",
"self",
"[",
"key",
"]",
"=",
"_ToStr",
"(",
"values",
"[",
"key",
"]",
")",
"elif",
"isinstance",
"(",
"values",
",",
"list",
")",
"or",
"isinstance",
"(",
"values",
",",
"tuple",
")",
":",
"if",
"len",
"(",
"values",
")",
"!=",
"len",
"(",
"self",
".",
"_values",
")",
":",
"raise",
"TypeError",
"(",
"'Supplied list length != row length'",
")",
"for",
"(",
"index",
",",
"value",
")",
"in",
"enumerate",
"(",
"values",
")",
":",
"self",
".",
"_values",
"[",
"index",
"]",
"=",
"_ToStr",
"(",
"value",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Supplied argument must be Row, dict or list, not %s'",
",",
"type",
"(",
"values",
")",
")"
] | Set values from supplied dictionary or list.
Args:
values: A Row, dict indexed by column name, or list.
Raises:
TypeError: Argument is not a list or dict, or list is not equal row
length or dictionary keys don't match. | [
"Set",
"values",
"from",
"supplied",
"dictionary",
"or",
"list",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L222-L264 |
229,887 | google/textfsm | textfsm/texttable.py | TextTable.Filter | def Filter(self, function=None):
"""Construct Textable from the rows of which the function returns true.
Args:
function: A function applied to each row which returns a bool. If
function is None, all rows with empty column values are
removed.
Returns:
A new TextTable()
Raises:
TableError: When an invalid row entry is Append()'d
"""
flat = lambda x: x if isinstance(x, str) else ''.join([flat(y) for y in x])
if function is None:
function = lambda row: bool(flat(row.values))
new_table = self.__class__()
# pylint: disable=protected-access
new_table._table = [self.header]
for row in self:
if function(row) is True:
new_table.Append(row)
return new_table | python | def Filter(self, function=None):
"""Construct Textable from the rows of which the function returns true.
Args:
function: A function applied to each row which returns a bool. If
function is None, all rows with empty column values are
removed.
Returns:
A new TextTable()
Raises:
TableError: When an invalid row entry is Append()'d
"""
flat = lambda x: x if isinstance(x, str) else ''.join([flat(y) for y in x])
if function is None:
function = lambda row: bool(flat(row.values))
new_table = self.__class__()
# pylint: disable=protected-access
new_table._table = [self.header]
for row in self:
if function(row) is True:
new_table.Append(row)
return new_table | [
"def",
"Filter",
"(",
"self",
",",
"function",
"=",
"None",
")",
":",
"flat",
"=",
"lambda",
"x",
":",
"x",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
"else",
"''",
".",
"join",
"(",
"[",
"flat",
"(",
"y",
")",
"for",
"y",
"in",
"x",
"]",
")",
"if",
"function",
"is",
"None",
":",
"function",
"=",
"lambda",
"row",
":",
"bool",
"(",
"flat",
"(",
"row",
".",
"values",
")",
")",
"new_table",
"=",
"self",
".",
"__class__",
"(",
")",
"# pylint: disable=protected-access",
"new_table",
".",
"_table",
"=",
"[",
"self",
".",
"header",
"]",
"for",
"row",
"in",
"self",
":",
"if",
"function",
"(",
"row",
")",
"is",
"True",
":",
"new_table",
".",
"Append",
"(",
"row",
")",
"return",
"new_table"
] | Construct Textable from the rows of which the function returns true.
Args:
function: A function applied to each row which returns a bool. If
function is None, all rows with empty column values are
removed.
Returns:
A new TextTable()
Raises:
TableError: When an invalid row entry is Append()'d | [
"Construct",
"Textable",
"from",
"the",
"rows",
"of",
"which",
"the",
"function",
"returns",
"true",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L378-L402 |
229,888 | google/textfsm | textfsm/texttable.py | TextTable._GetTable | def _GetTable(self):
"""Returns table, with column headers and separators.
Returns:
The whole table including headers as a string. Each row is
joined by a newline and each entry by self.separator.
"""
result = []
# Avoid the global lookup cost on each iteration.
lstr = str
for row in self._table:
result.append(
'%s\n' %
self.separator.join(lstr(v) for v in row))
return ''.join(result) | python | def _GetTable(self):
"""Returns table, with column headers and separators.
Returns:
The whole table including headers as a string. Each row is
joined by a newline and each entry by self.separator.
"""
result = []
# Avoid the global lookup cost on each iteration.
lstr = str
for row in self._table:
result.append(
'%s\n' %
self.separator.join(lstr(v) for v in row))
return ''.join(result) | [
"def",
"_GetTable",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"# Avoid the global lookup cost on each iteration.",
"lstr",
"=",
"str",
"for",
"row",
"in",
"self",
".",
"_table",
":",
"result",
".",
"append",
"(",
"'%s\\n'",
"%",
"self",
".",
"separator",
".",
"join",
"(",
"lstr",
"(",
"v",
")",
"for",
"v",
"in",
"row",
")",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Returns table, with column headers and separators.
Returns:
The whole table including headers as a string. Each row is
joined by a newline and each entry by self.separator. | [
"Returns",
"table",
"with",
"column",
"headers",
"and",
"separators",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L595-L610 |
229,889 | google/textfsm | textfsm/texttable.py | TextTable._SetTable | def _SetTable(self, table):
"""Sets table, with column headers and separators."""
if not isinstance(table, TextTable):
raise TypeError('Not an instance of TextTable.')
self.Reset()
self._table = copy.deepcopy(table._table) # pylint: disable=W0212
# Point parent table of each row back ourselves.
for row in self:
row.table = self | python | def _SetTable(self, table):
"""Sets table, with column headers and separators."""
if not isinstance(table, TextTable):
raise TypeError('Not an instance of TextTable.')
self.Reset()
self._table = copy.deepcopy(table._table) # pylint: disable=W0212
# Point parent table of each row back ourselves.
for row in self:
row.table = self | [
"def",
"_SetTable",
"(",
"self",
",",
"table",
")",
":",
"if",
"not",
"isinstance",
"(",
"table",
",",
"TextTable",
")",
":",
"raise",
"TypeError",
"(",
"'Not an instance of TextTable.'",
")",
"self",
".",
"Reset",
"(",
")",
"self",
".",
"_table",
"=",
"copy",
".",
"deepcopy",
"(",
"table",
".",
"_table",
")",
"# pylint: disable=W0212",
"# Point parent table of each row back ourselves.",
"for",
"row",
"in",
"self",
":",
"row",
".",
"table",
"=",
"self"
] | Sets table, with column headers and separators. | [
"Sets",
"table",
"with",
"column",
"headers",
"and",
"separators",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L612-L620 |
229,890 | google/textfsm | textfsm/texttable.py | TextTable._TextJustify | def _TextJustify(self, text, col_size):
"""Formats text within column with white space padding.
A single space is prefixed, and a number of spaces are added as a
suffix such that the length of the resultant string equals the col_size.
If the length of the text exceeds the column width available then it
is split into words and returned as a list of string, each string
contains one or more words padded to the column size.
Args:
text: String of text to format.
col_size: integer size of column to pad out the text to.
Returns:
List of strings col_size in length.
Raises:
TableError: If col_size is too small to fit the words in the text.
"""
result = []
if '\n' in text:
for paragraph in text.split('\n'):
result.extend(self._TextJustify(paragraph, col_size))
return result
wrapper = textwrap.TextWrapper(width=col_size-2, break_long_words=False,
expand_tabs=False)
try:
text_list = wrapper.wrap(text)
except ValueError:
raise TableError('Field too small (minimum width: 3)')
if not text_list:
return [' '*col_size]
for current_line in text_list:
stripped_len = len(terminal.StripAnsiText(current_line))
ansi_color_adds = len(current_line) - stripped_len
# +2 for white space on either side.
if stripped_len + 2 > col_size:
raise TableError('String contains words that do not fit in column.')
result.append(' %-*s' % (col_size - 1 + ansi_color_adds, current_line))
return result | python | def _TextJustify(self, text, col_size):
"""Formats text within column with white space padding.
A single space is prefixed, and a number of spaces are added as a
suffix such that the length of the resultant string equals the col_size.
If the length of the text exceeds the column width available then it
is split into words and returned as a list of string, each string
contains one or more words padded to the column size.
Args:
text: String of text to format.
col_size: integer size of column to pad out the text to.
Returns:
List of strings col_size in length.
Raises:
TableError: If col_size is too small to fit the words in the text.
"""
result = []
if '\n' in text:
for paragraph in text.split('\n'):
result.extend(self._TextJustify(paragraph, col_size))
return result
wrapper = textwrap.TextWrapper(width=col_size-2, break_long_words=False,
expand_tabs=False)
try:
text_list = wrapper.wrap(text)
except ValueError:
raise TableError('Field too small (minimum width: 3)')
if not text_list:
return [' '*col_size]
for current_line in text_list:
stripped_len = len(terminal.StripAnsiText(current_line))
ansi_color_adds = len(current_line) - stripped_len
# +2 for white space on either side.
if stripped_len + 2 > col_size:
raise TableError('String contains words that do not fit in column.')
result.append(' %-*s' % (col_size - 1 + ansi_color_adds, current_line))
return result | [
"def",
"_TextJustify",
"(",
"self",
",",
"text",
",",
"col_size",
")",
":",
"result",
"=",
"[",
"]",
"if",
"'\\n'",
"in",
"text",
":",
"for",
"paragraph",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
":",
"result",
".",
"extend",
"(",
"self",
".",
"_TextJustify",
"(",
"paragraph",
",",
"col_size",
")",
")",
"return",
"result",
"wrapper",
"=",
"textwrap",
".",
"TextWrapper",
"(",
"width",
"=",
"col_size",
"-",
"2",
",",
"break_long_words",
"=",
"False",
",",
"expand_tabs",
"=",
"False",
")",
"try",
":",
"text_list",
"=",
"wrapper",
".",
"wrap",
"(",
"text",
")",
"except",
"ValueError",
":",
"raise",
"TableError",
"(",
"'Field too small (minimum width: 3)'",
")",
"if",
"not",
"text_list",
":",
"return",
"[",
"' '",
"*",
"col_size",
"]",
"for",
"current_line",
"in",
"text_list",
":",
"stripped_len",
"=",
"len",
"(",
"terminal",
".",
"StripAnsiText",
"(",
"current_line",
")",
")",
"ansi_color_adds",
"=",
"len",
"(",
"current_line",
")",
"-",
"stripped_len",
"# +2 for white space on either side.",
"if",
"stripped_len",
"+",
"2",
">",
"col_size",
":",
"raise",
"TableError",
"(",
"'String contains words that do not fit in column.'",
")",
"result",
".",
"append",
"(",
"' %-*s'",
"%",
"(",
"col_size",
"-",
"1",
"+",
"ansi_color_adds",
",",
"current_line",
")",
")",
"return",
"result"
] | Formats text within column with white space padding.
A single space is prefixed, and a number of spaces are added as a
suffix such that the length of the resultant string equals the col_size.
If the length of the text exceeds the column width available then it
is split into words and returned as a list of string, each string
contains one or more words padded to the column size.
Args:
text: String of text to format.
col_size: integer size of column to pad out the text to.
Returns:
List of strings col_size in length.
Raises:
TableError: If col_size is too small to fit the words in the text. | [
"Formats",
"text",
"within",
"column",
"with",
"white",
"space",
"padding",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L639-L684 |
229,891 | google/textfsm | textfsm/texttable.py | TextTable.index | def index(self, name=None): # pylint: disable=C6409
"""Returns index number of supplied column name.
Args:
name: string of column name.
Raises:
TableError: If name not found.
Returns:
Index of the specified header entry.
"""
try:
return self.header.index(name)
except ValueError:
raise TableError('Unknown index name %s.' % name) | python | def index(self, name=None): # pylint: disable=C6409
"""Returns index number of supplied column name.
Args:
name: string of column name.
Raises:
TableError: If name not found.
Returns:
Index of the specified header entry.
"""
try:
return self.header.index(name)
except ValueError:
raise TableError('Unknown index name %s.' % name) | [
"def",
"index",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable=C6409",
"try",
":",
"return",
"self",
".",
"header",
".",
"index",
"(",
"name",
")",
"except",
"ValueError",
":",
"raise",
"TableError",
"(",
"'Unknown index name %s.'",
"%",
"name",
")"
] | Returns index number of supplied column name.
Args:
name: string of column name.
Raises:
TableError: If name not found.
Returns:
Index of the specified header entry. | [
"Returns",
"index",
"number",
"of",
"supplied",
"column",
"name",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/texttable.py#L1074-L1089 |
229,892 | google/textfsm | textfsm/clitable.py | CliTable._ParseCmdItem | def _ParseCmdItem(self, cmd_input, template_file=None):
"""Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template was not found for the given command.
"""
# Build FSM machine from the template.
fsm = textfsm.TextFSM(template_file)
if not self._keys:
self._keys = set(fsm.GetValuesByAttrib('Key'))
# Pass raw data through FSM.
table = texttable.TextTable()
table.header = fsm.header
# Fill TextTable from record entries.
for record in fsm.ParseText(cmd_input):
table.Append(record)
return table | python | def _ParseCmdItem(self, cmd_input, template_file=None):
"""Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template was not found for the given command.
"""
# Build FSM machine from the template.
fsm = textfsm.TextFSM(template_file)
if not self._keys:
self._keys = set(fsm.GetValuesByAttrib('Key'))
# Pass raw data through FSM.
table = texttable.TextTable()
table.header = fsm.header
# Fill TextTable from record entries.
for record in fsm.ParseText(cmd_input):
table.Append(record)
return table | [
"def",
"_ParseCmdItem",
"(",
"self",
",",
"cmd_input",
",",
"template_file",
"=",
"None",
")",
":",
"# Build FSM machine from the template.",
"fsm",
"=",
"textfsm",
".",
"TextFSM",
"(",
"template_file",
")",
"if",
"not",
"self",
".",
"_keys",
":",
"self",
".",
"_keys",
"=",
"set",
"(",
"fsm",
".",
"GetValuesByAttrib",
"(",
"'Key'",
")",
")",
"# Pass raw data through FSM.",
"table",
"=",
"texttable",
".",
"TextTable",
"(",
")",
"table",
".",
"header",
"=",
"fsm",
".",
"header",
"# Fill TextTable from record entries.",
"for",
"record",
"in",
"fsm",
".",
"ParseText",
"(",
"cmd_input",
")",
":",
"table",
".",
"Append",
"(",
"record",
")",
"return",
"table"
] | Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template was not found for the given command. | [
"Creates",
"Texttable",
"with",
"output",
"of",
"command",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/clitable.py#L288-L313 |
229,893 | google/textfsm | textfsm/clitable.py | CliTable._Completion | def _Completion(self, match):
# pylint: disable=C6114
r"""Replaces double square brackets with variable length completion.
Completion cannot be mixed with regexp matching or '\' characters
i.e. '[[(\n)]] would become (\(n)?)?.'
Args:
match: A regex Match() object.
Returns:
String of the format '(a(b(c(d)?)?)?)?'.
"""
# Strip the outer '[[' & ']]' and replace with ()? regexp pattern.
word = str(match.group())[2:-2]
return '(' + ('(').join(word) + ')?' * len(word) | python | def _Completion(self, match):
# pylint: disable=C6114
r"""Replaces double square brackets with variable length completion.
Completion cannot be mixed with regexp matching or '\' characters
i.e. '[[(\n)]] would become (\(n)?)?.'
Args:
match: A regex Match() object.
Returns:
String of the format '(a(b(c(d)?)?)?)?'.
"""
# Strip the outer '[[' & ']]' and replace with ()? regexp pattern.
word = str(match.group())[2:-2]
return '(' + ('(').join(word) + ')?' * len(word) | [
"def",
"_Completion",
"(",
"self",
",",
"match",
")",
":",
"# pylint: disable=C6114",
"# Strip the outer '[[' & ']]' and replace with ()? regexp pattern.",
"word",
"=",
"str",
"(",
"match",
".",
"group",
"(",
")",
")",
"[",
"2",
":",
"-",
"2",
"]",
"return",
"'('",
"+",
"(",
"'('",
")",
".",
"join",
"(",
"word",
")",
"+",
"')?'",
"*",
"len",
"(",
"word",
")"
] | r"""Replaces double square brackets with variable length completion.
Completion cannot be mixed with regexp matching or '\' characters
i.e. '[[(\n)]] would become (\(n)?)?.'
Args:
match: A regex Match() object.
Returns:
String of the format '(a(b(c(d)?)?)?)?'. | [
"r",
"Replaces",
"double",
"square",
"brackets",
"with",
"variable",
"length",
"completion",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/clitable.py#L329-L344 |
229,894 | google/textfsm | textfsm/parser.py | main | def main(argv=None):
"""Validate text parsed with FSM or validate an FSM via command line."""
if argv is None:
argv = sys.argv
try:
opts, args = getopt.getopt(argv[1:], 'h', ['help'])
except getopt.error as msg:
raise Usage(msg)
for opt, _ in opts:
if opt in ('-h', '--help'):
print(__doc__)
print(help_msg)
return 0
if not args or len(args) > 4:
raise Usage('Invalid arguments.')
# If we have an argument, parse content of file and display as a template.
# Template displayed will match input template, minus any comment lines.
with open(args[0], 'r') as template:
fsm = TextFSM(template)
print('FSM Template:\n%s\n' % fsm)
if len(args) > 1:
# Second argument is file with example cli input.
# Prints parsed tabular result.
with open(args[1], 'r') as f:
cli_input = f.read()
table = fsm.ParseText(cli_input)
print('FSM Table:')
result = str(fsm.header) + '\n'
for line in table:
result += str(line) + '\n'
print(result, end='')
if len(args) > 2:
# Compare tabular result with data in third file argument.
# Exit value indicates if processed data matched expected result.
with open(args[2], 'r') as f:
ref_table = f.read()
if ref_table != result:
print('Data mis-match!')
return 1
else:
print('Data match!') | python | def main(argv=None):
"""Validate text parsed with FSM or validate an FSM via command line."""
if argv is None:
argv = sys.argv
try:
opts, args = getopt.getopt(argv[1:], 'h', ['help'])
except getopt.error as msg:
raise Usage(msg)
for opt, _ in opts:
if opt in ('-h', '--help'):
print(__doc__)
print(help_msg)
return 0
if not args or len(args) > 4:
raise Usage('Invalid arguments.')
# If we have an argument, parse content of file and display as a template.
# Template displayed will match input template, minus any comment lines.
with open(args[0], 'r') as template:
fsm = TextFSM(template)
print('FSM Template:\n%s\n' % fsm)
if len(args) > 1:
# Second argument is file with example cli input.
# Prints parsed tabular result.
with open(args[1], 'r') as f:
cli_input = f.read()
table = fsm.ParseText(cli_input)
print('FSM Table:')
result = str(fsm.header) + '\n'
for line in table:
result += str(line) + '\n'
print(result, end='')
if len(args) > 2:
# Compare tabular result with data in third file argument.
# Exit value indicates if processed data matched expected result.
with open(args[2], 'r') as f:
ref_table = f.read()
if ref_table != result:
print('Data mis-match!')
return 1
else:
print('Data match!') | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"argv",
"[",
"1",
":",
"]",
",",
"'h'",
",",
"[",
"'help'",
"]",
")",
"except",
"getopt",
".",
"error",
"as",
"msg",
":",
"raise",
"Usage",
"(",
"msg",
")",
"for",
"opt",
",",
"_",
"in",
"opts",
":",
"if",
"opt",
"in",
"(",
"'-h'",
",",
"'--help'",
")",
":",
"print",
"(",
"__doc__",
")",
"print",
"(",
"help_msg",
")",
"return",
"0",
"if",
"not",
"args",
"or",
"len",
"(",
"args",
")",
">",
"4",
":",
"raise",
"Usage",
"(",
"'Invalid arguments.'",
")",
"# If we have an argument, parse content of file and display as a template.",
"# Template displayed will match input template, minus any comment lines.",
"with",
"open",
"(",
"args",
"[",
"0",
"]",
",",
"'r'",
")",
"as",
"template",
":",
"fsm",
"=",
"TextFSM",
"(",
"template",
")",
"print",
"(",
"'FSM Template:\\n%s\\n'",
"%",
"fsm",
")",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"# Second argument is file with example cli input.",
"# Prints parsed tabular result.",
"with",
"open",
"(",
"args",
"[",
"1",
"]",
",",
"'r'",
")",
"as",
"f",
":",
"cli_input",
"=",
"f",
".",
"read",
"(",
")",
"table",
"=",
"fsm",
".",
"ParseText",
"(",
"cli_input",
")",
"print",
"(",
"'FSM Table:'",
")",
"result",
"=",
"str",
"(",
"fsm",
".",
"header",
")",
"+",
"'\\n'",
"for",
"line",
"in",
"table",
":",
"result",
"+=",
"str",
"(",
"line",
")",
"+",
"'\\n'",
"print",
"(",
"result",
",",
"end",
"=",
"''",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"# Compare tabular result with data in third file argument.",
"# Exit value indicates if processed data matched expected result.",
"with",
"open",
"(",
"args",
"[",
"2",
"]",
",",
"'r'",
")",
"as",
"f",
":",
"ref_table",
"=",
"f",
".",
"read",
"(",
")",
"if",
"ref_table",
"!=",
"result",
":",
"print",
"(",
"'Data mis-match!'",
")",
"return",
"1",
"else",
":",
"print",
"(",
"'Data match!'",
")"
] | Validate text parsed with FSM or validate an FSM via command line. | [
"Validate",
"text",
"parsed",
"with",
"FSM",
"or",
"validate",
"an",
"FSM",
"via",
"command",
"line",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L1044-L1093 |
229,895 | google/textfsm | textfsm/parser.py | TextFSMOptions.ValidOptions | def ValidOptions(cls):
"""Returns a list of valid option names."""
valid_options = []
for obj_name in dir(cls):
obj = getattr(cls, obj_name)
if inspect.isclass(obj) and issubclass(obj, cls.OptionBase):
valid_options.append(obj_name)
return valid_options | python | def ValidOptions(cls):
"""Returns a list of valid option names."""
valid_options = []
for obj_name in dir(cls):
obj = getattr(cls, obj_name)
if inspect.isclass(obj) and issubclass(obj, cls.OptionBase):
valid_options.append(obj_name)
return valid_options | [
"def",
"ValidOptions",
"(",
"cls",
")",
":",
"valid_options",
"=",
"[",
"]",
"for",
"obj_name",
"in",
"dir",
"(",
"cls",
")",
":",
"obj",
"=",
"getattr",
"(",
"cls",
",",
"obj_name",
")",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
"and",
"issubclass",
"(",
"obj",
",",
"cls",
".",
"OptionBase",
")",
":",
"valid_options",
".",
"append",
"(",
"obj_name",
")",
"return",
"valid_options"
] | Returns a list of valid option names. | [
"Returns",
"a",
"list",
"of",
"valid",
"option",
"names",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L114-L121 |
229,896 | google/textfsm | textfsm/parser.py | TextFSMValue.Header | def Header(self):
"""Fetch the header name of this Value."""
# Call OnGetValue on options.
_ = [option.OnGetValue() for option in self.options]
return self.name | python | def Header(self):
"""Fetch the header name of this Value."""
# Call OnGetValue on options.
_ = [option.OnGetValue() for option in self.options]
return self.name | [
"def",
"Header",
"(",
"self",
")",
":",
"# Call OnGetValue on options.",
"_",
"=",
"[",
"option",
".",
"OnGetValue",
"(",
")",
"for",
"option",
"in",
"self",
".",
"options",
"]",
"return",
"self",
".",
"name"
] | Fetch the header name of this Value. | [
"Fetch",
"the",
"header",
"name",
"of",
"this",
"Value",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L262-L266 |
229,897 | google/textfsm | textfsm/parser.py | TextFSMValue._AddOption | def _AddOption(self, name):
"""Add an option to this Value.
Args:
name: (str), the name of the Option to add.
Raises:
TextFSMTemplateError: If option is already present or
the option does not exist.
"""
# Check for duplicate option declaration
if name in [option.name for option in self.options]:
raise TextFSMTemplateError('Duplicate option "%s"' % name)
# Create the option object
try:
option = self._options_cls.GetOption(name)(self)
except AttributeError:
raise TextFSMTemplateError('Unknown option "%s"' % name)
self.options.append(option) | python | def _AddOption(self, name):
"""Add an option to this Value.
Args:
name: (str), the name of the Option to add.
Raises:
TextFSMTemplateError: If option is already present or
the option does not exist.
"""
# Check for duplicate option declaration
if name in [option.name for option in self.options]:
raise TextFSMTemplateError('Duplicate option "%s"' % name)
# Create the option object
try:
option = self._options_cls.GetOption(name)(self)
except AttributeError:
raise TextFSMTemplateError('Unknown option "%s"' % name)
self.options.append(option) | [
"def",
"_AddOption",
"(",
"self",
",",
"name",
")",
":",
"# Check for duplicate option declaration",
"if",
"name",
"in",
"[",
"option",
".",
"name",
"for",
"option",
"in",
"self",
".",
"options",
"]",
":",
"raise",
"TextFSMTemplateError",
"(",
"'Duplicate option \"%s\"'",
"%",
"name",
")",
"# Create the option object",
"try",
":",
"option",
"=",
"self",
".",
"_options_cls",
".",
"GetOption",
"(",
"name",
")",
"(",
"self",
")",
"except",
"AttributeError",
":",
"raise",
"TextFSMTemplateError",
"(",
"'Unknown option \"%s\"'",
"%",
"name",
")",
"self",
".",
"options",
".",
"append",
"(",
"option",
")"
] | Add an option to this Value.
Args:
name: (str), the name of the Option to add.
Raises:
TextFSMTemplateError: If option is already present or
the option does not exist. | [
"Add",
"an",
"option",
"to",
"this",
"Value",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L321-L342 |
229,898 | google/textfsm | textfsm/parser.py | TextFSM.Reset | def Reset(self):
"""Preserves FSM but resets starting state and current record."""
# Current state is Start state.
self._cur_state = self.states['Start']
self._cur_state_name = 'Start'
# Clear table of results and current record.
self._result = []
self._ClearAllRecord() | python | def Reset(self):
"""Preserves FSM but resets starting state and current record."""
# Current state is Start state.
self._cur_state = self.states['Start']
self._cur_state_name = 'Start'
# Clear table of results and current record.
self._result = []
self._ClearAllRecord() | [
"def",
"Reset",
"(",
"self",
")",
":",
"# Current state is Start state.",
"self",
".",
"_cur_state",
"=",
"self",
".",
"states",
"[",
"'Start'",
"]",
"self",
".",
"_cur_state_name",
"=",
"'Start'",
"# Clear table of results and current record.",
"self",
".",
"_result",
"=",
"[",
"]",
"self",
".",
"_ClearAllRecord",
"(",
")"
] | Preserves FSM but resets starting state and current record. | [
"Preserves",
"FSM",
"but",
"resets",
"starting",
"state",
"and",
"current",
"record",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L596-L605 |
229,899 | google/textfsm | textfsm/parser.py | TextFSM._GetHeader | def _GetHeader(self):
"""Returns header."""
header = []
for value in self.values:
try:
header.append(value.Header())
except SkipValue:
continue
return header | python | def _GetHeader(self):
"""Returns header."""
header = []
for value in self.values:
try:
header.append(value.Header())
except SkipValue:
continue
return header | [
"def",
"_GetHeader",
"(",
"self",
")",
":",
"header",
"=",
"[",
"]",
"for",
"value",
"in",
"self",
".",
"values",
":",
"try",
":",
"header",
".",
"append",
"(",
"value",
".",
"Header",
"(",
")",
")",
"except",
"SkipValue",
":",
"continue",
"return",
"header"
] | Returns header. | [
"Returns",
"header",
"."
] | 63a2aaece33e07947aa80963dca99b893964633b | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L612-L620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.