idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
223,700 | def path_for ( self , * args ) : if args and args [ 0 ] . startswith ( os . path . sep ) : return os . path . join ( * args ) return os . path . join ( self . _root_path or os . getcwd ( ) , * args ) | Path containing _root_path | 65 | 6 |
223,701 | def validators ( self ) : if not hasattr ( self , "_validators" ) : self . _validators = ValidatorList ( self ) return self . _validators | Gets or creates validator wrapper | 38 | 7 |
223,702 | def populate_obj ( self , obj , keys = None ) : keys = keys or self . keys ( ) for key in keys : key = key . upper ( ) value = self . get ( key , empty ) if value is not empty : setattr ( obj , key , value ) | Given the obj populate it using self . store items . | 60 | 11 |
223,703 | def default_loader ( obj , defaults = None ) : defaults = defaults or { } default_settings_values = { key : value for key , value in default_settings . __dict__ . items ( ) # noqa if key . isupper ( ) } all_keys = deduplicate ( list ( defaults . keys ( ) ) + list ( default_settings_values . keys ( ) ) ) for key in all_keys : if not obj . exists ( key ) : value = defaults . get ( key , default_settings_values . get ( key ) ) obj . logger . debug ( "loading: %s:%s" , key , value ) obj . set ( key , value ) # start dotenv to get default env vars from there # check overrides in env vars default_settings . start_dotenv ( obj ) # Deal with cases where a custom ENV_SWITCHER_IS_PROVIDED # Example: Flask and Django Extensions env_switcher = defaults . get ( "ENV_SWITCHER_FOR_DYNACONF" , "ENV_FOR_DYNACONF" ) for key in all_keys : if key not in default_settings_values . keys ( ) : continue env_value = obj . get_environ ( env_switcher if key == "ENV_FOR_DYNACONF" else key , default = "_not_found" , ) if env_value != "_not_found" : obj . logger . debug ( "overriding from envvar: %s:%s" , key , env_value ) obj . set ( key , env_value , tomlfy = True ) | Loads default settings and check if there are overridings exported as environment variables | 363 | 16 |
223,704 | def enable_external_loaders ( obj ) : for name , loader in ct . EXTERNAL_LOADERS . items ( ) : enabled = getattr ( obj , "{}_ENABLED_FOR_DYNACONF" . format ( name . upper ( ) ) , False ) if ( enabled and enabled not in false_values and loader not in obj . LOADERS_FOR_DYNACONF ) : # noqa obj . logger . debug ( "loaders: Enabling %s" , loader ) obj . LOADERS_FOR_DYNACONF . insert ( 0 , loader ) | Enable external service loaders like VAULT_ and REDIS_ looks forenv variables like REDIS_ENABLED_FOR_DYNACONF | 134 | 32 |
223,705 | def _walk_to_root ( path , break_at = None ) : if not os . path . exists ( path ) : # pragma: no cover raise IOError ( "Starting path not found" ) if os . path . isfile ( path ) : # pragma: no cover path = os . path . dirname ( path ) last_dir = None current_dir = os . path . abspath ( path ) paths = [ ] while last_dir != current_dir : paths . append ( current_dir ) paths . append ( os . path . join ( current_dir , "config" ) ) if break_at and current_dir == os . path . abspath ( break_at ) : # noqa logger . debug ( "Reached the %s directory, breaking." , break_at ) break parent_dir = os . path . abspath ( os . path . join ( current_dir , os . path . pardir ) ) last_dir , current_dir = current_dir , parent_dir return paths | Directories starting from the given directory up to the root or break_at | 221 | 15 |
223,706 | def find_file ( filename = ".env" , project_root = None , skip_files = None , * * kwargs ) : search_tree = [ ] work_dir = os . getcwd ( ) skip_files = skip_files or [ ] if project_root is None : logger . debug ( "No root_path for %s" , filename ) else : logger . debug ( "Got root_path %s for %s" , project_root , filename ) search_tree . extend ( _walk_to_root ( project_root , break_at = work_dir ) ) script_dir = os . path . dirname ( os . path . abspath ( inspect . stack ( ) [ - 1 ] . filename ) ) # Path to invoked script and recursively to root with its ./config dirs search_tree . extend ( _walk_to_root ( script_dir ) ) # Path to where Python interpreter was invoked and recursively to root search_tree . extend ( _walk_to_root ( work_dir ) ) # Don't look the same place twice search_tree = deduplicate ( search_tree ) global SEARCHTREE SEARCHTREE != search_tree and logger . debug ( "Search Tree: %s" , search_tree ) SEARCHTREE = search_tree logger . debug ( "Searching for %s" , filename ) for dirname in search_tree : check_path = os . path . join ( dirname , filename ) if check_path in skip_files : continue if os . path . exists ( check_path ) : logger . debug ( "Found: %s" , os . path . abspath ( check_path ) ) return check_path # First found will return # return empty string if not found so it can still be joined in os.path return "" | Search in increasingly higher folders for the given file Returns path to the file if found or an empty string otherwise . | 397 | 22 |
223,707 | def validate ( self , settings ) : if self . envs is None : self . envs = [ settings . current_env ] if self . when is not None : try : # inherit env if not defined if self . when . envs is None : self . when . envs = self . envs self . when . validate ( settings ) except ValidationError : # if when is invalid, return canceling validation flow return # If only using current_env, skip using_env decoration (reload) if ( len ( self . envs ) == 1 and self . envs [ 0 ] . upper ( ) == settings . current_env . upper ( ) ) : self . _validate_items ( settings , settings . current_env ) return for env in self . envs : with settings . using_env ( env ) : self . _validate_items ( settings , env ) | Raise ValidationError if invalid | 189 | 7 |
223,708 | def to_representation ( self , instance ) : ret = OrderedDict ( ) readable_fields = [ field for field in self . fields . values ( ) if not field . write_only ] for field in readable_fields : try : field_representation = self . _get_field_representation ( field , instance ) ret [ field . field_name ] = field_representation except SkipField : continue return ret | Object instance - > Dict of primitive datatypes . | 91 | 12 |
223,709 | def extract_attributes ( cls , fields , resource ) : data = OrderedDict ( ) for field_name , field in six . iteritems ( fields ) : # ID is always provided in the root of JSON API so remove it from attributes if field_name == 'id' : continue # don't output a key for write only fields if fields [ field_name ] . write_only : continue # Skip fields with relations if isinstance ( field , ( relations . RelatedField , relations . ManyRelatedField , BaseSerializer ) ) : continue # Skip read_only attribute fields when `resource` is an empty # serializer. Prevents the "Raw Data" form of the browsable API # from rendering `"foo": null` for read only fields try : resource [ field_name ] except KeyError : if fields [ field_name ] . read_only : continue data . update ( { field_name : resource . get ( field_name ) } ) return utils . _format_object ( data ) | Builds the attributes object of the JSON API resource object . | 216 | 12 |
223,710 | def extract_relation_instance ( cls , field_name , field , resource_instance , serializer ) : relation_instance = None try : relation_instance = getattr ( resource_instance , field_name ) except AttributeError : try : # For ManyRelatedFields if `related_name` is not set # we need to access `foo_set` from `source` relation_instance = getattr ( resource_instance , field . child_relation . source ) except AttributeError : if hasattr ( serializer , field . source ) : serializer_method = getattr ( serializer , field . source ) relation_instance = serializer_method ( resource_instance ) else : # case when source is a simple remap on resource_instance try : relation_instance = getattr ( resource_instance , field . source ) except AttributeError : pass return relation_instance | Determines what instance represents given relation and extracts it . | 188 | 12 |
223,711 | def extract_meta ( cls , serializer , resource ) : if hasattr ( serializer , 'child' ) : meta = getattr ( serializer . child , 'Meta' , None ) else : meta = getattr ( serializer , 'Meta' , None ) meta_fields = getattr ( meta , 'meta_fields' , [ ] ) data = OrderedDict ( ) for field_name in meta_fields : data . update ( { field_name : resource . get ( field_name ) } ) return data | Gathers the data from serializer fields specified in meta_fields and adds it to the meta object . | 114 | 22 |
223,712 | def extract_root_meta ( cls , serializer , resource ) : many = False if hasattr ( serializer , 'child' ) : many = True serializer = serializer . child data = { } if getattr ( serializer , 'get_root_meta' , None ) : json_api_meta = serializer . get_root_meta ( resource , many ) assert isinstance ( json_api_meta , dict ) , 'get_root_meta must return a dict' data . update ( json_api_meta ) return data | Calls a get_root_meta function on a serializer if it exists . | 118 | 17 |
223,713 | def get_queryset ( self ) : qs = super ( PrefetchForIncludesHelperMixin , self ) . get_queryset ( ) if not hasattr ( self , 'prefetch_for_includes' ) : return qs includes = self . request . GET . get ( 'include' , '' ) . split ( ',' ) for inc in includes + [ '__all__' ] : prefetches = self . prefetch_for_includes . get ( inc ) if prefetches : qs = qs . prefetch_related ( * prefetches ) return qs | This viewset provides a helper attribute to prefetch related models based on the include specified in the URL . | 130 | 21 |
223,714 | def get_queryset ( self , * args , * * kwargs ) : qs = super ( AutoPrefetchMixin , self ) . get_queryset ( * args , * * kwargs ) included_resources = get_included_resources ( self . request ) for included in included_resources : included_model = None levels = included . split ( '.' ) level_model = qs . model for level in levels : if not hasattr ( level_model , level ) : break field = getattr ( level_model , level ) field_class = field . __class__ is_forward_relation = ( issubclass ( field_class , ForwardManyToOneDescriptor ) or issubclass ( field_class , ManyToManyDescriptor ) ) is_reverse_relation = ( issubclass ( field_class , ReverseManyToOneDescriptor ) or issubclass ( field_class , ReverseOneToOneDescriptor ) ) if not ( is_forward_relation or is_reverse_relation ) : break if level == levels [ - 1 ] : included_model = field else : if issubclass ( field_class , ReverseOneToOneDescriptor ) : model_field = field . related . field else : model_field = field . field if is_forward_relation : level_model = model_field . related_model else : level_model = model_field . model if included_model is not None : qs = qs . prefetch_related ( included . replace ( '.' , '__' ) ) return qs | This mixin adds automatic prefetching for OneToOne and ManyToMany fields . | 343 | 18 |
223,715 | def get_url ( self , name , view_name , kwargs , request ) : # Return None if the view name is not supplied if not view_name : return None # Return the hyperlink, or error if incorrectly configured. try : url = self . reverse ( view_name , kwargs = kwargs , request = request ) except NoReverseMatch : msg = ( 'Could not resolve URL for hyperlinked relationship using ' 'view name "%s". You may have failed to include the related ' 'model in your API, or incorrectly configured the ' '`lookup_field` attribute on this field.' ) raise ImproperlyConfigured ( msg % view_name ) if url is None : return None return Hyperlink ( url , name ) | Given a name view name and kwargs return the URL that hyperlinks to the object . | 162 | 19 |
223,716 | def get_resource_name ( context , expand_polymorphic_types = False ) : 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 # Check to see if there is a status code and return early # with the resource_name value of `errors`. try : code = str ( view . response . status_code ) except ( AttributeError , ValueError ) : pass else : if code . startswith ( '4' ) or code . startswith ( '5' ) : return 'errors' try : resource_name = getattr ( view , 'resource_name' ) except AttributeError : try : serializer = view . get_serializer_class ( ) if expand_polymorphic_types and issubclass ( serializer , PolymorphicModelSerializer ) : return serializer . get_polymorphic_types ( ) else : return get_resource_type_from_serializer ( serializer ) except AttributeError : try : resource_name = get_resource_type_from_model ( view . model ) except AttributeError : resource_name = view . __class__ . __name__ if not isinstance ( resource_name , six . string_types ) : # The resource name is not a string - return as is return resource_name # the name was calculated automatically from the view > pluralize and format resource_name = format_resource_type ( resource_name ) return resource_name | Return the name of a resource . | 342 | 7 |
223,717 | def format_field_names ( obj , format_type = None ) : if format_type is None : format_type = json_api_settings . FORMAT_FIELD_NAMES if isinstance ( obj , dict ) : formatted = OrderedDict ( ) for key , value in obj . items ( ) : key = format_value ( key , format_type ) formatted [ key ] = value return formatted return obj | Takes a dict and returns it with formatted keys as set in format_type or JSON_API_FORMAT_FIELD_NAMES | 90 | 28 |
223,718 | def _format_object ( obj , format_type = None ) : if json_api_settings . FORMAT_KEYS is not None : return format_keys ( obj , format_type ) return format_field_names ( obj , format_type ) | Depending on settings calls either format_keys or format_field_names | 55 | 14 |
223,719 | def get_included_resources ( request , serializer = None ) : 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_resources_from_serializer ( serializer ) | Build a list of included resources . | 77 | 7 |
223,720 | def parse ( self , stream , media_type = None , parser_context = None ) : result = super ( JSONParser , self ) . parse ( stream , media_type = media_type , parser_context = parser_context ) if not isinstance ( result , dict ) or 'data' not in result : raise ParseError ( 'Received document does not contain primary data' ) data = result . get ( 'data' ) view = parser_context [ 'view' ] from rest_framework_json_api . views import RelationshipView if isinstance ( view , RelationshipView ) : # We skip parsing the object as JSONAPI Resource Identifier Object and not a regular # Resource Object if isinstance ( data , list ) : for resource_identifier_object in data : if not ( resource_identifier_object . get ( 'id' ) and resource_identifier_object . get ( 'type' ) ) : raise ParseError ( 'Received data contains one or more malformed JSONAPI ' 'Resource Identifier Object(s)' ) elif not ( data . get ( 'id' ) and data . get ( 'type' ) ) : raise ParseError ( 'Received data is not a valid JSONAPI Resource Identifier Object' ) return data request = parser_context . get ( 'request' ) # Check for inconsistencies if request . method in ( 'PUT' , 'POST' , 'PATCH' ) : resource_name = utils . get_resource_name ( parser_context , expand_polymorphic_types = True ) if isinstance ( resource_name , six . string_types ) : if data . get ( 'type' ) != resource_name : raise exceptions . Conflict ( "The resource object's type ({data_type}) is not the type that " "constitute the collection represented by the endpoint " "({resource_type})." . format ( data_type = data . get ( 'type' ) , resource_type = resource_name ) ) else : if data . get ( 'type' ) not in resource_name : raise exceptions . Conflict ( "The resource object's type ({data_type}) is not the type that " "constitute the collection represented by the endpoint " "(one of [{resource_types}])." . format ( data_type = data . get ( 'type' ) , resource_types = ", " . join ( resource_name ) ) ) if not data . get ( 'id' ) and request . method in ( 'PATCH' , 'PUT' ) : raise ParseError ( "The resource identifier object must contain an 'id' member" ) # Construct the return data serializer_class = getattr ( view , 'serializer_class' , None ) parsed_data = { 'id' : data . get ( 'id' ) } if 'id' in data else { } # `type` field needs to be allowed in none polymorphic serializers if serializer_class is not None : if issubclass ( serializer_class , serializers . PolymorphicModelSerializer ) : parsed_data [ 'type' ] = data . get ( 'type' ) parsed_data . update ( self . parse_attributes ( data ) ) parsed_data . update ( self . parse_relationships ( data ) ) parsed_data . update ( self . parse_metadata ( result ) ) return parsed_data | Parses the incoming bytestream as JSON and returns the resulting data | 726 | 15 |
223,721 | def get_resource_type_from_included_serializer ( self ) : field_name = self . field_name or self . parent . field_name parent = self . get_parent_serializer ( ) if parent is not None : # accept both singular and plural versions of field_name field_names = [ inflection . singularize ( field_name ) , inflection . pluralize ( field_name ) ] includes = get_included_serializers ( parent ) for field in field_names : if field in includes . keys ( ) : return get_resource_type_from_serializer ( includes [ field ] ) return None | Check to see it this resource has a different resource_name when included and return that name or None | 138 | 20 |
223,722 | def sign_plaintext ( client_secret , resource_owner_secret ) : # The "oauth_signature" protocol parameter is set to the concatenated # value of: # 1. The client shared-secret, after being encoded (`Section 3.6`_). # # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 signature = utils . escape ( client_secret or '' ) # 2. An "&" character (ASCII code 38), which MUST be included even # when either secret is empty. signature += '&' # 3. The token shared-secret, after being encoded (`Section 3.6`_). # # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6 signature += utils . escape ( resource_owner_secret or '' ) return signature | Sign a request using plaintext . | 206 | 7 |
223,723 | def verify_hmac_sha1 ( request , client_secret = None , resource_owner_secret = None ) : norm_params = normalize_parameters ( request . params ) bs_uri = base_string_uri ( request . uri ) sig_base_str = signature_base_string ( request . http_method , bs_uri , norm_params ) signature = sign_hmac_sha1 ( sig_base_str , client_secret , resource_owner_secret ) match = safe_string_equals ( signature , request . signature ) if not match : log . debug ( 'Verify HMAC-SHA1 failed: signature base string: %s' , sig_base_str ) return match | Verify a HMAC - SHA1 signature . | 158 | 10 |
223,724 | def verify_plaintext ( request , client_secret = None , resource_owner_secret = None ) : signature = sign_plaintext ( client_secret , resource_owner_secret ) match = safe_string_equals ( signature , request . signature ) if not match : log . debug ( 'Verify PLAINTEXT failed' ) return match | Verify a PLAINTEXT signature . | 74 | 8 |
223,725 | def create_authorization_response ( self , uri , http_method = 'GET' , body = None , headers = None , realms = None , credentials = None ) : request = self . _create_request ( uri , http_method = http_method , body = body , headers = headers ) if not request . resource_owner_key : raise errors . InvalidRequestError ( 'Missing mandatory parameter oauth_token.' ) if not self . request_validator . verify_request_token ( request . resource_owner_key , request ) : raise errors . InvalidClientError ( ) request . realms = realms if ( request . realms and not self . request_validator . verify_realms ( request . resource_owner_key , request . realms , request ) ) : raise errors . InvalidRequestError ( description = ( 'User granted access to realms outside of ' 'what the client may request.' ) ) verifier = self . create_verifier ( request , credentials or { } ) redirect_uri = self . request_validator . get_redirect_uri ( request . resource_owner_key , request ) if redirect_uri == 'oob' : response_headers = { 'Content-Type' : 'application/x-www-form-urlencoded' } response_body = urlencode ( verifier ) return response_headers , response_body , 200 else : populated_redirect = add_params_to_uri ( redirect_uri , verifier . items ( ) ) return { 'Location' : populated_redirect } , None , 302 | Create an authorization response with a new request token if valid . | 337 | 12 |
223,726 | def get_realms_and_credentials ( self , uri , http_method = 'GET' , body = None , headers = None ) : request = self . _create_request ( uri , http_method = http_method , body = body , headers = headers ) if not self . request_validator . verify_request_token ( request . resource_owner_key , request ) : raise errors . InvalidClientError ( ) realms = self . request_validator . get_realms ( request . resource_owner_key , request ) return realms , { 'resource_owner_key' : request . resource_owner_key } | Fetch realms and credentials for the presented request token . | 140 | 11 |
223,727 | def create_introspect_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 , body , headers ) try : self . validate_introspect_request ( request ) log . debug ( 'Token introspect valid for %r.' , request ) except OAuth2Error as e : log . debug ( 'Client error during validation of %r. %r.' , request , e ) resp_headers . update ( e . headers ) return resp_headers , e . json , e . status_code claims = self . request_validator . introspect_token ( request . token , request . token_type_hint , request ) if claims is None : return resp_headers , json . dumps ( dict ( active = False ) ) , 200 if "active" in claims : claims . pop ( "active" ) return resp_headers , json . dumps ( dict ( active = True , * * claims ) ) , 200 | Create introspect valid or invalid response | 260 | 7 |
223,728 | def prepare_request_body ( self , private_key = None , subject = None , issuer = None , audience = None , expires_at = None , issued_at = None , extra_claims = None , body = '' , scope = None , include_client_id = False , * * kwargs ) : import jwt key = private_key or self . private_key if not key : raise ValueError ( 'An encryption key must be supplied to make JWT' ' token requests.' ) claim = { 'iss' : issuer or self . issuer , 'aud' : audience or self . audience , 'sub' : subject or self . subject , 'exp' : int ( expires_at or time . time ( ) + 3600 ) , 'iat' : int ( issued_at or time . time ( ) ) , } for attr in ( 'iss' , 'aud' , 'sub' ) : if claim [ attr ] is None : raise ValueError ( 'Claim must include %s but none was given.' % attr ) if 'not_before' in kwargs : claim [ 'nbf' ] = kwargs . pop ( 'not_before' ) if 'jwt_id' in kwargs : claim [ 'jti' ] = kwargs . pop ( 'jwt_id' ) claim . update ( extra_claims or { } ) assertion = jwt . encode ( claim , key , 'RS256' ) assertion = to_unicode ( assertion ) kwargs [ 'client_id' ] = self . client_id kwargs [ 'include_client_id' ] = include_client_id return prepare_token_request ( self . grant_type , body = body , assertion = assertion , scope = scope , * * kwargs ) | Create and add a JWT assertion to the request body . | 391 | 12 |
223,729 | def create_authorization_code ( self , request ) : grant = { 'code' : common . generate_token ( ) } if hasattr ( request , 'state' ) and request . state : grant [ 'state' ] = request . state log . debug ( 'Created authorization code grant %r for request %r.' , grant , request ) return grant | Generates an authorization grant represented as a dictionary . | 76 | 10 |
223,730 | def create_token_response ( self , request , token_handler ) : headers = self . _get_default_headers ( ) try : self . validate_token_request ( request ) log . debug ( 'Token request validation ok for %r.' , request ) except errors . OAuth2Error as e : log . debug ( 'Client error during validation of %r. %r.' , request , e ) headers . update ( e . headers ) return headers , e . json , e . status_code token = token_handler . create_token ( request , refresh_token = self . refresh_token ) for modifier in self . _token_modifiers : token = modifier ( token , token_handler , request ) self . request_validator . save_token ( token , request ) self . request_validator . invalidate_authorization_code ( request . client_id , request . code , request ) return headers , json . dumps ( token ) , 200 | Validate the authorization code . | 205 | 6 |
223,731 | def create_metadata_response ( self , uri , http_method = 'GET' , body = None , headers = None ) : headers = { 'Content-Type' : 'application/json' } return headers , json . dumps ( self . claims ) , 200 | Create metadata response | 57 | 3 |
223,732 | def validate_metadata_token ( self , claims , endpoint ) : self . _grant_types . extend ( endpoint . _grant_types . keys ( ) ) claims . setdefault ( "token_endpoint_auth_methods_supported" , [ "client_secret_post" , "client_secret_basic" ] ) self . validate_metadata ( claims , "token_endpoint_auth_methods_supported" , is_list = True ) self . validate_metadata ( claims , "token_endpoint_auth_signing_alg_values_supported" , is_list = True ) self . validate_metadata ( claims , "token_endpoint" , is_required = True , is_url = True ) | 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 . | 160 | 40 |
223,733 | def prepare_request_body ( self , code = None , redirect_uri = None , body = '' , include_client_id = True , * * kwargs ) : code = code or self . code if 'client_id' in kwargs : warnings . warn ( "`client_id` has been deprecated in favor of " "`include_client_id`, a boolean value which will " "include the already configured `self.client_id`." , DeprecationWarning ) if kwargs [ 'client_id' ] != self . client_id : raise ValueError ( "`client_id` was supplied as an argument, but " "it does not match `self.client_id`" ) kwargs [ 'client_id' ] = self . client_id kwargs [ 'include_client_id' ] = include_client_id return prepare_token_request ( self . grant_type , code = code , body = body , redirect_uri = redirect_uri , * * kwargs ) | Prepare the access token request body . | 225 | 8 |
223,734 | def parse_request_uri_response ( self , uri , state = None ) : response = parse_authorization_code_response ( uri , state = state ) self . populate_code_attributes ( response ) return response | Parse the URI query for code and state . | 50 | 10 |
223,735 | def add_token ( self , uri , http_method = 'GET' , body = None , headers = None , token_placement = None , * * kwargs ) : if not is_secure_transport ( uri ) : raise InsecureTransportError ( ) token_placement = token_placement or self . default_token_placement case_insensitive_token_types = dict ( ( k . lower ( ) , v ) for k , v in self . token_types . items ( ) ) if not self . token_type . lower ( ) in case_insensitive_token_types : raise ValueError ( "Unsupported token type: %s" % self . token_type ) if not ( self . access_token or self . token . get ( 'access_token' ) ) : raise ValueError ( "Missing access token." ) if self . _expires_at and self . _expires_at < time . time ( ) : raise TokenExpiredError ( ) return case_insensitive_token_types [ self . token_type . lower ( ) ] ( uri , http_method , body , headers , token_placement , * * kwargs ) | Add token to the request uri body or authorization header . | 261 | 12 |
223,736 | def prepare_authorization_request ( self , authorization_url , state = None , redirect_url = None , scope = None , * * kwargs ) : if not is_secure_transport ( authorization_url ) : raise InsecureTransportError ( ) self . state = state or self . state_generator ( ) self . redirect_url = redirect_url or self . redirect_url self . scope = scope or self . scope auth_url = self . prepare_request_uri ( authorization_url , redirect_uri = self . redirect_url , scope = self . scope , state = self . state , * * kwargs ) return auth_url , FORM_ENC_HEADERS , '' | Prepare the authorization request . | 152 | 6 |
223,737 | def prepare_token_request ( self , token_url , authorization_response = None , redirect_url = None , state = None , body = '' , * * kwargs ) : if not is_secure_transport ( token_url ) : raise InsecureTransportError ( ) state = state or self . state if authorization_response : self . parse_request_uri_response ( authorization_response , state = state ) self . redirect_url = redirect_url or self . redirect_url body = self . prepare_request_body ( body = body , redirect_uri = self . redirect_url , * * kwargs ) return token_url , FORM_ENC_HEADERS , body | Prepare a token creation request . | 150 | 7 |
223,738 | def prepare_refresh_token_request ( self , token_url , refresh_token = None , body = '' , scope = None , * * kwargs ) : if not is_secure_transport ( token_url ) : raise InsecureTransportError ( ) self . scope = scope or self . scope body = self . prepare_refresh_body ( body = body , refresh_token = refresh_token , scope = self . scope , * * kwargs ) return token_url , FORM_ENC_HEADERS , body | Prepare an access token refresh request . | 116 | 8 |
223,739 | def parse_request_body_response ( self , body , scope = None , * * kwargs ) : self . token = parse_token_response ( body , scope = scope ) self . populate_token_attributes ( self . token ) return self . token | Parse the JSON response body . | 57 | 7 |
223,740 | def prepare_refresh_body ( self , body = '' , refresh_token = None , scope = None , * * kwargs ) : refresh_token = refresh_token or self . refresh_token return prepare_token_request ( self . refresh_token_key , body = body , scope = scope , refresh_token = refresh_token , * * kwargs ) | Prepare an access token request using a refresh token . | 81 | 11 |
223,741 | def _add_mac_token ( self , uri , http_method = 'GET' , body = None , headers = None , token_placement = AUTH_HEADER , ext = None , * * kwargs ) : if token_placement != AUTH_HEADER : raise ValueError ( "Invalid token placement." ) headers = tokens . prepare_mac_header ( self . access_token , uri , self . mac_key , http_method , headers = headers , body = body , ext = ext , hash_algorithm = self . mac_algorithm , * * kwargs ) return uri , headers , body | Add a MAC token to the request authorization header . | 137 | 10 |
223,742 | def populate_token_attributes ( self , response ) : if 'access_token' in response : self . access_token = response . get ( 'access_token' ) if 'refresh_token' in response : self . refresh_token = response . get ( 'refresh_token' ) if 'token_type' in response : self . token_type = response . get ( 'token_type' ) if 'expires_in' in response : self . expires_in = response . get ( 'expires_in' ) self . _expires_at = time . time ( ) + int ( self . expires_in ) if 'expires_at' in response : self . _expires_at = int ( response . get ( 'expires_at' ) ) if 'mac_key' in response : self . mac_key = response . get ( 'mac_key' ) if 'mac_algorithm' in response : self . mac_algorithm = response . get ( 'mac_algorithm' ) | Add attributes from a token exchange response to self . | 224 | 10 |
223,743 | def _get_signature_type_and_params ( self , request ) : # Per RFC5849, only the Authorization header may contain the 'realm' # optional parameter. header_params = signature . collect_parameters ( headers = request . headers , exclude_oauth_signature = False , with_realm = True ) body_params = signature . collect_parameters ( body = request . body , exclude_oauth_signature = False ) query_params = signature . collect_parameters ( uri_query = request . uri_query , exclude_oauth_signature = False ) params = [ ] params . extend ( header_params ) params . extend ( body_params ) params . extend ( query_params ) signature_types_with_oauth_params = list ( filter ( lambda s : s [ 2 ] , ( ( SIGNATURE_TYPE_AUTH_HEADER , params , utils . filter_oauth_params ( header_params ) ) , ( SIGNATURE_TYPE_BODY , params , utils . filter_oauth_params ( body_params ) ) , ( SIGNATURE_TYPE_QUERY , params , utils . filter_oauth_params ( query_params ) ) ) ) ) if len ( signature_types_with_oauth_params ) > 1 : found_types = [ s [ 0 ] for s in signature_types_with_oauth_params ] raise errors . InvalidRequestError ( description = ( 'oauth_ params must come from only 1 signature' 'type but were found in %s' , ', ' . join ( found_types ) ) ) try : signature_type , params , oauth_params = signature_types_with_oauth_params [ 0 ] except IndexError : raise errors . InvalidRequestError ( description = 'Missing mandatory OAuth parameters.' ) return signature_type , params , oauth_params | Extracts parameters from query headers and body . Signature type is set to the source in which parameters were found . | 412 | 23 |
223,744 | def create_token_response ( self , request , token_handler ) : headers = self . _get_default_headers ( ) try : if self . request_validator . client_authentication_required ( request ) : log . debug ( 'Authenticating client, %r.' , request ) if not self . request_validator . authenticate_client ( request ) : log . debug ( 'Client authentication failed, %r.' , request ) raise errors . InvalidClientError ( request = request ) elif not self . request_validator . authenticate_client_id ( request . client_id , request ) : log . debug ( 'Client authentication failed, %r.' , request ) raise errors . InvalidClientError ( request = request ) log . debug ( 'Validating access token request, %r.' , request ) self . validate_token_request ( request ) except errors . OAuth2Error as e : log . debug ( 'Client error in token request, %s.' , e ) headers . update ( e . headers ) return headers , e . json , e . status_code token = token_handler . create_token ( request , self . refresh_token ) for modifier in self . _token_modifiers : token = modifier ( token ) self . request_validator . save_token ( token , request ) log . debug ( 'Issuing token %r to client id %r (%r) and username %s.' , token , request . client_id , request . client , request . username ) return headers , json . dumps ( token ) , 200 | Return token or error in json format . | 333 | 8 |
223,745 | def check_client_key ( self , client_key ) : lower , upper = self . client_key_length return ( set ( client_key ) <= self . safe_characters and lower <= len ( client_key ) <= upper ) | Check that the client key only contains safe characters and is no shorter than lower and no longer than upper . | 52 | 21 |
223,746 | def check_request_token ( self , request_token ) : lower , upper = self . request_token_length return ( set ( request_token ) <= self . safe_characters and lower <= len ( request_token ) <= upper ) | Checks that the request token contains only safe characters and is no shorter than lower and no longer than upper . | 52 | 22 |
223,747 | def check_access_token ( self , request_token ) : lower , upper = self . access_token_length return ( set ( request_token ) <= self . safe_characters and lower <= len ( request_token ) <= upper ) | Checks that the token contains only safe characters and is no shorter than lower and no longer than upper . | 52 | 21 |
223,748 | def check_nonce ( self , nonce ) : lower , upper = self . nonce_length return ( set ( nonce ) <= self . safe_characters and lower <= len ( nonce ) <= upper ) | Checks that the nonce only contains only safe characters and is no shorter than lower and no longer than upper . | 47 | 23 |
223,749 | 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 . | 47 | 22 |
223,750 | 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 . | 62 | 12 |
223,751 | 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 . | 201 | 8 |
223,752 | 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 . | 296 | 7 |
223,753 | 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 . | 114 | 10 |
223,754 | 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 . | 234 | 11 |
223,755 | 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 . | 214 | 11 |
223,756 | 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 . | 293 | 14 |
223,757 | 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 . | 105 | 12 |
223,758 | 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 . | 78 | 8 |
223,759 | 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 . | 62 | 7 |
223,760 | 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 . | 50 | 18 |
223,761 | 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 . | 44 | 11 |
223,762 | 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 | 78 | 25 |
223,763 | 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 . | 75 | 26 |
223,764 | 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 . | 536 | 26 |
223,765 | 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 . | 116 | 15 |
223,766 | 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 | 50 | 10 |
223,767 | 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 . | 66 | 13 |
223,768 | 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 . | 95 | 15 |
223,769 | 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 . | 172 | 13 |
223,770 | 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 . | 107 | 12 |
223,771 | 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 . | 94 | 7 |
223,772 | 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 . | 503 | 8 |
223,773 | 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 . | 83 | 11 |
223,774 | 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 | 323 | 12 |
223,775 | 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 . | 514 | 14 |
223,776 | 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 | 369 | 8 |
223,777 | 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 | 893 | 3 |
223,778 | 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 . | 125 | 7 |
223,779 | 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 . | 74 | 6 |
223,780 | 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 . | 280 | 8 |
223,781 | 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 . | 276 | 7 |
223,782 | 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 . | 652 | 10 |
223,783 | 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 . | 85 | 11 |
223,784 | 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 . | 351 | 11 |
223,785 | 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 . | 90 | 13 |
223,786 | 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 . | 61 | 13 |
223,787 | 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 . | 96 | 9 |
223,788 | 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 . | 55 | 12 |
223,789 | 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 . | 64 | 11 |
223,790 | 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 . | 505 | 10 |
223,791 | 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 . | 834 | 10 |
223,792 | 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 . | 87 | 10 |
223,793 | 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 . | 366 | 10 |
223,794 | 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 . | 234 | 9 |
223,795 | 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 . | 80 | 16 |
223,796 | 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 | 117 | 15 |
223,797 | 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 . | 166 | 8 |
223,798 | 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 . | 144 | 8 |
223,799 | 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 . | 193 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.