_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q225100 | JSONRenderer.extract_relation_instance | train | def extract_relation_instance(cls, field_name, field, resource_instance, serializer):
"""
Determines what instance represents given relation and extracts it.
Relation instance is determined by given field_name or source configured on
field. As fallback is a serializer method called with... | python | {
"resource": ""
} |
q225101 | JSONRenderer.extract_meta | train | def extract_meta(cls, serializer, resource):
"""
Gathers the data from serializer fields specified in meta_fields and adds it to
the meta object.
"""
if hasattr(serializer, 'child'):
meta = getattr(serializer.child, 'Meta', None)
else:
meta = getat... | python | {
"resource": ""
} |
q225102 | JSONRenderer.extract_root_meta | train | def extract_root_meta(cls, serializer, resource):
"""
Calls a `get_root_meta` function on a serializer, if it exists.
"""
many = False
if hasattr(serializer, 'child'):
many = True
serializer = serializer.child
data = {}
if getattr(serializ... | python | {
"resource": ""
} |
q225103 | PrefetchForIncludesHelperMixin.get_queryset | train | def get_queryset(self):
"""
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is ... | python | {
"resource": ""
} |
q225104 | AutoPrefetchMixin.get_queryset | train | def get_queryset(self, *args, **kwargs):
""" This mixin adds automatic prefetching for OneToOne and ManyToMany fields. """
qs = super(AutoPrefetchMixin, self).get_queryset(*args, **kwargs)
included_resources = get_included_resources(self.request)
for included in included_resources:
... | python | {
"resource": ""
} |
q225105 | RelationshipView.get_url | train | def get_url(self, name, view_name, kwargs, request):
"""
Given a name, view name and kwargs, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
... | python | {
"resource": ""
} |
q225106 | get_resource_name | train | def get_resource_name(context, expand_polymorphic_types=False):
"""
Return the name of a resource.
"""
from rest_framework_json_api.serializers import PolymorphicModelSerializer
view = context.get('view')
# Sanity check to make sure we have a view.
if not view:
return None
# Ch... | python | {
"resource": ""
} |
q225107 | format_field_names | train | def format_field_names(obj, format_type=None):
"""
Takes a dict and returns it with formatted keys as set in `format_type`
or `JSON_API_FORMAT_FIELD_NAMES`
:format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore'
"""
if format_type is None:
format_type = json_api_setti... | python | {
"resource": ""
} |
q225108 | _format_object | train | def _format_object(obj, format_type=None):
"""Depending on settings calls either `format_keys` or `format_field_names`"""
if json_api_settings.FORMAT_KEYS is not None:
return format_keys(obj, format_type)
return format_field_names(obj, format_type) | python | {
"resource": ""
} |
q225109 | get_included_resources | train | def get_included_resources(request, serializer=None):
""" Build a list of included resources. """
include_resources_param = request.query_params.get('include') if request else None
if include_resources_param:
return include_resources_param.split(',')
else:
return get_default_included_res... | python | {
"resource": ""
} |
q225110 | JSONParser.parse | train | def parse(self, stream, media_type=None, parser_context=None):
"""
Parses the incoming bytestream as JSON and returns the resulting data
"""
result = super(JSONParser, self).parse(
stream, media_type=media_type, parser_context=parser_context
)
if not isinstan... | python | {
"resource": ""
} |
q225111 | ResourceRelatedField.get_resource_type_from_included_serializer | train | def get_resource_type_from_included_serializer(self):
"""
Check to see it this resource has a different resource_name when
included and return that name, or None
"""
field_name = self.field_name or self.parent.field_name
parent = self.get_parent_serializer()
if p... | python | {
"resource": ""
} |
q225112 | sign_plaintext | train | def sign_plaintext(client_secret, resource_owner_secret):
"""Sign a request using plaintext.
Per `section 3.4.4`_ of the spec.
The "PLAINTEXT" method does not employ a signature algorithm. It
MUST be used with a transport-layer mechanism such as TLS or SSL (or
sent over a secure channel with equi... | python | {
"resource": ""
} |
q225113 | verify_hmac_sha1 | train | def verify_hmac_sha1(request, client_secret=None,
resource_owner_secret=None):
"""Verify a HMAC-SHA1 signature.
Per `section 3.4`_ of the spec.
.. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri
... | python | {
"resource": ""
} |
q225114 | verify_plaintext | train | def verify_plaintext(request, client_secret=None, resource_owner_secret=None):
"""Verify a PLAINTEXT signature.
Per `section 3.4`_ of the spec.
.. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
"""
signature = sign_plaintext(client_secret, resource_owner_secret)
match = safe_s... | python | {
"resource": ""
} |
q225115 | AuthorizationEndpoint.create_authorization_response | train | def create_authorization_response(self, uri, http_method='GET', body=None,
headers=None, realms=None, credentials=None):
"""Create an authorization response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_metho... | python | {
"resource": ""
} |
q225116 | AuthorizationEndpoint.get_realms_and_credentials | train | def get_realms_and_credentials(self, uri, http_method='GET', body=None,
headers=None):
"""Fetch realms and credentials for the presented request token.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, H... | python | {
"resource": ""
} |
q225117 | IntrospectEndpoint.create_introspect_response | train | def create_introspect_response(self, uri, http_method='POST', body=None,
headers=None):
"""Create introspect valid or invalid response
If the authorization server is unable to determine the state
of the token without additional information, it SHOULD return
... | python | {
"resource": ""
} |
q225118 | ServiceApplicationClient.prepare_request_body | train | def prepare_request_body(self,
private_key=None,
subject=None,
issuer=None,
audience=None,
expires_at=None,
issued_at=None,
... | python | {
"resource": ""
} |
q225119 | AuthorizationCodeGrant.create_authorization_code | train | def create_authorization_code(self, request):
"""
Generates an authorization grant represented as a dictionary.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
grant = {'code': common.generate_token()}
if hasattr(request, 'state') and... | python | {
"resource": ""
} |
q225120 | AuthorizationCodeGrant.create_token_response | train | def create_token_response(self, request, token_handler):
"""Validate the authorization code.
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) a... | python | {
"resource": ""
} |
q225121 | AuthorizationCodeGrant.validate_authorization_request | train | def validate_authorization_request(self, request):
"""Check the authorization request for normal and fatal errors.
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 i... | python | {
"resource": ""
} |
q225122 | MetadataEndpoint.create_metadata_response | train | def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
"""Create metadata response
"""
headers = {
'Content-Type': 'application/json'
}
return headers, json.dumps(self.claims), 200 | python | {
"resource": ""
} |
q225123 | MetadataEndpoint.validate_metadata_token | train | def validate_metadata_token(self, claims, endpoint):
"""
If the token endpoint is used in the grant type, the value of this
parameter MUST be the same as the value of the "grant_type"
parameter passed to the token endpoint defined in the grant type
definition.
"""
... | python | {
"resource": ""
} |
q225124 | WebApplicationClient.prepare_request_body | train | def prepare_request_body(self, code=None, redirect_uri=None, body='',
include_client_id=True, **kwargs):
"""Prepare the access token request body.
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-u... | python | {
"resource": ""
} |
q225125 | WebApplicationClient.parse_request_uri_response | train | def parse_request_uri_response(self, uri, state=None):
"""Parse the URI query for code and state.
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 componen... | python | {
"resource": ""
} |
q225126 | Client.add_token | train | def add_token(self, uri, http_method='GET', body=None, headers=None,
token_placement=None, **kwargs):
"""Add token to the request uri, body or authorization header.
The access token type provides the client with the information
required to successfully utilize the access token... | python | {
"resource": ""
} |
q225127 | Client.prepare_authorization_request | train | def prepare_authorization_request(self, authorization_url, state=None,
redirect_url=None, scope=None, **kwargs):
"""Prepare the authorization request.
This is the first step in many OAuth flows in which the user is
redirected to a certain authorization URL.... | python | {
"resource": ""
} |
q225128 | Client.prepare_token_request | train | def prepare_token_request(self, token_url, authorization_response=None,
redirect_url=None, state=None, body='', **kwargs):
"""Prepare a token creation request.
Note that these requests usually require client authentication, either
by including client_id or a set of... | python | {
"resource": ""
} |
q225129 | Client.prepare_refresh_token_request | train | def prepare_refresh_token_request(self, token_url, refresh_token=None,
body='', scope=None, **kwargs):
"""Prepare an access token refresh request.
Expired access tokens can be replaced by new access tokens without
going through the OAuth dance if the client... | python | {
"resource": ""
} |
q225130 | Client.parse_request_body_response | train | def parse_request_body_response(self, body, scope=None, **kwargs):
"""Parse the JSON response body.
If the access token request is valid and authorized, the
authorization server issues an access token as described in
`Section 5.1`_. A refresh token SHOULD NOT be included. If the reque... | python | {
"resource": ""
} |
q225131 | Client.prepare_refresh_body | train | def prepare_refresh_body(self, body='', refresh_token=None, scope=None, **kwargs):
"""Prepare an access token request, using a refresh token.
If the authorization server issued a refresh token to the client, the
client makes a refresh request to the token endpoint by adding the
followin... | python | {
"resource": ""
} |
q225132 | Client._add_mac_token | train | def _add_mac_token(self, uri, http_method='GET', body=None,
headers=None, token_placement=AUTH_HEADER, ext=None, **kwargs):
"""Add a MAC token to the request authorization header.
Warning: MAC token support is experimental as the spec is not yet stable.
"""
if tok... | python | {
"resource": ""
} |
q225133 | Client.populate_token_attributes | train | def populate_token_attributes(self, response):
"""Add attributes from a token exchange response to self."""
if 'access_token' in response:
self.access_token = response.get('access_token')
if 'refresh_token' in response:
self.refresh_token = response.get('refresh_token')... | python | {
"resource": ""
} |
q225134 | BaseEndpoint._get_signature_type_and_params | train | def _get_signature_type_and_params(self, request):
"""Extracts parameters from query, headers and body. Signature type
is set to the source in which parameters were found.
"""
# Per RFC5849, only the Authorization header may contain the 'realm'
# optional parameter.
heade... | python | {
"resource": ""
} |
q225135 | ResourceOwnerPasswordCredentialsGrant.create_token_response | train | def create_token_response(self, request, token_handler):
"""Return token or error in json format.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token_handler: A token handler instance, for example of type
oauthlib.oauth2.Be... | python | {
"resource": ""
} |
q225136 | RequestValidator.check_client_key | train | def check_client_key(self, client_key):
"""Check that the client key only contains safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.client_key_length
return (set(client_key) <= self.safe_characters and
lower <= len(cli... | python | {
"resource": ""
} |
q225137 | RequestValidator.check_request_token | train | def check_request_token(self, request_token):
"""Checks that the request token contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.request_token_length
return (set(request_token) <= self.safe_characters and
... | python | {
"resource": ""
} |
q225138 | RequestValidator.check_access_token | train | def check_access_token(self, request_token):
"""Checks that the token contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.access_token_length
return (set(request_token) <= self.safe_characters and
lower <= l... | python | {
"resource": ""
} |
q225139 | RequestValidator.check_nonce | train | def check_nonce(self, nonce):
"""Checks that the nonce only contains only safe characters
and is no shorter than lower and no longer than upper.
"""
lower, upper = self.nonce_length
return (set(nonce) <= self.safe_characters and
lower <= len(nonce) <= upper) | python | {
"resource": ""
} |
q225140 | RequestValidator.check_verifier | train | 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) <=... | python | {
"resource": ""
} |
q225141 | RequestValidator.validate_timestamp_and_nonce | train | 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`` ... | python | {
"resource": ""
} |
q225142 | prepare_grant_uri | train | 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
... | python | {
"resource": ""
} |
q225143 | prepare_token_request | train | 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 ... | python | {
"resource": ""
} |
q225144 | parse_authorization_code_response | train | 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 o... | python | {
"resource": ""
} |
q225145 | parse_implicit_response | train | 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 ... | python | {
"resource": ""
} |
q225146 | parse_token_response | train | 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:
... | python | {
"resource": ""
} |
q225147 | validate_token_parameters | train | 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.")
i... | python | {
"resource": ""
} |
q225148 | LegacyApplicationClient.prepare_request_body | train | 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... | python | {
"resource": ""
} |
q225149 | MobileApplicationClient.prepare_request_uri | train | 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
... | python | {
"resource": ""
} |
q225150 | MobileApplicationClient.parse_request_uri_response | train | 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 compon... | python | {
"resource": ""
} |
q225151 | RequestValidator.confirm_redirect_uri | train | 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 cod... | python | {
"resource": ""
} |
q225152 | RequestValidator.save_token | train | 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
"... | python | {
"resource": ""
} |
q225153 | encode_params_utf8 | train | 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 isin... | python | {
"resource": ""
} |
q225154 | decode_params_utf8 | train | 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, ... | python | {
"resource": ""
} |
q225155 | urldecode | train | 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. url... | python | {
"resource": ""
} |
q225156 | extract_params | train | 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 ... | python | {
"resource": ""
} |
q225157 | generate_token | train | 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 i... | python | {
"resource": ""
} |
q225158 | add_params_to_qs | train | 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 | {
"resource": ""
} |
q225159 | add_params_to_uri | train | 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.urlu... | python | {
"resource": ""
} |
q225160 | to_unicode | train | 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(d... | python | {
"resource": ""
} |
q225161 | _append_params | train | 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://... | python | {
"resource": ""
} |
q225162 | prepare_request_uri_query | train | 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 = urlp... | python | {
"resource": ""
} |
q225163 | RequestTokenEndpoint.validate_request_token_request | train | 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 r... | python | {
"resource": ""
} |
q225164 | SignatureOnlyEndpoint.validate_request | train | 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 a... | python | {
"resource": ""
} |
q225165 | JWTToken.create_token | train | 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 ... | python | {
"resource": ""
} |
q225166 | Client.get_oauth_signature | train | 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
... | python | {
"resource": ""
} |
q225167 | Client.get_oauth_params | train | 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.ti... | python | {
"resource": ""
} |
q225168 | Client._render | train | 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 f... | python | {
"resource": ""
} |
q225169 | Client.sign | train | 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
... | python | {
"resource": ""
} |
q225170 | BaseEndpoint._raise_on_invalid_client | train | 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)
... | python | {
"resource": ""
} |
q225171 | BaseEndpoint._raise_on_unsupported_token | train | 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... | python | {
"resource": ""
} |
q225172 | RevocationEndpoint.create_revocation_response | train | 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 submitte... | python | {
"resource": ""
} |
q225173 | GrantTypeBase.prepare_authorization_response | train | 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... | python | {
"resource": ""
} |
q225174 | prepare_mac_header | train | 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):
"... | python | {
"resource": ""
} |
q225175 | get_token_from_header | train | 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' i... | python | {
"resource": ""
} |
q225176 | BearerToken.create_token | train | 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:
w... | python | {
"resource": ""
} |
q225177 | list_to_scope | train | 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 sc... | python | {
"resource": ""
} |
q225178 | scope_to_list | train | 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 | {
"resource": ""
} |
q225179 | host_from_uri | train | 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, ... | python | {
"resource": ""
} |
q225180 | escape | train | 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 | {
"resource": ""
} |
q225181 | generate_age | train | 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 | {
"resource": ""
} |
q225182 | ImplicitGrant.create_token_response | train | 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
oaut... | python | {
"resource": ""
} |
q225183 | ImplicitGrant.validate_token_request | train | 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 ... | python | {
"resource": ""
} |
q225184 | GrantTypeBase.validate_authorization_request | train | 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 ... | python | {
"resource": ""
} |
q225185 | GrantTypeBase.openid_authorization_validator | train | 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 t... | python | {
"resource": ""
} |
q225186 | HybridGrant.openid_authorization_validator | train | 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_i... | python | {
"resource": ""
} |
q225187 | filter_oauth_params | train | 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 | {
"resource": ""
} |
q225188 | parse_authorization_header | train | 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):])
... | python | {
"resource": ""
} |
q225189 | ImplicitGrant.openid_authorization_validator | train | 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
... | python | {
"resource": ""
} |
q225190 | AccessTokenEndpoint.create_access_token | train | 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.comm... | python | {
"resource": ""
} |
q225191 | AccessTokenEndpoint.create_access_token_response | train | 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 ... | python | {
"resource": ""
} |
q225192 | AccessTokenEndpoint.validate_access_token_request | train | 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 re... | python | {
"resource": ""
} |
q225193 | ResourceEndpoint.verify_request | train | 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 = sco... | python | {
"resource": ""
} |
q225194 | ResourceEndpoint.find_token_type | train | 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... | python | {
"resource": ""
} |
q225195 | Tfstate.load_file | train | 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 =... | python | {
"resource": ""
} |
q225196 | Terraform.generate_cmd_string | train | 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:
te... | python | {
"resource": ""
} |
q225197 | OneLogin_Saml2_Response.get_nameid_data | train | 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_a... | python | {
"resource": ""
} |
q225198 | OneLogin_Saml2_Response.validate_signed_elements | train | 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 excep... | python | {
"resource": ""
} |
q225199 | OneLogin_Saml2_Response.__decrypt_assertion | train | 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()... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.