repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
rochacbruno/dynaconf
dynaconf/base.py
Settings.load_file
def load_file(self, path=None, env=None, silent=True, key=None): """Programmatically load files from ``path``. :param path: A single filename or a file list :param env: Which env to load from file (default current_env) :param silent: Should raise errors? :param key: Load a single key? """ env = (env or self.current_env).upper() files = ensure_a_list(path) if files: self.logger.debug("Got %s files to process", files) already_loaded = set() for _filename in files: self.logger.debug("Processing file %s", _filename) filepath = os.path.join(self._root_path, _filename) self.logger.debug("File path is %s", filepath) # Handle possible *.globs sorted alphanumeric for path in sorted(glob.glob(filepath)): self.logger.debug("Loading %s", path) if path in already_loaded: # pragma: no cover self.logger.debug("Skipping %s, already loaded", path) continue settings_loader( obj=self, env=env, silent=silent, key=key, filename=path, ) already_loaded.add(path) if not already_loaded: self.logger.warning( "Not able to locate the files %s to load", files )
python
def load_file(self, path=None, env=None, silent=True, key=None): """Programmatically load files from ``path``. :param path: A single filename or a file list :param env: Which env to load from file (default current_env) :param silent: Should raise errors? :param key: Load a single key? """ env = (env or self.current_env).upper() files = ensure_a_list(path) if files: self.logger.debug("Got %s files to process", files) already_loaded = set() for _filename in files: self.logger.debug("Processing file %s", _filename) filepath = os.path.join(self._root_path, _filename) self.logger.debug("File path is %s", filepath) # Handle possible *.globs sorted alphanumeric for path in sorted(glob.glob(filepath)): self.logger.debug("Loading %s", path) if path in already_loaded: # pragma: no cover self.logger.debug("Skipping %s, already loaded", path) continue settings_loader( obj=self, env=env, silent=silent, key=key, filename=path, ) already_loaded.add(path) if not already_loaded: self.logger.warning( "Not able to locate the files %s to load", files )
[ "def", "load_file", "(", "self", ",", "path", "=", "None", ",", "env", "=", "None", ",", "silent", "=", "True", ",", "key", "=", "None", ")", ":", "env", "=", "(", "env", "or", "self", ".", "current_env", ")", ".", "upper", "(", ")", "files", "...
Programmatically load files from ``path``. :param path: A single filename or a file list :param env: Which env to load from file (default current_env) :param silent: Should raise errors? :param key: Load a single key?
[ "Programmatically", "load", "files", "from", "path", "." ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L765-L799
train
224,600
rochacbruno/dynaconf
dynaconf/base.py
Settings._root_path
def _root_path(self): """ROOT_PATH_FOR_DYNACONF or the path of first loaded file or '.'""" if self.ROOT_PATH_FOR_DYNACONF is not None: return self.ROOT_PATH_FOR_DYNACONF elif self._loaded_files: # called once root_path = os.path.dirname(self._loaded_files[0]) self.set("ROOT_PATH_FOR_DYNACONF", root_path) return root_path
python
def _root_path(self): """ROOT_PATH_FOR_DYNACONF or the path of first loaded file or '.'""" if self.ROOT_PATH_FOR_DYNACONF is not None: return self.ROOT_PATH_FOR_DYNACONF elif self._loaded_files: # called once root_path = os.path.dirname(self._loaded_files[0]) self.set("ROOT_PATH_FOR_DYNACONF", root_path) return root_path
[ "def", "_root_path", "(", "self", ")", ":", "if", "self", ".", "ROOT_PATH_FOR_DYNACONF", "is", "not", "None", ":", "return", "self", ".", "ROOT_PATH_FOR_DYNACONF", "elif", "self", ".", "_loaded_files", ":", "# called once", "root_path", "=", "os", ".", "path",...
ROOT_PATH_FOR_DYNACONF or the path of first loaded file or '.
[ "ROOT_PATH_FOR_DYNACONF", "or", "the", "path", "of", "first", "loaded", "file", "or", "." ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L802-L809
train
224,601
rochacbruno/dynaconf
dynaconf/base.py
Settings.load_extra_yaml
def load_extra_yaml(self, env, silent, key): """This is deprecated, kept for compat .. deprecated:: 1.0.0 Use multiple settings or INCLUDES_FOR_DYNACONF files instead. """ if self.get("YAML") is not None: self.logger.warning( "The use of YAML var is deprecated, please define multiple " "filepaths instead: " "e.g: SETTINGS_FILE_FOR_DYNACONF = " "'settings.py,settings.yaml,settings.toml' or " "INCLUDES_FOR_DYNACONF=['path.toml', 'folder/*']" ) yaml_loader.load( self, env=env, filename=self.find_file(self.get("YAML")), silent=silent, key=key, )
python
def load_extra_yaml(self, env, silent, key): """This is deprecated, kept for compat .. deprecated:: 1.0.0 Use multiple settings or INCLUDES_FOR_DYNACONF files instead. """ if self.get("YAML") is not None: self.logger.warning( "The use of YAML var is deprecated, please define multiple " "filepaths instead: " "e.g: SETTINGS_FILE_FOR_DYNACONF = " "'settings.py,settings.yaml,settings.toml' or " "INCLUDES_FOR_DYNACONF=['path.toml', 'folder/*']" ) yaml_loader.load( self, env=env, filename=self.find_file(self.get("YAML")), silent=silent, key=key, )
[ "def", "load_extra_yaml", "(", "self", ",", "env", ",", "silent", ",", "key", ")", ":", "if", "self", ".", "get", "(", "\"YAML\"", ")", "is", "not", "None", ":", "self", ".", "logger", ".", "warning", "(", "\"The use of YAML var is deprecated, please define ...
This is deprecated, kept for compat .. deprecated:: 1.0.0 Use multiple settings or INCLUDES_FOR_DYNACONF files instead.
[ "This", "is", "deprecated", "kept", "for", "compat" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L811-L831
train
224,602
rochacbruno/dynaconf
dynaconf/base.py
Settings.path_for
def path_for(self, *args): """Path containing _root_path""" 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)
python
def path_for(self, *args): """Path containing _root_path""" 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)
[ "def", "path_for", "(", "self", ",", "*", "args", ")", ":", "if", "args", "and", "args", "[", "0", "]", ".", "startswith", "(", "os", ".", "path", ".", "sep", ")", ":", "return", "os", ".", "path", ".", "join", "(", "*", "args", ")", "return", ...
Path containing _root_path
[ "Path", "containing", "_root_path" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L833-L837
train
224,603
rochacbruno/dynaconf
dynaconf/base.py
Settings.validators
def validators(self): """Gets or creates validator wrapper""" if not hasattr(self, "_validators"): self._validators = ValidatorList(self) return self._validators
python
def validators(self): """Gets or creates validator wrapper""" if not hasattr(self, "_validators"): self._validators = ValidatorList(self) return self._validators
[ "def", "validators", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_validators\"", ")", ":", "self", ".", "_validators", "=", "ValidatorList", "(", "self", ")", "return", "self", ".", "_validators" ]
Gets or creates validator wrapper
[ "Gets", "or", "creates", "validator", "wrapper" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L847-L851
train
224,604
rochacbruno/dynaconf
dynaconf/base.py
Settings.populate_obj
def populate_obj(self, obj, keys=None): """Given the `obj` populate it using self.store items.""" 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)
python
def populate_obj(self, obj, keys=None): """Given the `obj` populate it using self.store items.""" 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)
[ "def", "populate_obj", "(", "self", ",", "obj", ",", "keys", "=", "None", ")", ":", "keys", "=", "keys", "or", "self", ".", "keys", "(", ")", "for", "key", "in", "keys", ":", "key", "=", "key", ".", "upper", "(", ")", "value", "=", "self", ".",...
Given the `obj` populate it using self.store items.
[ "Given", "the", "obj", "populate", "it", "using", "self", ".", "store", "items", "." ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L878-L885
train
224,605
rochacbruno/dynaconf
dynaconf/loaders/__init__.py
default_loader
def default_loader(obj, defaults=None): """Loads default settings and check if there are overridings exported as environment variables""" 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)
python
def default_loader(obj, defaults=None): """Loads default settings and check if there are overridings exported as environment variables""" 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)
[ "def", "default_loader", "(", "obj", ",", "defaults", "=", "None", ")", ":", "defaults", "=", "defaults", "or", "{", "}", "default_settings_values", "=", "{", "key", ":", "value", "for", "key", ",", "value", "in", "default_settings", ".", "__dict__", ".", ...
Loads default settings and check if there are overridings exported as environment variables
[ "Loads", "default", "settings", "and", "check", "if", "there", "are", "overridings", "exported", "as", "environment", "variables" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/__init__.py#L15-L56
train
224,606
rochacbruno/dynaconf
dynaconf/loaders/__init__.py
settings_loader
def settings_loader( obj, settings_module=None, env=None, silent=True, key=None, filename=None ): """Loads from defined settings module :param obj: A dynaconf instance :param settings_module: A path or a list of paths e.g settings.toml :param env: Env to look for data defaults: development :param silent: Boolean to raise loading errors :param key: Load a single key if provided :param filename: optional filename to override the settings_module """ if filename is None: settings_module = settings_module or obj.settings_module if not settings_module: # pragma: no cover return files = ensure_a_list(settings_module) else: files = ensure_a_list(filename) files.extend(ensure_a_list(obj.get("SECRETS_FOR_DYNACONF", None))) found_files = [] modules_names = [] for item in files: if item.endswith(ct.ALL_EXTENSIONS + (".py",)): p_root = obj._root_path or ( os.path.dirname(found_files[0]) if found_files else None ) found = obj.find_file(item, project_root=p_root) if found: found_files.append(found) else: # a bare python module name w/o extension modules_names.append(item) enabled_core_loaders = obj.get("CORE_LOADERS_FOR_DYNACONF") for mod_file in modules_names + found_files: # can be set to multiple files settings.py,settings.yaml,... # Cascade all loaders loaders = [ {"ext": ct.YAML_EXTENSIONS, "name": "YAML", "loader": yaml_loader}, {"ext": ct.TOML_EXTENSIONS, "name": "TOML", "loader": toml_loader}, {"ext": ct.INI_EXTENSIONS, "name": "INI", "loader": ini_loader}, {"ext": ct.JSON_EXTENSIONS, "name": "JSON", "loader": json_loader}, ] for loader in loaders: if loader["name"] not in enabled_core_loaders: continue if mod_file.endswith(loader["ext"]): loader["loader"].load( obj, filename=mod_file, env=env, silent=silent, key=key ) continue if mod_file.endswith(ct.ALL_EXTENSIONS): continue if "PY" not in enabled_core_loaders: # pyloader is disabled continue # must be Python file or module # load from default defined module settings.py or .secrets.py if exists py_loader.load(obj, mod_file, key=key) # load from the current env e.g: development_settings.py env = env or obj.current_env if mod_file.endswith(".py"): if ".secrets.py" == mod_file: tmpl = ".{0}_{1}{2}" mod_file = "secrets.py" else: tmpl = "{0}_{1}{2}" dirname = os.path.dirname(mod_file) filename, extension = os.path.splitext(os.path.basename(mod_file)) new_filename = tmpl.format(env.lower(), filename, extension) env_mod_file = os.path.join(dirname, new_filename) global_filename = tmpl.format("global", filename, extension) global_mod_file = os.path.join(dirname, global_filename) else: env_mod_file = "{0}_{1}".format(env.lower(), mod_file) global_mod_file = "{0}_{1}".format("global", mod_file) py_loader.load( obj, env_mod_file, identifier="py_{0}".format(env.upper()), silent=True, key=key, ) # load from global_settings.py py_loader.load( obj, global_mod_file, identifier="py_global", silent=True, key=key )
python
def settings_loader( obj, settings_module=None, env=None, silent=True, key=None, filename=None ): """Loads from defined settings module :param obj: A dynaconf instance :param settings_module: A path or a list of paths e.g settings.toml :param env: Env to look for data defaults: development :param silent: Boolean to raise loading errors :param key: Load a single key if provided :param filename: optional filename to override the settings_module """ if filename is None: settings_module = settings_module or obj.settings_module if not settings_module: # pragma: no cover return files = ensure_a_list(settings_module) else: files = ensure_a_list(filename) files.extend(ensure_a_list(obj.get("SECRETS_FOR_DYNACONF", None))) found_files = [] modules_names = [] for item in files: if item.endswith(ct.ALL_EXTENSIONS + (".py",)): p_root = obj._root_path or ( os.path.dirname(found_files[0]) if found_files else None ) found = obj.find_file(item, project_root=p_root) if found: found_files.append(found) else: # a bare python module name w/o extension modules_names.append(item) enabled_core_loaders = obj.get("CORE_LOADERS_FOR_DYNACONF") for mod_file in modules_names + found_files: # can be set to multiple files settings.py,settings.yaml,... # Cascade all loaders loaders = [ {"ext": ct.YAML_EXTENSIONS, "name": "YAML", "loader": yaml_loader}, {"ext": ct.TOML_EXTENSIONS, "name": "TOML", "loader": toml_loader}, {"ext": ct.INI_EXTENSIONS, "name": "INI", "loader": ini_loader}, {"ext": ct.JSON_EXTENSIONS, "name": "JSON", "loader": json_loader}, ] for loader in loaders: if loader["name"] not in enabled_core_loaders: continue if mod_file.endswith(loader["ext"]): loader["loader"].load( obj, filename=mod_file, env=env, silent=silent, key=key ) continue if mod_file.endswith(ct.ALL_EXTENSIONS): continue if "PY" not in enabled_core_loaders: # pyloader is disabled continue # must be Python file or module # load from default defined module settings.py or .secrets.py if exists py_loader.load(obj, mod_file, key=key) # load from the current env e.g: development_settings.py env = env or obj.current_env if mod_file.endswith(".py"): if ".secrets.py" == mod_file: tmpl = ".{0}_{1}{2}" mod_file = "secrets.py" else: tmpl = "{0}_{1}{2}" dirname = os.path.dirname(mod_file) filename, extension = os.path.splitext(os.path.basename(mod_file)) new_filename = tmpl.format(env.lower(), filename, extension) env_mod_file = os.path.join(dirname, new_filename) global_filename = tmpl.format("global", filename, extension) global_mod_file = os.path.join(dirname, global_filename) else: env_mod_file = "{0}_{1}".format(env.lower(), mod_file) global_mod_file = "{0}_{1}".format("global", mod_file) py_loader.load( obj, env_mod_file, identifier="py_{0}".format(env.upper()), silent=True, key=key, ) # load from global_settings.py py_loader.load( obj, global_mod_file, identifier="py_global", silent=True, key=key )
[ "def", "settings_loader", "(", "obj", ",", "settings_module", "=", "None", ",", "env", "=", "None", ",", "silent", "=", "True", ",", "key", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "settings_module", "="...
Loads from defined settings module :param obj: A dynaconf instance :param settings_module: A path or a list of paths e.g settings.toml :param env: Env to look for data defaults: development :param silent: Boolean to raise loading errors :param key: Load a single key if provided :param filename: optional filename to override the settings_module
[ "Loads", "from", "defined", "settings", "module" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/__init__.py#L59-L159
train
224,607
rochacbruno/dynaconf
dynaconf/loaders/__init__.py
enable_external_loaders
def enable_external_loaders(obj): """Enable external service loaders like `VAULT_` and `REDIS_` looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF` """ 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)
python
def enable_external_loaders(obj): """Enable external service loaders like `VAULT_` and `REDIS_` looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF` """ 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)
[ "def", "enable_external_loaders", "(", "obj", ")", ":", "for", "name", ",", "loader", "in", "ct", ".", "EXTERNAL_LOADERS", ".", "items", "(", ")", ":", "enabled", "=", "getattr", "(", "obj", ",", "\"{}_ENABLED_FOR_DYNACONF\"", ".", "format", "(", "name", "...
Enable external service loaders like `VAULT_` and `REDIS_` looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF`
[ "Enable", "external", "service", "loaders", "like", "VAULT_", "and", "REDIS_", "looks", "forenv", "variables", "like", "REDIS_ENABLED_FOR_DYNACONF" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/__init__.py#L162-L176
train
224,608
rochacbruno/dynaconf
dynaconf/utils/files.py
_walk_to_root
def _walk_to_root(path, break_at=None): """ Directories starting from the given directory up to the root or break_at """ 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
python
def _walk_to_root(path, break_at=None): """ Directories starting from the given directory up to the root or break_at """ 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
[ "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", ...
Directories starting from the given directory up to the root or break_at
[ "Directories", "starting", "from", "the", "given", "directory", "up", "to", "the", "root", "or", "break_at" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/files.py#L12-L33
train
224,609
rochacbruno/dynaconf
dynaconf/utils/files.py
find_file
def find_file(filename=".env", project_root=None, skip_files=None, **kwargs): """Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise. This function will build a `search_tree` based on: - Project_root if specified - Invoked script location and its parents until root - Current working directory For each path in the `search_tree` it will also look for an aditional `./config` folder. """ 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 ""
python
def find_file(filename=".env", project_root=None, skip_files=None, **kwargs): """Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise. This function will build a `search_tree` based on: - Project_root if specified - Invoked script location and its parents until root - Current working directory For each path in the `search_tree` it will also look for an aditional `./config` folder. """ 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 ""
[ "def", "find_file", "(", "filename", "=", "\".env\"", ",", "project_root", "=", "None", ",", "skip_files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "search_tree", "=", "[", "]", "work_dir", "=", "os", ".", "getcwd", "(", ")", "skip_files", "=", ...
Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise. This function will build a `search_tree` based on: - Project_root if specified - Invoked script location and its parents until root - Current working directory For each path in the `search_tree` it will also look for an aditional `./config` folder.
[ "Search", "in", "increasingly", "higher", "folders", "for", "the", "given", "file", "Returns", "path", "to", "the", "file", "if", "found", "or", "an", "empty", "string", "otherwise", "." ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/files.py#L39-L88
train
224,610
rochacbruno/dynaconf
dynaconf/validator.py
Validator.validate
def validate(self, settings): """Raise ValidationError if invalid""" 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)
python
def validate(self, settings): """Raise ValidationError if invalid""" 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)
[ "def", "validate", "(", "self", ",", "settings", ")", ":", "if", "self", ".", "envs", "is", "None", ":", "self", ".", "envs", "=", "[", "settings", ".", "current_env", "]", "if", "self", ".", "when", "is", "not", "None", ":", "try", ":", "# inherit...
Raise ValidationError if invalid
[ "Raise", "ValidationError", "if", "invalid" ]
5a7cc8f8252251cbdf4f4112965801f9dfe2831d
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/validator.py#L86-L113
train
224,611
django-json-api/django-rest-framework-json-api
rest_framework_json_api/serializers.py
ModelSerializer.to_representation
def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ 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
python
def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ 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
[ "def", "to_representation", "(", "self", ",", "instance", ")", ":", "ret", "=", "OrderedDict", "(", ")", "readable_fields", "=", "[", "field", "for", "field", "in", "self", ".", "fields", ".", "values", "(", ")", "if", "not", "field", ".", "write_only", ...
Object instance -> Dict of primitive datatypes.
[ "Object", "instance", "-", ">", "Dict", "of", "primitive", "datatypes", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/serializers.py#L175-L192
train
224,612
django-json-api/django-rest-framework-json-api
rest_framework_json_api/renderers.py
JSONRenderer.extract_attributes
def extract_attributes(cls, fields, resource): """ Builds the `attributes` object of the JSON API resource object. """ 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)
python
def extract_attributes(cls, fields, resource): """ Builds the `attributes` object of the JSON API resource object. """ 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)
[ "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 s...
Builds the `attributes` object of the JSON API resource object.
[ "Builds", "the", "attributes", "object", "of", "the", "JSON", "API", "resource", "object", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L50-L81
train
224,613
django-json-api/django-rest-framework-json-api
rest_framework_json_api/renderers.py
JSONRenderer.extract_relation_instance
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 name of field's source. """ 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
python
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 name of field's source. """ 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
[ "def", "extract_relation_instance", "(", "cls", ",", "field_name", ",", "field", ",", "resource_instance", ",", "serializer", ")", ":", "relation_instance", "=", "None", "try", ":", "relation_instance", "=", "getattr", "(", "resource_instance", ",", "field_name", ...
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 name of field's source.
[ "Determines", "what", "instance", "represents", "given", "relation", "and", "extracts", "it", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L299-L326
train
224,614
django-json-api/django-rest-framework-json-api
rest_framework_json_api/renderers.py
JSONRenderer.extract_meta
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 = 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
python
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 = 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
[ "def", "extract_meta", "(", "cls", ",", "serializer", ",", "resource", ")", ":", "if", "hasattr", "(", "serializer", ",", "'child'", ")", ":", "meta", "=", "getattr", "(", "serializer", ".", "child", ",", "'Meta'", ",", "None", ")", "else", ":", "meta"...
Gathers the data from serializer fields specified in meta_fields and adds it to the meta object.
[ "Gathers", "the", "data", "from", "serializer", "fields", "specified", "in", "meta_fields", "and", "adds", "it", "to", "the", "meta", "object", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L458-L473
train
224,615
django-json-api/django-rest-framework-json-api
rest_framework_json_api/renderers.py
JSONRenderer.extract_root_meta
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(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
python
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(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
[ "def", "extract_root_meta", "(", "cls", ",", "serializer", ",", "resource", ")", ":", "many", "=", "False", "if", "hasattr", "(", "serializer", ",", "'child'", ")", ":", "many", "=", "True", "serializer", "=", "serializer", ".", "child", "data", "=", "{"...
Calls a `get_root_meta` function on a serializer, if it exists.
[ "Calls", "a", "get_root_meta", "function", "on", "a", "serializer", "if", "it", "exists", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L476-L490
train
224,616
django-json-api/django-rest-framework-json-api
rest_framework_json_api/views.py
PrefetchForIncludesHelperMixin.get_queryset
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 called with ?include=author it will prefetch author and authorbio class MyViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() prefetch_for_includes = { '__all__': [], 'author': ['author', 'author__authorbio'], 'category.section': ['category'] } """ 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
python
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 called with ?include=author it will prefetch author and authorbio class MyViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() prefetch_for_includes = { '__all__': [], 'author': ['author', 'author__authorbio'], 'category.section': ['category'] } """ 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
[ "def", "get_queryset", "(", "self", ")", ":", "qs", "=", "super", "(", "PrefetchForIncludesHelperMixin", ",", "self", ")", ".", "get_queryset", "(", ")", "if", "not", "hasattr", "(", "self", ",", "'prefetch_for_includes'", ")", ":", "return", "qs", "includes...
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 called with ?include=author it will prefetch author and authorbio class MyViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() prefetch_for_includes = { '__all__': [], 'author': ['author', 'author__authorbio'], 'category.section': ['category'] }
[ "This", "viewset", "provides", "a", "helper", "attribute", "to", "prefetch", "related", "models", "based", "on", "the", "include", "specified", "in", "the", "URL", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/views.py#L34-L62
train
224,617
django-json-api/django-rest-framework-json-api
rest_framework_json_api/views.py
AutoPrefetchMixin.get_queryset
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: 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
python
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: 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
[ "def", "get_queryset", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "qs", "=", "super", "(", "AutoPrefetchMixin", ",", "self", ")", ".", "get_queryset", "(", "*", "args", ",", "*", "*", "kwargs", ")", "included_resources", "=", "...
This mixin adds automatic prefetching for OneToOne and ManyToMany fields.
[ "This", "mixin", "adds", "automatic", "prefetching", "for", "OneToOne", "and", "ManyToMany", "fields", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/views.py#L66-L109
train
224,618
django-json-api/django-rest-framework-json-api
rest_framework_json_api/views.py
RelationshipView.get_url
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. """ # 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)
python
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. """ # 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)
[ "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", ...
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.
[ "Given", "a", "name", "view", "name", "and", "kwargs", "return", "the", "URL", "that", "hyperlinks", "to", "the", "object", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/views.py#L221-L248
train
224,619
django-json-api/django-rest-framework-json-api
rest_framework_json_api/utils.py
get_resource_name
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 # 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
python
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 # 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
[ "def", "get_resource_name", "(", "context", ",", "expand_polymorphic_types", "=", "False", ")", ":", "from", "rest_framework_json_api", ".", "serializers", "import", "PolymorphicModelSerializer", "view", "=", "context", ".", "get", "(", "'view'", ")", "# Sanity check ...
Return the name of a resource.
[ "Return", "the", "name", "of", "a", "resource", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L36-L79
train
224,620
django-json-api/django-rest-framework-json-api
rest_framework_json_api/utils.py
format_field_names
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_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
python
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_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
[ "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", ...
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'
[ "Takes", "a", "dict", "and", "returns", "it", "with", "formatted", "keys", "as", "set", "in", "format_type", "or", "JSON_API_FORMAT_FIELD_NAMES" ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L101-L118
train
224,621
django-json-api/django-rest-framework-json-api
rest_framework_json_api/utils.py
_format_object
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
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)
[ "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", ...
Depending on settings calls either `format_keys` or `format_field_names`
[ "Depending", "on", "settings", "calls", "either", "format_keys", "or", "format_field_names" ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L121-L127
train
224,622
django-json-api/django-rest-framework-json-api
rest_framework_json_api/utils.py
get_included_resources
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_resources_from_serializer(serializer)
python
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_resources_from_serializer(serializer)
[ "def", "get_included_resources", "(", "request", ",", "serializer", "=", "None", ")", ":", "include_resources_param", "=", "request", ".", "query_params", ".", "get", "(", "'include'", ")", "if", "request", "else", "None", "if", "include_resources_param", ":", "...
Build a list of included resources.
[ "Build", "a", "list", "of", "included", "resources", "." ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L327-L333
train
224,623
django-json-api/django-rest-framework-json-api
rest_framework_json_api/parsers.py
JSONParser.parse
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 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
python
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 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
[ "def", "parse", "(", "self", ",", "stream", ",", "media_type", "=", "None", ",", "parser_context", "=", "None", ")", ":", "result", "=", "super", "(", "JSONParser", ",", "self", ")", ".", "parse", "(", "stream", ",", "media_type", "=", "media_type", ",...
Parses the incoming bytestream as JSON and returns the resulting data
[ "Parses", "the", "incoming", "bytestream", "as", "JSON", "and", "returns", "the", "resulting", "data" ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/parsers.py#L85-L153
train
224,624
django-json-api/django-rest-framework-json-api
rest_framework_json_api/relations.py
ResourceRelatedField.get_resource_type_from_included_serializer
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 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
python
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 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
[ "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", ...
Check to see it this resource has a different resource_name when included and return that name, or None
[ "Check", "to", "see", "it", "this", "resource", "has", "a", "different", "resource_name", "when", "included", "and", "return", "that", "name", "or", "None" ]
de7021f9e011615ce8b65d0cb38227c6c12721b6
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/relations.py#L255-L274
train
224,625
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/signature.py
sign_plaintext
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 equivalent protections). It does not utilize the signature base string or the "oauth_timestamp" and "oauth_nonce" parameters. .. _`section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4 """ # 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
python
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 equivalent protections). It does not utilize the signature base string or the "oauth_timestamp" and "oauth_nonce" parameters. .. _`section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4 """ # 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
[ "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.i...
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 equivalent protections). It does not utilize the signature base string or the "oauth_timestamp" and "oauth_nonce" parameters. .. _`section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4
[ "Sign", "a", "request", "using", "plaintext", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/signature.py#L595-L627
train
224,626
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/signature.py
verify_hmac_sha1
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 attribute MUST be an absolute URI whose netloc part identifies the origin server or gateway on which the resource resides. Any Host item of the request argument's headers dict attribute will be ignored. .. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2 """ 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
python
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 attribute MUST be an absolute URI whose netloc part identifies the origin server or gateway on which the resource resides. Any Host item of the request argument's headers dict attribute will be ignored. .. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2 """ 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
[ "def", "verify_hmac_sha1", "(", "request", ",", "client_secret", "=", "None", ",", "resource_owner_secret", "=", "None", ")", ":", "norm_params", "=", "normalize_parameters", "(", "request", ".", "params", ")", "bs_uri", "=", "base_string_uri", "(", "request", "...
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 attribute MUST be an absolute URI whose netloc part identifies the origin server or gateway on which the resource resides. Any Host item of the request argument's headers dict attribute will be ignored. .. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2
[ "Verify", "a", "HMAC", "-", "SHA1", "signature", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/signature.py#L634-L661
train
224,627
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/signature.py
verify_plaintext
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_string_equals(signature, request.signature) if not match: log.debug('Verify PLAINTEXT failed') return match
python
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_string_equals(signature, request.signature) if not match: log.debug('Verify PLAINTEXT failed') return match
[ "def", "verify_plaintext", "(", "request", ",", "client_secret", "=", "None", ",", "resource_owner_secret", "=", "None", ")", ":", "signature", "=", "sign_plaintext", "(", "client_secret", ",", "resource_owner_secret", ")", "match", "=", "safe_string_equals", "(", ...
Verify a PLAINTEXT signature. Per `section 3.4`_ of the spec. .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
[ "Verify", "a", "PLAINTEXT", "signature", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/signature.py#L702-L713
train
224,628
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/authorization.py
AuthorizationEndpoint.create_authorization_response
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_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :param credentials: A list of credentials to include in the verifier. :returns: A tuple of 3 elements. 1. A dict of headers to set on the response. 2. The response body as a string. 3. The response status code as an integer. If the callback URI tied to the current token is "oob", a response with a 200 status code will be returned. In this case, it may be desirable to modify the response to better display the verifier to the client. An example of an authorization request:: >>> from your_validator import your_validator >>> from oauthlib.oauth1 import AuthorizationEndpoint >>> endpoint = AuthorizationEndpoint(your_validator) >>> h, b, s = endpoint.create_authorization_response( ... 'https://your.provider/authorize?oauth_token=...', ... credentials={ ... 'extra': 'argument', ... }) >>> h {'Location': 'https://the.client/callback?oauth_verifier=...&extra=argument'} >>> b None >>> s 302 An example of a request with an "oob" callback:: >>> from your_validator import your_validator >>> from oauthlib.oauth1 import AuthorizationEndpoint >>> endpoint = AuthorizationEndpoint(your_validator) >>> h, b, s = endpoint.create_authorization_response( ... 'https://your.provider/authorize?foo=bar', ... credentials={ ... 'extra': 'argument', ... }) >>> h {'Content-Type': 'application/x-www-form-urlencoded'} >>> b 'oauth_verifier=...&extra=argument' >>> s 200 """ 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
python
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_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :param credentials: A list of credentials to include in the verifier. :returns: A tuple of 3 elements. 1. A dict of headers to set on the response. 2. The response body as a string. 3. The response status code as an integer. If the callback URI tied to the current token is "oob", a response with a 200 status code will be returned. In this case, it may be desirable to modify the response to better display the verifier to the client. An example of an authorization request:: >>> from your_validator import your_validator >>> from oauthlib.oauth1 import AuthorizationEndpoint >>> endpoint = AuthorizationEndpoint(your_validator) >>> h, b, s = endpoint.create_authorization_response( ... 'https://your.provider/authorize?oauth_token=...', ... credentials={ ... 'extra': 'argument', ... }) >>> h {'Location': 'https://the.client/callback?oauth_verifier=...&extra=argument'} >>> b None >>> s 302 An example of a request with an "oob" callback:: >>> from your_validator import your_validator >>> from oauthlib.oauth1 import AuthorizationEndpoint >>> endpoint = AuthorizationEndpoint(your_validator) >>> h, b, s = endpoint.create_authorization_response( ... 'https://your.provider/authorize?foo=bar', ... credentials={ ... 'extra': 'argument', ... }) >>> h {'Content-Type': 'application/x-www-form-urlencoded'} >>> b 'oauth_verifier=...&extra=argument' >>> s 200 """ 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
[ "def", "create_authorization_response", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "realms", "=", "None", ",", "credentials", "=", "None", ")", ":", "request", "=", "self", ".", ...
Create an authorization response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :param credentials: A list of credentials to include in the verifier. :returns: A tuple of 3 elements. 1. A dict of headers to set on the response. 2. The response body as a string. 3. The response status code as an integer. If the callback URI tied to the current token is "oob", a response with a 200 status code will be returned. In this case, it may be desirable to modify the response to better display the verifier to the client. An example of an authorization request:: >>> from your_validator import your_validator >>> from oauthlib.oauth1 import AuthorizationEndpoint >>> endpoint = AuthorizationEndpoint(your_validator) >>> h, b, s = endpoint.create_authorization_response( ... 'https://your.provider/authorize?oauth_token=...', ... credentials={ ... 'extra': 'argument', ... }) >>> h {'Location': 'https://the.client/callback?oauth_verifier=...&extra=argument'} >>> b None >>> s 302 An example of a request with an "oob" callback:: >>> from your_validator import your_validator >>> from oauthlib.oauth1 import AuthorizationEndpoint >>> endpoint = AuthorizationEndpoint(your_validator) >>> h, b, s = endpoint.create_authorization_response( ... 'https://your.provider/authorize?foo=bar', ... credentials={ ... 'extra': 'argument', ... }) >>> h {'Content-Type': 'application/x-www-form-urlencoded'} >>> b 'oauth_verifier=...&extra=argument' >>> s 200
[ "Create", "an", "authorization", "response", "with", "a", "new", "request", "token", "if", "valid", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/authorization.py#L59-L139
train
224,629
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/authorization.py
AuthorizationEndpoint.get_realms_and_credentials
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, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns: A tuple of 2 elements. 1. A list of request realms. 2. A dict of credentials which may be useful in creating the authorization form. """ 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}
python
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, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns: A tuple of 2 elements. 1. A list of request realms. 2. A dict of credentials which may be useful in creating the authorization form. """ 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}
[ "def", "get_realms_and_credentials", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "request", "=", "self", ".", "_create_request", "(", "uri", ",", "http_method", "=", "http_meth...
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, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns: A tuple of 2 elements. 1. A list of request realms. 2. A dict of credentials which may be useful in creating the authorization form.
[ "Fetch", "realms", "and", "credentials", "for", "the", "presented", "request", "token", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/authorization.py#L141-L163
train
224,630
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/introspect.py
IntrospectEndpoint.create_introspect_response
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 an introspection response indicating the token is not active as described in Section 2.2. """ 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
python
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 an introspection response indicating the token is not active as described in Section 2.2. """ 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
[ "def", "create_introspect_response", "(", "self", ",", "uri", ",", "http_method", "=", "'POST'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "resp_headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Cache-Control'", ":"...
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 an introspection response indicating the token is not active as described in Section 2.2.
[ "Create", "introspect", "valid", "or", "invalid", "response" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/introspect.py#L50-L82
train
224,631
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/service_application.py
ServiceApplicationClient.prepare_request_body
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): """Create and add a JWT assertion to the request body. :param private_key: Private key used for signing and encrypting. Must be given as a string. :param subject: (sub) The principal that is the subject of the JWT, i.e. which user is the token requested on behalf of. For example, ``foo@example.com. :param issuer: (iss) The JWT MUST contain an "iss" (issuer) claim that contains a unique identifier for the entity that issued the JWT. For example, ``your-client@provider.com``. :param audience: (aud) A value identifying the authorization server as an intended audience, e.g. ``https://provider.com/oauth2/token``. :param expires_at: A unix expiration timestamp for the JWT. Defaults to an hour from now, i.e. ``time.time() + 3600``. :param issued_at: A unix timestamp of when the JWT was created. Defaults to now, i.e. ``time.time()``. :param extra_claims: A dict of additional claims to include in the JWT. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: The scope of the access request. :param include_client_id: `True` to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. False otherwise (default). :type include_client_id: Boolean :param not_before: A unix timestamp after which the JWT may be used. Not included unless provided. * :param jwt_id: A unique JWT token identifier. Not included unless provided. * :param kwargs: Extra credentials to include in the token request. Parameters marked with a `*` above are not explicit arguments in the function signature, but are specially documented arguments for items appearing in the generic `**kwargs` keyworded input. The "scope" parameter may be used, as defined in the Assertion Framework for OAuth 2.0 Client Authentication and Authorization Grants [I-D.ietf-oauth-assertions] specification, to indicate the requested scope. Authentication of the client is optional, as described in `Section 3.2.1`_ of OAuth 2.0 [RFC6749] and consequently, the "client_id" is only needed when a form of client authentication that relies on the parameter is used. The following non-normative example demonstrates an Access Token Request with a JWT as an authorization grant (with extra line breaks for display purposes only): .. code-block: http POST /token.oauth2 HTTP/1.1 Host: as.example.com Content-Type: application/x-www-form-urlencoded grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer &assertion=eyJhbGciOiJFUzI1NiJ9. eyJpc3Mi[...omitted for brevity...]. J9l-ZhwP[...omitted for brevity...] .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 """ 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)
python
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): """Create and add a JWT assertion to the request body. :param private_key: Private key used for signing and encrypting. Must be given as a string. :param subject: (sub) The principal that is the subject of the JWT, i.e. which user is the token requested on behalf of. For example, ``foo@example.com. :param issuer: (iss) The JWT MUST contain an "iss" (issuer) claim that contains a unique identifier for the entity that issued the JWT. For example, ``your-client@provider.com``. :param audience: (aud) A value identifying the authorization server as an intended audience, e.g. ``https://provider.com/oauth2/token``. :param expires_at: A unix expiration timestamp for the JWT. Defaults to an hour from now, i.e. ``time.time() + 3600``. :param issued_at: A unix timestamp of when the JWT was created. Defaults to now, i.e. ``time.time()``. :param extra_claims: A dict of additional claims to include in the JWT. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: The scope of the access request. :param include_client_id: `True` to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. False otherwise (default). :type include_client_id: Boolean :param not_before: A unix timestamp after which the JWT may be used. Not included unless provided. * :param jwt_id: A unique JWT token identifier. Not included unless provided. * :param kwargs: Extra credentials to include in the token request. Parameters marked with a `*` above are not explicit arguments in the function signature, but are specially documented arguments for items appearing in the generic `**kwargs` keyworded input. The "scope" parameter may be used, as defined in the Assertion Framework for OAuth 2.0 Client Authentication and Authorization Grants [I-D.ietf-oauth-assertions] specification, to indicate the requested scope. Authentication of the client is optional, as described in `Section 3.2.1`_ of OAuth 2.0 [RFC6749] and consequently, the "client_id" is only needed when a form of client authentication that relies on the parameter is used. The following non-normative example demonstrates an Access Token Request with a JWT as an authorization grant (with extra line breaks for display purposes only): .. code-block: http POST /token.oauth2 HTTP/1.1 Host: as.example.com Content-Type: application/x-www-form-urlencoded grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer &assertion=eyJhbGciOiJFUzI1NiJ9. eyJpc3Mi[...omitted for brevity...]. J9l-ZhwP[...omitted for brevity...] .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 """ 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)
[ "def", "prepare_request_body", "(", "self", ",", "private_key", "=", "None", ",", "subject", "=", "None", ",", "issuer", "=", "None", ",", "audience", "=", "None", ",", "expires_at", "=", "None", ",", "issued_at", "=", "None", ",", "extra_claims", "=", "...
Create and add a JWT assertion to the request body. :param private_key: Private key used for signing and encrypting. Must be given as a string. :param subject: (sub) The principal that is the subject of the JWT, i.e. which user is the token requested on behalf of. For example, ``foo@example.com. :param issuer: (iss) The JWT MUST contain an "iss" (issuer) claim that contains a unique identifier for the entity that issued the JWT. For example, ``your-client@provider.com``. :param audience: (aud) A value identifying the authorization server as an intended audience, e.g. ``https://provider.com/oauth2/token``. :param expires_at: A unix expiration timestamp for the JWT. Defaults to an hour from now, i.e. ``time.time() + 3600``. :param issued_at: A unix timestamp of when the JWT was created. Defaults to now, i.e. ``time.time()``. :param extra_claims: A dict of additional claims to include in the JWT. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: The scope of the access request. :param include_client_id: `True` to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. False otherwise (default). :type include_client_id: Boolean :param not_before: A unix timestamp after which the JWT may be used. Not included unless provided. * :param jwt_id: A unique JWT token identifier. Not included unless provided. * :param kwargs: Extra credentials to include in the token request. Parameters marked with a `*` above are not explicit arguments in the function signature, but are specially documented arguments for items appearing in the generic `**kwargs` keyworded input. The "scope" parameter may be used, as defined in the Assertion Framework for OAuth 2.0 Client Authentication and Authorization Grants [I-D.ietf-oauth-assertions] specification, to indicate the requested scope. Authentication of the client is optional, as described in `Section 3.2.1`_ of OAuth 2.0 [RFC6749] and consequently, the "client_id" is only needed when a form of client authentication that relies on the parameter is used. The following non-normative example demonstrates an Access Token Request with a JWT as an authorization grant (with extra line breaks for display purposes only): .. code-block: http POST /token.oauth2 HTTP/1.1 Host: as.example.com Content-Type: application/x-www-form-urlencoded grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer &assertion=eyJhbGciOiJFUzI1NiJ9. eyJpc3Mi[...omitted for brevity...]. J9l-ZhwP[...omitted for brevity...] .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1
[ "Create", "and", "add", "a", "JWT", "assertion", "to", "the", "request", "body", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/service_application.py#L66-L190
train
224,632
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
AuthorizationCodeGrant.create_authorization_code
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 request.state: grant['state'] = request.state log.debug('Created authorization code grant %r for request %r.', grant, request) return grant
python
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 request.state: grant['state'] = request.state log.debug('Created authorization code grant %r for request %r.', grant, request) return grant
[ "def", "create_authorization_code", "(", "self", ",", "request", ")", ":", "grant", "=", "{", "'code'", ":", "common", ".", "generate_token", "(", ")", "}", "if", "hasattr", "(", "request", ",", "'state'", ")", "and", "request", ".", "state", ":", "grant...
Generates an authorization grant represented as a dictionary. :param request: OAuthlib request. :type request: oauthlib.common.Request
[ "Generates", "an", "authorization", "grant", "represented", "as", "a", "dictionary", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L163-L175
train
224,633
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
AuthorizationCodeGrant.create_token_response
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) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. """ 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
python
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) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. """ 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
[ "def", "create_token_response", "(", "self", ",", "request", ",", "token_handler", ")", ":", "headers", "=", "self", ".", "_get_default_headers", "(", ")", "try", ":", "self", ".", "validate_token_request", "(", "request", ")", "log", ".", "debug", "(", "'To...
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) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken.
[ "Validate", "the", "authorization", "code", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L284-L316
train
224,634
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/authorization_code.py
AuthorizationCodeGrant.validate_authorization_request
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 included in the redirection URI and sent back to the client. Fatal errors occur when the client_id or redirect_uri is invalid or missing. These must be caught by the provider and handled, how this is done is outside of the scope of OAuthLib but showing an error page describing the issue is a good idea. :param request: OAuthlib request. :type request: oauthlib.common.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 log.debug('Validating redirection uri %s for client %s.', request.redirect_uri, request.client_id) # 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. # 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 query 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. request_info = {} for validator in self.custom_validators.pre_auth: request_info.update(validator(request)) # REQUIRED. if request.response_type is None: raise errors.MissingResponseTypeError(request=request) # Value MUST be set to "code" or one of the OpenID authorization code including # response_types "code token", "code id_token", "code token id_token" elif not 'code' in request.response_type and request.response_type != 'none': raise errors.UnsupportedResponseTypeError(request=request) 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. Validate PKCE request or reply with "error"/"invalid_request" # https://tools.ietf.org/html/rfc6749#section-4.4.1 if self.request_validator.is_pkce_required(request.client_id, request) is True: if request.code_challenge is None: raise errors.MissingCodeChallengeError(request=request) if request.code_challenge is not None: # OPTIONAL, defaults to "plain" if not present in the request. if request.code_challenge_method is None: request.code_challenge_method = "plain" if request.code_challenge_method not in self._code_challenge_methods: raise errors.UnsupportedCodeChallengeMethodError(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 }) for validator in self.custom_validators.post_auth: request_info.update(validator(request)) return request.scopes, request_info
python
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 included in the redirection URI and sent back to the client. Fatal errors occur when the client_id or redirect_uri is invalid or missing. These must be caught by the provider and handled, how this is done is outside of the scope of OAuthLib but showing an error page describing the issue is a good idea. :param request: OAuthlib request. :type request: oauthlib.common.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 log.debug('Validating redirection uri %s for client %s.', request.redirect_uri, request.client_id) # 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. # 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 query 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. request_info = {} for validator in self.custom_validators.pre_auth: request_info.update(validator(request)) # REQUIRED. if request.response_type is None: raise errors.MissingResponseTypeError(request=request) # Value MUST be set to "code" or one of the OpenID authorization code including # response_types "code token", "code id_token", "code token id_token" elif not 'code' in request.response_type and request.response_type != 'none': raise errors.UnsupportedResponseTypeError(request=request) 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. Validate PKCE request or reply with "error"/"invalid_request" # https://tools.ietf.org/html/rfc6749#section-4.4.1 if self.request_validator.is_pkce_required(request.client_id, request) is True: if request.code_challenge is None: raise errors.MissingCodeChallengeError(request=request) if request.code_challenge is not None: # OPTIONAL, defaults to "plain" if not present in the request. if request.code_challenge_method is None: request.code_challenge_method = "plain" if request.code_challenge_method not in self._code_challenge_methods: raise errors.UnsupportedCodeChallengeMethodError(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 }) for validator in self.custom_validators.post_auth: request_info.update(validator(request)) return request.scopes, request_info
[ "def", "validate_authorization_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 info...
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 included in the redirection URI and sent back to the client. Fatal errors occur when the client_id or redirect_uri is invalid or missing. These must be caught by the provider and handled, how this is done is outside of the scope of OAuthLib but showing an error page describing the issue is a good idea. :param request: OAuthlib request. :type request: oauthlib.common.Request
[ "Check", "the", "authorization", "request", "for", "normal", "and", "fatal", "errors", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L318-L430
train
224,635
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/metadata.py
MetadataEndpoint.create_metadata_response
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
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
[ "def", "create_metadata_response", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "return", "headers", ",", ...
Create metadata response
[ "Create", "metadata", "response" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/metadata.py#L57-L64
train
224,636
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/metadata.py
MetadataEndpoint.validate_metadata_token
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. """ 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)
python
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. """ 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)
[ "def", "validate_metadata_token", "(", "self", ",", "claims", ",", "endpoint", ")", ":", "self", ".", "_grant_types", ".", "extend", "(", "endpoint", ".", "_grant_types", ".", "keys", "(", ")", ")", "claims", ".", "setdefault", "(", "\"token_endpoint_auth_meth...
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.
[ "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", ...
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/metadata.py#L91-L103
train
224,637
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/web_application.py
WebApplicationClient.prepare_request_body
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-urlencoded" format in the HTTP request entity-body: :param code: REQUIRED. The authorization code received from the authorization server. :param redirect_uri: REQUIRED, if the "redirect_uri" parameter was included in the authorization request as described in `Section 4.1.1`_, and their values MUST be identical. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param include_client_id: `True` (default) to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. :type include_client_id: Boolean :param kwargs: Extra parameters to include in the token request. In addition OAuthLib will add the ``grant_type`` parameter set to ``authorization_code``. If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in `Section 3.2.1`_:: >>> from oauthlib.oauth2 import WebApplicationClient >>> client = WebApplicationClient('your_id') >>> client.prepare_request_body(code='sh35ksdf09sf') 'grant_type=authorization_code&code=sh35ksdf09sf' >>> client.prepare_request_body(code='sh35ksdf09sf', foo='bar') 'grant_type=authorization_code&code=sh35ksdf09sf&foo=bar' `Section 3.2.1` also states: In the "authorization_code" "grant_type" request to the token endpoint, an unauthenticated client MUST send its "client_id" to prevent itself from inadvertently accepting a code intended for a client with a different "client_id". This protects the client from substitution of the authentication code. (It provides no additional security for the protected resource.) .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 """ 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)
python
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-urlencoded" format in the HTTP request entity-body: :param code: REQUIRED. The authorization code received from the authorization server. :param redirect_uri: REQUIRED, if the "redirect_uri" parameter was included in the authorization request as described in `Section 4.1.1`_, and their values MUST be identical. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param include_client_id: `True` (default) to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. :type include_client_id: Boolean :param kwargs: Extra parameters to include in the token request. In addition OAuthLib will add the ``grant_type`` parameter set to ``authorization_code``. If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in `Section 3.2.1`_:: >>> from oauthlib.oauth2 import WebApplicationClient >>> client = WebApplicationClient('your_id') >>> client.prepare_request_body(code='sh35ksdf09sf') 'grant_type=authorization_code&code=sh35ksdf09sf' >>> client.prepare_request_body(code='sh35ksdf09sf', foo='bar') 'grant_type=authorization_code&code=sh35ksdf09sf&foo=bar' `Section 3.2.1` also states: In the "authorization_code" "grant_type" request to the token endpoint, an unauthenticated client MUST send its "client_id" to prevent itself from inadvertently accepting a code intended for a client with a different "client_id". This protects the client from substitution of the authentication code. (It provides no additional security for the protected resource.) .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 """ 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)
[ "def", "prepare_request_body", "(", "self", ",", "code", "=", "None", ",", "redirect_uri", "=", "None", ",", "body", "=", "''", ",", "include_client_id", "=", "True", ",", "*", "*", "kwargs", ")", ":", "code", "=", "code", "or", "self", ".", "code", ...
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-urlencoded" format in the HTTP request entity-body: :param code: REQUIRED. The authorization code received from the authorization server. :param redirect_uri: REQUIRED, if the "redirect_uri" parameter was included in the authorization request as described in `Section 4.1.1`_, and their values MUST be identical. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param include_client_id: `True` (default) to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. :type include_client_id: Boolean :param kwargs: Extra parameters to include in the token request. In addition OAuthLib will add the ``grant_type`` parameter set to ``authorization_code``. If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in `Section 3.2.1`_:: >>> from oauthlib.oauth2 import WebApplicationClient >>> client = WebApplicationClient('your_id') >>> client.prepare_request_body(code='sh35ksdf09sf') 'grant_type=authorization_code&code=sh35ksdf09sf' >>> client.prepare_request_body(code='sh35ksdf09sf', foo='bar') 'grant_type=authorization_code&code=sh35ksdf09sf&foo=bar' `Section 3.2.1` also states: In the "authorization_code" "grant_type" request to the token endpoint, an unauthenticated client MUST send its "client_id" to prevent itself from inadvertently accepting a code intended for a client with a different "client_id". This protects the client from substitution of the authentication code. (It provides no additional security for the protected resource.) .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1
[ "Prepare", "the", "access", "token", "request", "body", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/web_application.py#L92-L157
train
224,638
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/web_application.py
WebApplicationClient.parse_request_uri_response
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 component of the redirection URI using the "application/x-www-form-urlencoded" format: :param uri: The callback URI that resulted from the user being redirected back from the provider to you, the client. :param state: The state provided in the authorization request. **code** The authorization code generated by the authorization server. The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. **state** If the "state" parameter was present in the authorization request. This method is mainly intended to enforce strict state checking with the added benefit of easily extracting parameters from the URI:: >>> from oauthlib.oauth2 import WebApplicationClient >>> client = WebApplicationClient('your_id') >>> uri = 'https://example.com/callback?code=sdfkjh345&state=sfetw45' >>> client.parse_request_uri_response(uri, state='sfetw45') {'state': 'sfetw45', 'code': 'sdfkjh345'} >>> client.parse_request_uri_response(uri, state='other') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "oauthlib/oauth2/rfc6749/__init__.py", line 357, in parse_request_uri_response back from the provider to you, the client. File "oauthlib/oauth2/rfc6749/parameters.py", line 153, in parse_authorization_code_response raise MismatchingStateError() oauthlib.oauth2.rfc6749.errors.MismatchingStateError """ response = parse_authorization_code_response(uri, state=state) self.populate_code_attributes(response) return response
python
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 component of the redirection URI using the "application/x-www-form-urlencoded" format: :param uri: The callback URI that resulted from the user being redirected back from the provider to you, the client. :param state: The state provided in the authorization request. **code** The authorization code generated by the authorization server. The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. **state** If the "state" parameter was present in the authorization request. This method is mainly intended to enforce strict state checking with the added benefit of easily extracting parameters from the URI:: >>> from oauthlib.oauth2 import WebApplicationClient >>> client = WebApplicationClient('your_id') >>> uri = 'https://example.com/callback?code=sdfkjh345&state=sfetw45' >>> client.parse_request_uri_response(uri, state='sfetw45') {'state': 'sfetw45', 'code': 'sdfkjh345'} >>> client.parse_request_uri_response(uri, state='other') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "oauthlib/oauth2/rfc6749/__init__.py", line 357, in parse_request_uri_response back from the provider to you, the client. File "oauthlib/oauth2/rfc6749/parameters.py", line 153, in parse_authorization_code_response raise MismatchingStateError() oauthlib.oauth2.rfc6749.errors.MismatchingStateError """ response = parse_authorization_code_response(uri, state=state) self.populate_code_attributes(response) return response
[ "def", "parse_request_uri_response", "(", "self", ",", "uri", ",", "state", "=", "None", ")", ":", "response", "=", "parse_authorization_code_response", "(", "uri", ",", "state", "=", "state", ")", "self", ".", "populate_code_attributes", "(", "response", ")", ...
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 component of the redirection URI using the "application/x-www-form-urlencoded" format: :param uri: The callback URI that resulted from the user being redirected back from the provider to you, the client. :param state: The state provided in the authorization request. **code** The authorization code generated by the authorization server. The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. **state** If the "state" parameter was present in the authorization request. This method is mainly intended to enforce strict state checking with the added benefit of easily extracting parameters from the URI:: >>> from oauthlib.oauth2 import WebApplicationClient >>> client = WebApplicationClient('your_id') >>> uri = 'https://example.com/callback?code=sdfkjh345&state=sfetw45' >>> client.parse_request_uri_response(uri, state='sfetw45') {'state': 'sfetw45', 'code': 'sdfkjh345'} >>> client.parse_request_uri_response(uri, state='other') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "oauthlib/oauth2/rfc6749/__init__.py", line 357, in parse_request_uri_response back from the provider to you, the client. File "oauthlib/oauth2/rfc6749/parameters.py", line 153, in parse_authorization_code_response raise MismatchingStateError() oauthlib.oauth2.rfc6749.errors.MismatchingStateError
[ "Parse", "the", "URI", "query", "for", "code", "and", "state", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/web_application.py#L159-L205
train
224,639
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client.add_token
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 to make a protected resource request (along with type-specific attributes). The client MUST NOT use an access token if it does not understand the token type. For example, the "bearer" token type defined in [`I-D.ietf-oauth-v2-bearer`_] is utilized by simply including the access token string in the request: .. code-block:: http GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer mF_9.B5f-4.1JqM while the "mac" token type defined in [`I-D.ietf-oauth-v2-http-mac`_] is utilized by issuing a MAC key together with the access token which is used to sign certain components of the HTTP requests: .. code-block:: http GET /resource/1 HTTP/1.1 Host: example.com Authorization: MAC id="h480djs93hd8", nonce="274312:dj83hs9s", mac="kDZvddkndxvhGRXZhvuDjEWhGeE=" .. _`I-D.ietf-oauth-v2-bearer`: https://tools.ietf.org/html/rfc6749#section-12.2 .. _`I-D.ietf-oauth-v2-http-mac`: https://tools.ietf.org/html/rfc6749#section-12.2 """ 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)
python
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 to make a protected resource request (along with type-specific attributes). The client MUST NOT use an access token if it does not understand the token type. For example, the "bearer" token type defined in [`I-D.ietf-oauth-v2-bearer`_] is utilized by simply including the access token string in the request: .. code-block:: http GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer mF_9.B5f-4.1JqM while the "mac" token type defined in [`I-D.ietf-oauth-v2-http-mac`_] is utilized by issuing a MAC key together with the access token which is used to sign certain components of the HTTP requests: .. code-block:: http GET /resource/1 HTTP/1.1 Host: example.com Authorization: MAC id="h480djs93hd8", nonce="274312:dj83hs9s", mac="kDZvddkndxvhGRXZhvuDjEWhGeE=" .. _`I-D.ietf-oauth-v2-bearer`: https://tools.ietf.org/html/rfc6749#section-12.2 .. _`I-D.ietf-oauth-v2-http-mac`: https://tools.ietf.org/html/rfc6749#section-12.2 """ 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)
[ "def", "add_token", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "token_placement", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "uri"...
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 to make a protected resource request (along with type-specific attributes). The client MUST NOT use an access token if it does not understand the token type. For example, the "bearer" token type defined in [`I-D.ietf-oauth-v2-bearer`_] is utilized by simply including the access token string in the request: .. code-block:: http GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer mF_9.B5f-4.1JqM while the "mac" token type defined in [`I-D.ietf-oauth-v2-http-mac`_] is utilized by issuing a MAC key together with the access token which is used to sign certain components of the HTTP requests: .. code-block:: http GET /resource/1 HTTP/1.1 Host: example.com Authorization: MAC id="h480djs93hd8", nonce="274312:dj83hs9s", mac="kDZvddkndxvhGRXZhvuDjEWhGeE=" .. _`I-D.ietf-oauth-v2-bearer`: https://tools.ietf.org/html/rfc6749#section-12.2 .. _`I-D.ietf-oauth-v2-http-mac`: https://tools.ietf.org/html/rfc6749#section-12.2
[ "Add", "token", "to", "the", "request", "uri", "body", "or", "authorization", "header", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L149-L201
train
224,640
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client.prepare_authorization_request
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. This method adds required parameters to the authorization URL. :param authorization_url: Provider authorization endpoint URL. :param state: CSRF protection string. Will be automatically created if not provided. The generated state is available via the ``state`` attribute. Clients should verify that the state is unchanged and present in the authorization response. This verification is done automatically if using the ``authorization_response`` parameter with ``prepare_token_request``. :param redirect_url: Redirect URL to which the user will be returned after authorization. Must be provided unless previously setup with the provider. If provided then it must also be provided in the token request. :param scope: :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body). """ 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, ''
python
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. This method adds required parameters to the authorization URL. :param authorization_url: Provider authorization endpoint URL. :param state: CSRF protection string. Will be automatically created if not provided. The generated state is available via the ``state`` attribute. Clients should verify that the state is unchanged and present in the authorization response. This verification is done automatically if using the ``authorization_response`` parameter with ``prepare_token_request``. :param redirect_url: Redirect URL to which the user will be returned after authorization. Must be provided unless previously setup with the provider. If provided then it must also be provided in the token request. :param scope: :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body). """ 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, ''
[ "def", "prepare_authorization_request", "(", "self", ",", "authorization_url", ",", "state", "=", "None", ",", "redirect_url", "=", "None", ",", "scope", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "authorization_ur...
Prepare the authorization request. This is the first step in many OAuth flows in which the user is redirected to a certain authorization URL. This method adds required parameters to the authorization URL. :param authorization_url: Provider authorization endpoint URL. :param state: CSRF protection string. Will be automatically created if not provided. The generated state is available via the ``state`` attribute. Clients should verify that the state is unchanged and present in the authorization response. This verification is done automatically if using the ``authorization_response`` parameter with ``prepare_token_request``. :param redirect_url: Redirect URL to which the user will be returned after authorization. Must be provided unless previously setup with the provider. If provided then it must also be provided in the token request. :param scope: :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body).
[ "Prepare", "the", "authorization", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L203-L240
train
224,641
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client.prepare_token_request
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 provider specific authentication credentials. :param token_url: Provider token creation endpoint URL. :param authorization_response: The full redirection URL string, i.e. the location to which the user was redirected after successfull authorization. Used to mine credentials needed to obtain a token in this step, such as authorization code. :param redirect_url: The redirect_url supplied with the authorization request (if there was one). :param state: :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body). """ 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
python
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 provider specific authentication credentials. :param token_url: Provider token creation endpoint URL. :param authorization_response: The full redirection URL string, i.e. the location to which the user was redirected after successfull authorization. Used to mine credentials needed to obtain a token in this step, such as authorization code. :param redirect_url: The redirect_url supplied with the authorization request (if there was one). :param state: :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body). """ 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
[ "def", "prepare_token_request", "(", "self", ",", "token_url", ",", "authorization_response", "=", "None", ",", "redirect_url", "=", "None", ",", "state", "=", "None", ",", "body", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_trans...
Prepare a token creation request. Note that these requests usually require client authentication, either by including client_id or a set of provider specific authentication credentials. :param token_url: Provider token creation endpoint URL. :param authorization_response: The full redirection URL string, i.e. the location to which the user was redirected after successfull authorization. Used to mine credentials needed to obtain a token in this step, such as authorization code. :param redirect_url: The redirect_url supplied with the authorization request (if there was one). :param state: :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body).
[ "Prepare", "a", "token", "creation", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L242-L280
train
224,642
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client.prepare_refresh_token_request
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 obtained a refresh token. This refresh token and authentication credentials can be used to obtain a new access token, and possibly a new refresh token. :param token_url: Provider token refresh endpoint URL. :param refresh_token: Refresh token string. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: List of scopes to request. Must be equal to or a subset of the scopes granted when obtaining the refresh token. :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body). """ 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
python
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 obtained a refresh token. This refresh token and authentication credentials can be used to obtain a new access token, and possibly a new refresh token. :param token_url: Provider token refresh endpoint URL. :param refresh_token: Refresh token string. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: List of scopes to request. Must be equal to or a subset of the scopes granted when obtaining the refresh token. :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body). """ 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
[ "def", "prepare_refresh_token_request", "(", "self", ",", "token_url", ",", "refresh_token", "=", "None", ",", "body", "=", "''", ",", "scope", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "token_url", ")", ":", ...
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 obtained a refresh token. This refresh token and authentication credentials can be used to obtain a new access token, and possibly a new refresh token. :param token_url: Provider token refresh endpoint URL. :param refresh_token: Refresh token string. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: List of scopes to request. Must be equal to or a subset of the scopes granted when obtaining the refresh token. :param kwargs: Additional parameters to included in the request. :returns: The prepared request tuple with (url, headers, body).
[ "Prepare", "an", "access", "token", "refresh", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L282-L312
train
224,643
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client.parse_request_body_response
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 request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. :param body: The response body from the token request. :param scope: Scopes originally requested. :return: Dictionary of token parameters. :raises: Warning if scope has changed. OAuth2Error if response is invalid. These response are json encoded and could easily be parsed without the assistance of OAuthLib. However, there are a few subtle issues to be aware of regarding the response which are helpfully addressed through the raising of various errors. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 """ self.token = parse_token_response(body, scope=scope) self.populate_token_attributes(self.token) return self.token
python
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 request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. :param body: The response body from the token request. :param scope: Scopes originally requested. :return: Dictionary of token parameters. :raises: Warning if scope has changed. OAuth2Error if response is invalid. These response are json encoded and could easily be parsed without the assistance of OAuthLib. However, there are a few subtle issues to be aware of regarding the response which are helpfully addressed through the raising of various errors. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 """ self.token = parse_token_response(body, scope=scope) self.populate_token_attributes(self.token) return self.token
[ "def", "parse_request_body_response", "(", "self", ",", "body", ",", "scope", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "token", "=", "parse_token_response", "(", "body", ",", "scope", "=", "scope", ")", "self", ".", "populate_token_attr...
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 request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. :param body: The response body from the token request. :param scope: Scopes originally requested. :return: Dictionary of token parameters. :raises: Warning if scope has changed. OAuth2Error if response is invalid. These response are json encoded and could easily be parsed without the assistance of OAuthLib. However, there are a few subtle issues to be aware of regarding the response which are helpfully addressed through the raising of various errors. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
[ "Parse", "the", "JSON", "response", "body", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L375-L423
train
224,644
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client.prepare_refresh_body
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 following parameters using the "application/x-www-form-urlencoded" format in the HTTP request entity-body: grant_type REQUIRED. Value MUST be set to "refresh_token". refresh_token REQUIRED. The refresh token issued to the client. scope OPTIONAL. The scope of the access request as described by Section 3.3. The requested scope MUST NOT include any scope not originally granted by the resource owner, and if omitted is treated as equal to the scope originally granted by the resource owner. """ 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)
python
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 following parameters using the "application/x-www-form-urlencoded" format in the HTTP request entity-body: grant_type REQUIRED. Value MUST be set to "refresh_token". refresh_token REQUIRED. The refresh token issued to the client. scope OPTIONAL. The scope of the access request as described by Section 3.3. The requested scope MUST NOT include any scope not originally granted by the resource owner, and if omitted is treated as equal to the scope originally granted by the resource owner. """ 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)
[ "def", "prepare_refresh_body", "(", "self", ",", "body", "=", "''", ",", "refresh_token", "=", "None", ",", "scope", "=", "None", ",", "*", "*", "kwargs", ")", ":", "refresh_token", "=", "refresh_token", "or", "self", ".", "refresh_token", "return", "prepa...
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 following parameters using the "application/x-www-form-urlencoded" format in the HTTP request entity-body: grant_type REQUIRED. Value MUST be set to "refresh_token". refresh_token REQUIRED. The refresh token issued to the client. scope OPTIONAL. The scope of the access request as described by Section 3.3. The requested scope MUST NOT include any scope not originally granted by the resource owner, and if omitted is treated as equal to the scope originally granted by the resource owner.
[ "Prepare", "an", "access", "token", "request", "using", "a", "refresh", "token", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L425-L446
train
224,645
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client._add_mac_token
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 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
python
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 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
[ "def", "_add_mac_token", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "token_placement", "=", "AUTH_HEADER", ",", "ext", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "...
Add a MAC token to the request authorization header. Warning: MAC token support is experimental as the spec is not yet stable.
[ "Add", "a", "MAC", "token", "to", "the", "request", "authorization", "header", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L464-L476
train
224,646
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/base.py
Client.populate_token_attributes
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') 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')
python
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') 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')
[ "def", "populate_token_attributes", "(", "self", ",", "response", ")", ":", "if", "'access_token'", "in", "response", ":", "self", ".", "access_token", "=", "response", ".", "get", "(", "'access_token'", ")", "if", "'refresh_token'", "in", "response", ":", "se...
Add attributes from a token exchange response to self.
[ "Add", "attributes", "from", "a", "token", "exchange", "response", "to", "self", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/base.py#L489-L512
train
224,647
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/base.py
BaseEndpoint._get_signature_type_and_params
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. 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
python
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. 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
[ "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", ".", ...
Extracts parameters from query, headers and body. Signature type is set to the source in which parameters were found.
[ "Extracts", "parameters", "from", "query", "headers", "and", "body", ".", "Signature", "type", "is", "set", "to", "the", "source", "in", "which", "parameters", "were", "found", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/base.py#L26-L66
train
224,648
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py
ResourceOwnerPasswordCredentialsGrant.create_token_response
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.BearerToken. If the access token request is valid and authorized, the authorization server issues an access token and optional refresh token as described in `Section 5.1`_. If the request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 """ 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
python
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.BearerToken. If the access token request is valid and authorized, the authorization server issues an access token and optional refresh token as described in `Section 5.1`_. If the request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 """ 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
[ "def", "create_token_response", "(", "self", ",", "request", ",", "token_handler", ")", ":", "headers", "=", "self", ".", "_get_default_headers", "(", ")", "try", ":", "if", "self", ".", "request_validator", ".", "client_authentication_required", "(", "request", ...
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.BearerToken. If the access token request is valid and authorized, the authorization server issues an access token and optional refresh token as described in `Section 5.1`_. If the request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2
[ "Return", "token", "or", "error", "in", "json", "format", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py#L73-L116
train
224,649
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.check_client_key
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(client_key) <= upper)
python
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(client_key) <= upper)
[ "def", "check_client_key", "(", "self", ",", "client_key", ")", ":", "lower", ",", "upper", "=", "self", ".", "client_key_length", "return", "(", "set", "(", "client_key", ")", "<=", "self", ".", "safe_characters", "and", "lower", "<=", "len", "(", "client...
Check that the client key only contains safe characters and is no shorter than lower and no longer than upper.
[ "Check", "that", "the", "client", "key", "only", "contains", "safe", "characters", "and", "is", "no", "shorter", "than", "lower", "and", "no", "longer", "than", "upper", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L158-L164
train
224,650
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.check_request_token
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 lower <= len(request_token) <= upper)
python
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 lower <= len(request_token) <= upper)
[ "def", "check_request_token", "(", "self", ",", "request_token", ")", ":", "lower", ",", "upper", "=", "self", ".", "request_token_length", "return", "(", "set", "(", "request_token", ")", "<=", "self", ".", "safe_characters", "and", "lower", "<=", "len", "(...
Checks that the request token contains only safe characters and is no shorter than lower and no longer than upper.
[ "Checks", "that", "the", "request", "token", "contains", "only", "safe", "characters", "and", "is", "no", "shorter", "than", "lower", "and", "no", "longer", "than", "upper", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L166-L172
train
224,651
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.check_access_token
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 <= len(request_token) <= upper)
python
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 <= len(request_token) <= upper)
[ "def", "check_access_token", "(", "self", ",", "request_token", ")", ":", "lower", ",", "upper", "=", "self", ".", "access_token_length", "return", "(", "set", "(", "request_token", ")", "<=", "self", ".", "safe_characters", "and", "lower", "<=", "len", "(",...
Checks that the token contains only safe characters and is no shorter than lower and no longer than upper.
[ "Checks", "that", "the", "token", "contains", "only", "safe", "characters", "and", "is", "no", "shorter", "than", "lower", "and", "no", "longer", "than", "upper", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L174-L180
train
224,652
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.check_nonce
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
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)
[ "def", "check_nonce", "(", "self", ",", "nonce", ")", ":", "lower", ",", "upper", "=", "self", ".", "nonce_length", "return", "(", "set", "(", "nonce", ")", "<=", "self", ".", "safe_characters", "and", "lower", "<=", "len", "(", "nonce", ")", "<=", "...
Checks that the nonce only contains only safe characters and is no shorter than lower and no longer than upper.
[ "Checks", "that", "the", "nonce", "only", "contains", "only", "safe", "characters", "and", "is", "no", "shorter", "than", "lower", "and", "no", "longer", "than", "upper", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L182-L188
train
224,653
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.check_verifier
def check_verifier(self, verifier): """Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.verifier_length return (set(verifier) <= self.safe_characters and lower <= len(verifier) <= upper)
python
def check_verifier(self, verifier): """Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.verifier_length return (set(verifier) <= self.safe_characters and lower <= len(verifier) <= upper)
[ "def", "check_verifier", "(", "self", ",", "verifier", ")", ":", "lower", ",", "upper", "=", "self", ".", "verifier_length", "return", "(", "set", "(", "verifier", ")", "<=", "self", ".", "safe_characters", "and", "lower", "<=", "len", "(", "verifier", "...
Checks that the verifier contains only safe characters and is no shorter than lower and no longer than upper.
[ "Checks", "that", "the", "verifier", "contains", "only", "safe", "characters", "and", "is", "no", "shorter", "than", "lower", "and", "no", "longer", "than", "upper", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L190-L196
train
224,654
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/request_validator.py
RequestValidator.validate_timestamp_and_nonce
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request, request_token=None, access_token=None): """Validates that the nonce has not been used before. :param client_key: The client/consumer key. :param timestamp: The ``oauth_timestamp`` parameter. :param nonce: The ``oauth_nonce`` parameter. :param request_token: Request token string, if any. :param access_token: Access token string, if any. :param request: OAuthlib request. :type request: oauthlib.common.Request :returns: True or False Per `Section 3.3`_ of the spec. "A nonce is a random string, uniquely generated by the client to allow the server to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel. The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations." .. _`Section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3 One of the first validation checks that will be made is for the validity of the nonce and timestamp, which are associated with a client key and possibly a token. If invalid then immediately fail the request by returning False. If the nonce/timestamp pair has been used before and you may just have detected a replay attack. Therefore it is an essential part of OAuth security that you not allow nonce/timestamp reuse. Note that this validation check is done before checking the validity of the client and token.:: nonces_and_timestamps_database = [ (u'foo', 1234567890, u'rannoMstrInghere', u'bar') ] def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): return ((client_key, timestamp, nonce, request_token or access_token) not in self.nonces_and_timestamps_database) This method is used by * AccessTokenEndpoint * RequestTokenEndpoint * ResourceEndpoint * SignatureOnlyEndpoint """ raise self._subclass_must_implement("validate_timestamp_and_nonce")
python
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request, request_token=None, access_token=None): """Validates that the nonce has not been used before. :param client_key: The client/consumer key. :param timestamp: The ``oauth_timestamp`` parameter. :param nonce: The ``oauth_nonce`` parameter. :param request_token: Request token string, if any. :param access_token: Access token string, if any. :param request: OAuthlib request. :type request: oauthlib.common.Request :returns: True or False Per `Section 3.3`_ of the spec. "A nonce is a random string, uniquely generated by the client to allow the server to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel. The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations." .. _`Section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3 One of the first validation checks that will be made is for the validity of the nonce and timestamp, which are associated with a client key and possibly a token. If invalid then immediately fail the request by returning False. If the nonce/timestamp pair has been used before and you may just have detected a replay attack. Therefore it is an essential part of OAuth security that you not allow nonce/timestamp reuse. Note that this validation check is done before checking the validity of the client and token.:: nonces_and_timestamps_database = [ (u'foo', 1234567890, u'rannoMstrInghere', u'bar') ] def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): return ((client_key, timestamp, nonce, request_token or access_token) not in self.nonces_and_timestamps_database) This method is used by * AccessTokenEndpoint * RequestTokenEndpoint * ResourceEndpoint * SignatureOnlyEndpoint """ raise self._subclass_must_implement("validate_timestamp_and_nonce")
[ "def", "validate_timestamp_and_nonce", "(", "self", ",", "client_key", ",", "timestamp", ",", "nonce", ",", "request", ",", "request_token", "=", "None", ",", "access_token", "=", "None", ")", ":", "raise", "self", ".", "_subclass_must_implement", "(", "\"valida...
Validates that the nonce has not been used before. :param client_key: The client/consumer key. :param timestamp: The ``oauth_timestamp`` parameter. :param nonce: The ``oauth_nonce`` parameter. :param request_token: Request token string, if any. :param access_token: Access token string, if any. :param request: OAuthlib request. :type request: oauthlib.common.Request :returns: True or False Per `Section 3.3`_ of the spec. "A nonce is a random string, uniquely generated by the client to allow the server to verify that a request has never been made before and helps prevent replay attacks when requests are made over a non-secure channel. The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations." .. _`Section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3 One of the first validation checks that will be made is for the validity of the nonce and timestamp, which are associated with a client key and possibly a token. If invalid then immediately fail the request by returning False. If the nonce/timestamp pair has been used before and you may just have detected a replay attack. Therefore it is an essential part of OAuth security that you not allow nonce/timestamp reuse. Note that this validation check is done before checking the validity of the client and token.:: nonces_and_timestamps_database = [ (u'foo', 1234567890, u'rannoMstrInghere', u'bar') ] def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): return ((client_key, timestamp, nonce, request_token or access_token) not in self.nonces_and_timestamps_database) This method is used by * AccessTokenEndpoint * RequestTokenEndpoint * ResourceEndpoint * SignatureOnlyEndpoint
[ "Validates", "that", "the", "nonce", "has", "not", "been", "used", "before", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/request_validator.py#L576-L625
train
224,655
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
prepare_grant_uri
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the ``application/x-www-form-urlencoded`` format as defined by [`W3C.REC-html401-19991224`_]: :param uri: :param client_id: The client identifier as described in `Section 2.2`_. :param response_type: To indicate which OAuth 2 grant/flow is required, "code" and "token". :param redirect_uri: The client provided URI to redirect back to after authorization as described in `Section 3.1.2`_. :param scope: The scope of the access request as described by `Section 3.3`_. :param state: An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery as described in `Section 10.12`_. :param kwargs: Extra arguments to embed in the grant/authorization URL. An example of an authorization code grant authorization URL: .. code-block:: http GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 Host: server.example.com .. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224 .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 """ if not is_secure_transport(uri): raise InsecureTransportError() params = [(('response_type', response_type)), (('client_id', client_id))] if redirect_uri: params.append(('redirect_uri', redirect_uri)) if scope: params.append(('scope', list_to_scope(scope))) if state: params.append(('state', state)) for k in kwargs: if kwargs[k]: params.append((unicode_type(k), kwargs[k])) return add_params_to_uri(uri, params)
python
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the ``application/x-www-form-urlencoded`` format as defined by [`W3C.REC-html401-19991224`_]: :param uri: :param client_id: The client identifier as described in `Section 2.2`_. :param response_type: To indicate which OAuth 2 grant/flow is required, "code" and "token". :param redirect_uri: The client provided URI to redirect back to after authorization as described in `Section 3.1.2`_. :param scope: The scope of the access request as described by `Section 3.3`_. :param state: An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery as described in `Section 10.12`_. :param kwargs: Extra arguments to embed in the grant/authorization URL. An example of an authorization code grant authorization URL: .. code-block:: http GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 Host: server.example.com .. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224 .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 """ if not is_secure_transport(uri): raise InsecureTransportError() params = [(('response_type', response_type)), (('client_id', client_id))] if redirect_uri: params.append(('redirect_uri', redirect_uri)) if scope: params.append(('scope', list_to_scope(scope))) if state: params.append(('state', state)) for k in kwargs: if kwargs[k]: params.append((unicode_type(k), kwargs[k])) return add_params_to_uri(uri, params)
[ "def", "prepare_grant_uri", "(", "uri", ",", "client_id", ",", "response_type", ",", "redirect_uri", "=", "None", ",", "scope", "=", "None", ",", "state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "uri", ")"...
Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the ``application/x-www-form-urlencoded`` format as defined by [`W3C.REC-html401-19991224`_]: :param uri: :param client_id: The client identifier as described in `Section 2.2`_. :param response_type: To indicate which OAuth 2 grant/flow is required, "code" and "token". :param redirect_uri: The client provided URI to redirect back to after authorization as described in `Section 3.1.2`_. :param scope: The scope of the access request as described by `Section 3.3`_. :param state: An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery as described in `Section 10.12`_. :param kwargs: Extra arguments to embed in the grant/authorization URL. An example of an authorization code grant authorization URL: .. code-block:: http GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 Host: server.example.com .. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224 .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
[ "Prepare", "the", "authorization", "grant", "request", "URI", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L31-L87
train
224,656
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
prepare_token_request
def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs): """Prepare the access token request. The client makes a request to the token endpoint by adding the following parameters using the ``application/x-www-form-urlencoded`` format in the HTTP request entity-body: :param grant_type: To indicate grant type being used, i.e. "password", "authorization_code" or "client_credentials". :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra parameters. Default ''. :param include_client_id: `True` (default) to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. :type include_client_id: Boolean :param client_id: Unicode client identifier. Will only appear if `include_client_id` is True. * :param client_secret: Unicode client secret. Will only appear if set to a value that is not `None`. Invoking this function with an empty string will send an empty `client_secret` value to the server. * :param code: If using authorization_code grant, pass the previously obtained authorization code as the ``code`` argument. * :param redirect_uri: If the "redirect_uri" parameter was included in the authorization request as described in `Section 4.1.1`_, and their values MUST be identical. * :param kwargs: Extra arguments to embed in the request body. Parameters marked with a `*` above are not explicit arguments in the function signature, but are specially documented arguments for items appearing in the generic `**kwargs` keyworded input. An example of an authorization code token request body: .. code-block:: http grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 """ params = [('grant_type', grant_type)] if 'scope' in kwargs: kwargs['scope'] = list_to_scope(kwargs['scope']) # pull the `client_id` out of the kwargs. client_id = kwargs.pop('client_id', None) if include_client_id: if client_id is not None: params.append((unicode_type('client_id'), client_id)) # the kwargs iteration below only supports including boolean truth (truthy) # values, but some servers may require an empty string for `client_secret` client_secret = kwargs.pop('client_secret', None) if client_secret is not None: params.append((unicode_type('client_secret'), client_secret)) # this handles: `code`, `redirect_uri`, and other undocumented params for k in kwargs: if kwargs[k]: params.append((unicode_type(k), kwargs[k])) return add_params_to_qs(body, params)
python
def prepare_token_request(grant_type, body='', include_client_id=True, **kwargs): """Prepare the access token request. The client makes a request to the token endpoint by adding the following parameters using the ``application/x-www-form-urlencoded`` format in the HTTP request entity-body: :param grant_type: To indicate grant type being used, i.e. "password", "authorization_code" or "client_credentials". :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra parameters. Default ''. :param include_client_id: `True` (default) to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. :type include_client_id: Boolean :param client_id: Unicode client identifier. Will only appear if `include_client_id` is True. * :param client_secret: Unicode client secret. Will only appear if set to a value that is not `None`. Invoking this function with an empty string will send an empty `client_secret` value to the server. * :param code: If using authorization_code grant, pass the previously obtained authorization code as the ``code`` argument. * :param redirect_uri: If the "redirect_uri" parameter was included in the authorization request as described in `Section 4.1.1`_, and their values MUST be identical. * :param kwargs: Extra arguments to embed in the request body. Parameters marked with a `*` above are not explicit arguments in the function signature, but are specially documented arguments for items appearing in the generic `**kwargs` keyworded input. An example of an authorization code token request body: .. code-block:: http grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1 """ params = [('grant_type', grant_type)] if 'scope' in kwargs: kwargs['scope'] = list_to_scope(kwargs['scope']) # pull the `client_id` out of the kwargs. client_id = kwargs.pop('client_id', None) if include_client_id: if client_id is not None: params.append((unicode_type('client_id'), client_id)) # the kwargs iteration below only supports including boolean truth (truthy) # values, but some servers may require an empty string for `client_secret` client_secret = kwargs.pop('client_secret', None) if client_secret is not None: params.append((unicode_type('client_secret'), client_secret)) # this handles: `code`, `redirect_uri`, and other undocumented params for k in kwargs: if kwargs[k]: params.append((unicode_type(k), kwargs[k])) return add_params_to_qs(body, params)
[ "def", "prepare_token_request", "(", "grant_type", ",", "body", "=", "''", ",", "include_client_id", "=", "True", ",", "*", "*", "kwargs", ")", ":", "params", "=", "[", "(", "'grant_type'", ",", "grant_type", ")", "]", "if", "'scope'", "in", "kwargs", ":...
Prepare the access token request. The client makes a request to the token endpoint by adding the following parameters using the ``application/x-www-form-urlencoded`` format in the HTTP request entity-body: :param grant_type: To indicate grant type being used, i.e. "password", "authorization_code" or "client_credentials". :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra parameters. Default ''. :param include_client_id: `True` (default) to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. :type include_client_id: Boolean :param client_id: Unicode client identifier. Will only appear if `include_client_id` is True. * :param client_secret: Unicode client secret. Will only appear if set to a value that is not `None`. Invoking this function with an empty string will send an empty `client_secret` value to the server. * :param code: If using authorization_code grant, pass the previously obtained authorization code as the ``code`` argument. * :param redirect_uri: If the "redirect_uri" parameter was included in the authorization request as described in `Section 4.1.1`_, and their values MUST be identical. * :param kwargs: Extra arguments to embed in the request body. Parameters marked with a `*` above are not explicit arguments in the function signature, but are specially documented arguments for items appearing in the generic `**kwargs` keyworded input. An example of an authorization code token request body: .. code-block:: http grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1
[ "Prepare", "the", "access", "token", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L90-L162
train
224,657
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
parse_authorization_code_response
def parse_authorization_code_response(uri, state=None): """Parse authorization grant response URI into a dict. If the resource owner grants the access request, the authorization server issues an authorization code and delivers it to the client by adding the following parameters to the query component of the redirection URI using the ``application/x-www-form-urlencoded`` format: **code** REQUIRED. The authorization code generated by the authorization server. The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. **state** REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. :param uri: The full redirect URL back to the client. :param state: The state parameter from the authorization request. For example, the authorization server redirects the user-agent by sending the following HTTP response: .. code-block:: http HTTP/1.1 302 Found Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA &state=xyz """ if not is_secure_transport(uri): raise InsecureTransportError() query = urlparse.urlparse(uri).query params = dict(urlparse.parse_qsl(query)) if not 'code' in params: raise MissingCodeError("Missing code parameter in response.") if state and params.get('state', None) != state: raise MismatchingStateError() return params
python
def parse_authorization_code_response(uri, state=None): """Parse authorization grant response URI into a dict. If the resource owner grants the access request, the authorization server issues an authorization code and delivers it to the client by adding the following parameters to the query component of the redirection URI using the ``application/x-www-form-urlencoded`` format: **code** REQUIRED. The authorization code generated by the authorization server. The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. **state** REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. :param uri: The full redirect URL back to the client. :param state: The state parameter from the authorization request. For example, the authorization server redirects the user-agent by sending the following HTTP response: .. code-block:: http HTTP/1.1 302 Found Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA &state=xyz """ if not is_secure_transport(uri): raise InsecureTransportError() query = urlparse.urlparse(uri).query params = dict(urlparse.parse_qsl(query)) if not 'code' in params: raise MissingCodeError("Missing code parameter in response.") if state and params.get('state', None) != state: raise MismatchingStateError() return params
[ "def", "parse_authorization_code_response", "(", "uri", ",", "state", "=", "None", ")", ":", "if", "not", "is_secure_transport", "(", "uri", ")", ":", "raise", "InsecureTransportError", "(", ")", "query", "=", "urlparse", ".", "urlparse", "(", "uri", ")", "....
Parse authorization grant response URI into a dict. If the resource owner grants the access request, the authorization server issues an authorization code and delivers it to the client by adding the following parameters to the query component of the redirection URI using the ``application/x-www-form-urlencoded`` format: **code** REQUIRED. The authorization code generated by the authorization server. The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The authorization code is bound to the client identifier and redirection URI. **state** REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. :param uri: The full redirect URL back to the client. :param state: The state parameter from the authorization request. For example, the authorization server redirects the user-agent by sending the following HTTP response: .. code-block:: http HTTP/1.1 302 Found Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA &state=xyz
[ "Parse", "authorization", "grant", "response", "URI", "into", "a", "dict", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L223-L273
train
224,658
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
parse_implicit_response
def parse_implicit_response(uri, state=None, scope=None): """Parse the implicit token response URI into a dict. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the ``application/x-www-form-urlencoded`` format: **access_token** REQUIRED. The access token issued by the authorization server. **token_type** REQUIRED. The type of the token issued as described in Section 7.1. Value is case insensitive. **expires_in** RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** OPTIONAL, if identical to the scope requested by the client, otherwise REQUIRED. The scope of the access token as described by Section 3.3. **state** REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. :param uri: :param state: :param scope: Similar to the authorization code response, but with a full token provided in the URL fragment: .. code-block:: http HTTP/1.1 302 Found Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA &state=xyz&token_type=example&expires_in=3600 """ if not is_secure_transport(uri): raise InsecureTransportError() fragment = urlparse.urlparse(uri).fragment params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True)) for key in ('expires_in',): if key in params: # cast things to int params[key] = int(params[key]) if 'scope' in params: params['scope'] = scope_to_list(params['scope']) if 'expires_in' in params: params['expires_at'] = time.time() + int(params['expires_in']) if state and params.get('state', None) != state: raise ValueError("Mismatching or missing state in params.") params = OAuth2Token(params, old_scope=scope) validate_token_parameters(params) return params
python
def parse_implicit_response(uri, state=None, scope=None): """Parse the implicit token response URI into a dict. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the ``application/x-www-form-urlencoded`` format: **access_token** REQUIRED. The access token issued by the authorization server. **token_type** REQUIRED. The type of the token issued as described in Section 7.1. Value is case insensitive. **expires_in** RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** OPTIONAL, if identical to the scope requested by the client, otherwise REQUIRED. The scope of the access token as described by Section 3.3. **state** REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. :param uri: :param state: :param scope: Similar to the authorization code response, but with a full token provided in the URL fragment: .. code-block:: http HTTP/1.1 302 Found Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA &state=xyz&token_type=example&expires_in=3600 """ if not is_secure_transport(uri): raise InsecureTransportError() fragment = urlparse.urlparse(uri).fragment params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True)) for key in ('expires_in',): if key in params: # cast things to int params[key] = int(params[key]) if 'scope' in params: params['scope'] = scope_to_list(params['scope']) if 'expires_in' in params: params['expires_at'] = time.time() + int(params['expires_in']) if state and params.get('state', None) != state: raise ValueError("Mismatching or missing state in params.") params = OAuth2Token(params, old_scope=scope) validate_token_parameters(params) return params
[ "def", "parse_implicit_response", "(", "uri", ",", "state", "=", "None", ",", "scope", "=", "None", ")", ":", "if", "not", "is_secure_transport", "(", "uri", ")", ":", "raise", "InsecureTransportError", "(", ")", "fragment", "=", "urlparse", ".", "urlparse",...
Parse the implicit token response URI into a dict. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the ``application/x-www-form-urlencoded`` format: **access_token** REQUIRED. The access token issued by the authorization server. **token_type** REQUIRED. The type of the token issued as described in Section 7.1. Value is case insensitive. **expires_in** RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** OPTIONAL, if identical to the scope requested by the client, otherwise REQUIRED. The scope of the access token as described by Section 3.3. **state** REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. :param uri: :param state: :param scope: Similar to the authorization code response, but with a full token provided in the URL fragment: .. code-block:: http HTTP/1.1 302 Found Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA &state=xyz&token_type=example&expires_in=3600
[ "Parse", "the", "implicit", "token", "response", "URI", "into", "a", "dict", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L276-L342
train
224,659
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
parse_token_response
def parse_token_response(body, scope=None): """Parse the JSON token response body into a dict. The authorization server issues an access token and optional refresh token, and constructs the response by adding the following parameters to the entity body of the HTTP response with a 200 (OK) status code: access_token REQUIRED. The access token issued by the authorization server. token_type REQUIRED. The type of the token issued as described in `Section 7.1`_. Value is case insensitive. expires_in RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. refresh_token OPTIONAL. The refresh token which can be used to obtain new access tokens using the same authorization grant as described in `Section 6`_. scope OPTIONAL, if identical to the scope requested by the client, otherwise REQUIRED. The scope of the access token as described by `Section 3.3`_. The parameters are included in the entity body of the HTTP response using the "application/json" media type as defined by [`RFC4627`_]. The parameters are serialized into a JSON structure by adding each parameter at the highest structure level. Parameter names and string values are included as JSON strings. Numerical values are included as JSON numbers. The order of parameters does not matter and can vary. :param body: The full json encoded response body. :param scope: The scope requested during authorization. For example: .. code-block:: http HTTP/1.1 200 OK Content-Type: application/json Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" } .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`RFC4627`: https://tools.ietf.org/html/rfc4627 """ try: params = json.loads(body) except ValueError: # Fall back to URL-encoded string, to support old implementations, # including (at time of writing) Facebook. See: # https://github.com/oauthlib/oauthlib/issues/267 params = dict(urlparse.parse_qsl(body)) for key in ('expires_in',): if key in params: # cast things to int params[key] = int(params[key]) if 'scope' in params: params['scope'] = scope_to_list(params['scope']) if 'expires_in' in params: params['expires_at'] = time.time() + int(params['expires_in']) params = OAuth2Token(params, old_scope=scope) validate_token_parameters(params) return params
python
def parse_token_response(body, scope=None): """Parse the JSON token response body into a dict. The authorization server issues an access token and optional refresh token, and constructs the response by adding the following parameters to the entity body of the HTTP response with a 200 (OK) status code: access_token REQUIRED. The access token issued by the authorization server. token_type REQUIRED. The type of the token issued as described in `Section 7.1`_. Value is case insensitive. expires_in RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. refresh_token OPTIONAL. The refresh token which can be used to obtain new access tokens using the same authorization grant as described in `Section 6`_. scope OPTIONAL, if identical to the scope requested by the client, otherwise REQUIRED. The scope of the access token as described by `Section 3.3`_. The parameters are included in the entity body of the HTTP response using the "application/json" media type as defined by [`RFC4627`_]. The parameters are serialized into a JSON structure by adding each parameter at the highest structure level. Parameter names and string values are included as JSON strings. Numerical values are included as JSON numbers. The order of parameters does not matter and can vary. :param body: The full json encoded response body. :param scope: The scope requested during authorization. For example: .. code-block:: http HTTP/1.1 200 OK Content-Type: application/json Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" } .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`RFC4627`: https://tools.ietf.org/html/rfc4627 """ try: params = json.loads(body) except ValueError: # Fall back to URL-encoded string, to support old implementations, # including (at time of writing) Facebook. See: # https://github.com/oauthlib/oauthlib/issues/267 params = dict(urlparse.parse_qsl(body)) for key in ('expires_in',): if key in params: # cast things to int params[key] = int(params[key]) if 'scope' in params: params['scope'] = scope_to_list(params['scope']) if 'expires_in' in params: params['expires_at'] = time.time() + int(params['expires_in']) params = OAuth2Token(params, old_scope=scope) validate_token_parameters(params) return params
[ "def", "parse_token_response", "(", "body", ",", "scope", "=", "None", ")", ":", "try", ":", "params", "=", "json", ".", "loads", "(", "body", ")", "except", "ValueError", ":", "# Fall back to URL-encoded string, to support old implementations,", "# including (at time...
Parse the JSON token response body into a dict. The authorization server issues an access token and optional refresh token, and constructs the response by adding the following parameters to the entity body of the HTTP response with a 200 (OK) status code: access_token REQUIRED. The access token issued by the authorization server. token_type REQUIRED. The type of the token issued as described in `Section 7.1`_. Value is case insensitive. expires_in RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. refresh_token OPTIONAL. The refresh token which can be used to obtain new access tokens using the same authorization grant as described in `Section 6`_. scope OPTIONAL, if identical to the scope requested by the client, otherwise REQUIRED. The scope of the access token as described by `Section 3.3`_. The parameters are included in the entity body of the HTTP response using the "application/json" media type as defined by [`RFC4627`_]. The parameters are serialized into a JSON structure by adding each parameter at the highest structure level. Parameter names and string values are included as JSON strings. Numerical values are included as JSON numbers. The order of parameters does not matter and can vary. :param body: The full json encoded response body. :param scope: The scope requested during authorization. For example: .. code-block:: http HTTP/1.1 200 OK Content-Type: application/json Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" } .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`RFC4627`: https://tools.ietf.org/html/rfc4627
[ "Parse", "the", "JSON", "token", "response", "body", "into", "a", "dict", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L345-L426
train
224,660
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/parameters.py
validate_token_parameters
def validate_token_parameters(params): """Ensures token precence, token type, expiration and scope in params.""" if 'error' in params: raise_from_error(params.get('error'), params) if not 'access_token' in params: raise MissingTokenError(description="Missing access token parameter.") if not 'token_type' in params: if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'): raise MissingTokenTypeError() # If the issued access token scope is different from the one requested by # the client, the authorization server MUST include the "scope" response # parameter to inform the client of the actual scope granted. # https://tools.ietf.org/html/rfc6749#section-3.3 if params.scope_changed: message = 'Scope has changed from "{old}" to "{new}".'.format( old=params.old_scope, new=params.scope, ) scope_changed.send(message=message, old=params.old_scopes, new=params.scopes) if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None): w = Warning(message) w.token = params w.old_scope = params.old_scopes w.new_scope = params.scopes raise w
python
def validate_token_parameters(params): """Ensures token precence, token type, expiration and scope in params.""" if 'error' in params: raise_from_error(params.get('error'), params) if not 'access_token' in params: raise MissingTokenError(description="Missing access token parameter.") if not 'token_type' in params: if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'): raise MissingTokenTypeError() # If the issued access token scope is different from the one requested by # the client, the authorization server MUST include the "scope" response # parameter to inform the client of the actual scope granted. # https://tools.ietf.org/html/rfc6749#section-3.3 if params.scope_changed: message = 'Scope has changed from "{old}" to "{new}".'.format( old=params.old_scope, new=params.scope, ) scope_changed.send(message=message, old=params.old_scopes, new=params.scopes) if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None): w = Warning(message) w.token = params w.old_scope = params.old_scopes w.new_scope = params.scopes raise w
[ "def", "validate_token_parameters", "(", "params", ")", ":", "if", "'error'", "in", "params", ":", "raise_from_error", "(", "params", ".", "get", "(", "'error'", ")", ",", "params", ")", "if", "not", "'access_token'", "in", "params", ":", "raise", "MissingTo...
Ensures token precence, token type, expiration and scope in params.
[ "Ensures", "token", "precence", "token", "type", "expiration", "and", "scope", "in", "params", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/parameters.py#L429-L455
train
224,661
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/legacy_application.py
LegacyApplicationClient.prepare_request_body
def prepare_request_body(self, username, password, body='', scope=None, include_client_id=False, **kwargs): """Add the resource owner password and username to the request body. The client makes a request to the token endpoint by adding the following parameters using the "application/x-www-form-urlencoded" format per `Appendix B`_ in the HTTP request entity-body: :param username: The resource owner username. :param password: The resource owner password. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: The scope of the access request as described by `Section 3.3`_. :param include_client_id: `True` to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. False otherwise (default). :type include_client_id: Boolean :param kwargs: Extra credentials to include in the token request. If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in `Section 3.2.1`_. The prepared body will include all provided credentials as well as the ``grant_type`` parameter set to ``password``:: >>> from oauthlib.oauth2 import LegacyApplicationClient >>> client = LegacyApplicationClient('your_id') >>> client.prepare_request_body(username='foo', password='bar', scope=['hello', 'world']) 'grant_type=password&username=foo&scope=hello+world&password=bar' .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 """ kwargs['client_id'] = self.client_id kwargs['include_client_id'] = include_client_id return prepare_token_request(self.grant_type, body=body, username=username, password=password, scope=scope, **kwargs)
python
def prepare_request_body(self, username, password, body='', scope=None, include_client_id=False, **kwargs): """Add the resource owner password and username to the request body. The client makes a request to the token endpoint by adding the following parameters using the "application/x-www-form-urlencoded" format per `Appendix B`_ in the HTTP request entity-body: :param username: The resource owner username. :param password: The resource owner password. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: The scope of the access request as described by `Section 3.3`_. :param include_client_id: `True` to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. False otherwise (default). :type include_client_id: Boolean :param kwargs: Extra credentials to include in the token request. If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in `Section 3.2.1`_. The prepared body will include all provided credentials as well as the ``grant_type`` parameter set to ``password``:: >>> from oauthlib.oauth2 import LegacyApplicationClient >>> client = LegacyApplicationClient('your_id') >>> client.prepare_request_body(username='foo', password='bar', scope=['hello', 'world']) 'grant_type=password&username=foo&scope=hello+world&password=bar' .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 """ kwargs['client_id'] = self.client_id kwargs['include_client_id'] = include_client_id return prepare_token_request(self.grant_type, body=body, username=username, password=password, scope=scope, **kwargs)
[ "def", "prepare_request_body", "(", "self", ",", "username", ",", "password", ",", "body", "=", "''", ",", "scope", "=", "None", ",", "include_client_id", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'client_id'", "]", "=", "self", ...
Add the resource owner password and username to the request body. The client makes a request to the token endpoint by adding the following parameters using the "application/x-www-form-urlencoded" format per `Appendix B`_ in the HTTP request entity-body: :param username: The resource owner username. :param password: The resource owner password. :param body: Existing request body (URL encoded string) to embed parameters into. This may contain extra paramters. Default ''. :param scope: The scope of the access request as described by `Section 3.3`_. :param include_client_id: `True` to send the `client_id` in the body of the upstream request. This is required if the client is not authenticating with the authorization server as described in `Section 3.2.1`_. False otherwise (default). :type include_client_id: Boolean :param kwargs: Extra credentials to include in the token request. If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in `Section 3.2.1`_. The prepared body will include all provided credentials as well as the ``grant_type`` parameter set to ``password``:: >>> from oauthlib.oauth2 import LegacyApplicationClient >>> client = LegacyApplicationClient('your_id') >>> client.prepare_request_body(username='foo', password='bar', scope=['hello', 'world']) 'grant_type=password&username=foo&scope=hello+world&password=bar' .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1
[ "Add", "the", "resource", "owner", "password", "and", "username", "to", "the", "request", "body", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/legacy_application.py#L43-L85
train
224,662
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/mobile_application.py
MobileApplicationClient.prepare_request_uri
def prepare_request_uri(self, uri, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the implicit grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the "application/x-www-form-urlencoded" format, per `Appendix B`_: :param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI and it should have been registerd with the OAuth provider prior to use. As described in `Section 3.1.2`_. :param scope: OPTIONAL. The scope of the access request as described by Section 3.3`_. These may be any string but are commonly URIs or various categories such as ``videos`` or ``documents``. :param state: RECOMMENDED. An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery as described in `Section 10.12`_. :param kwargs: Extra arguments to include in the request URI. In addition to supplied parameters, OAuthLib will append the ``client_id`` that was provided in the constructor as well as the mandatory ``response_type`` argument, set to ``token``:: >>> from oauthlib.oauth2 import MobileApplicationClient >>> client = MobileApplicationClient('your_id') >>> client.prepare_request_uri('https://example.com') 'https://example.com?client_id=your_id&response_type=token' >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback') 'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback' >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures']) 'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures' >>> client.prepare_request_uri('https://example.com', foo='bar') 'https://example.com?client_id=your_id&response_type=token&foo=bar' .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 """ return prepare_grant_uri(uri, self.client_id, self.response_type, redirect_uri=redirect_uri, state=state, scope=scope, **kwargs)
python
def prepare_request_uri(self, uri, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the implicit grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the "application/x-www-form-urlencoded" format, per `Appendix B`_: :param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI and it should have been registerd with the OAuth provider prior to use. As described in `Section 3.1.2`_. :param scope: OPTIONAL. The scope of the access request as described by Section 3.3`_. These may be any string but are commonly URIs or various categories such as ``videos`` or ``documents``. :param state: RECOMMENDED. An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery as described in `Section 10.12`_. :param kwargs: Extra arguments to include in the request URI. In addition to supplied parameters, OAuthLib will append the ``client_id`` that was provided in the constructor as well as the mandatory ``response_type`` argument, set to ``token``:: >>> from oauthlib.oauth2 import MobileApplicationClient >>> client = MobileApplicationClient('your_id') >>> client.prepare_request_uri('https://example.com') 'https://example.com?client_id=your_id&response_type=token' >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback') 'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback' >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures']) 'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures' >>> client.prepare_request_uri('https://example.com', foo='bar') 'https://example.com?client_id=your_id&response_type=token&foo=bar' .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12 """ return prepare_grant_uri(uri, self.client_id, self.response_type, redirect_uri=redirect_uri, state=state, scope=scope, **kwargs)
[ "def", "prepare_request_uri", "(", "self", ",", "uri", ",", "redirect_uri", "=", "None", ",", "scope", "=", "None", ",", "state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "prepare_grant_uri", "(", "uri", ",", "self", ".", "client_id", ...
Prepare the implicit grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI using the "application/x-www-form-urlencoded" format, per `Appendix B`_: :param redirect_uri: OPTIONAL. The redirect URI must be an absolute URI and it should have been registerd with the OAuth provider prior to use. As described in `Section 3.1.2`_. :param scope: OPTIONAL. The scope of the access request as described by Section 3.3`_. These may be any string but are commonly URIs or various categories such as ``videos`` or ``documents``. :param state: RECOMMENDED. An opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user-agent back to the client. The parameter SHOULD be used for preventing cross-site request forgery as described in `Section 10.12`_. :param kwargs: Extra arguments to include in the request URI. In addition to supplied parameters, OAuthLib will append the ``client_id`` that was provided in the constructor as well as the mandatory ``response_type`` argument, set to ``token``:: >>> from oauthlib.oauth2 import MobileApplicationClient >>> client = MobileApplicationClient('your_id') >>> client.prepare_request_uri('https://example.com') 'https://example.com?client_id=your_id&response_type=token' >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback') 'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback' >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures']) 'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures' >>> client.prepare_request_uri('https://example.com', foo='bar') 'https://example.com?client_id=your_id&response_type=token&foo=bar' .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2 .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
[ "Prepare", "the", "implicit", "grant", "request", "URI", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/mobile_application.py#L51-L97
train
224,663
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/clients/mobile_application.py
MobileApplicationClient.parse_request_uri_response
def parse_request_uri_response(self, uri, state=None, scope=None): """Parse the response URI fragment. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the "application/x-www-form-urlencoded" format: :param uri: The callback URI that resulted from the user being redirected back from the provider to you, the client. :param state: The state provided in the authorization request. :param scope: The scopes provided in the authorization request. :return: Dictionary of token parameters. :raises: OAuth2Error if response is invalid. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. **state** If you provided the state parameter in the authorization phase, then the provider is required to include that exact state value in the response. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. A few example responses can be seen below:: >>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world' >>> from oauthlib.oauth2 import MobileApplicationClient >>> client = MobileApplicationClient('your_id') >>> client.parse_request_uri_response(response_uri) { 'access_token': 'sdlfkj452', 'token_type': 'Bearer', 'state': 'ss345asyht', 'scope': [u'hello', u'world'] } >>> client.parse_request_uri_response(response_uri, state='other') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response **scope** File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response raise ValueError("Mismatching or missing state in params.") ValueError: Mismatching or missing state in params. >>> def alert_scope_changed(message, old, new): ... print(message, old, new) ... >>> oauthlib.signals.scope_changed.connect(alert_scope_changed) >>> client.parse_request_body_response(response_body, scope=['other']) ('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world']) .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 """ self.token = parse_implicit_response(uri, state=state, scope=scope) self.populate_token_attributes(self.token) return self.token
python
def parse_request_uri_response(self, uri, state=None, scope=None): """Parse the response URI fragment. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the "application/x-www-form-urlencoded" format: :param uri: The callback URI that resulted from the user being redirected back from the provider to you, the client. :param state: The state provided in the authorization request. :param scope: The scopes provided in the authorization request. :return: Dictionary of token parameters. :raises: OAuth2Error if response is invalid. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. **state** If you provided the state parameter in the authorization phase, then the provider is required to include that exact state value in the response. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. A few example responses can be seen below:: >>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world' >>> from oauthlib.oauth2 import MobileApplicationClient >>> client = MobileApplicationClient('your_id') >>> client.parse_request_uri_response(response_uri) { 'access_token': 'sdlfkj452', 'token_type': 'Bearer', 'state': 'ss345asyht', 'scope': [u'hello', u'world'] } >>> client.parse_request_uri_response(response_uri, state='other') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response **scope** File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response raise ValueError("Mismatching or missing state in params.") ValueError: Mismatching or missing state in params. >>> def alert_scope_changed(message, old, new): ... print(message, old, new) ... >>> oauthlib.signals.scope_changed.connect(alert_scope_changed) >>> client.parse_request_body_response(response_body, scope=['other']) ('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world']) .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 """ self.token = parse_implicit_response(uri, state=state, scope=scope) self.populate_token_attributes(self.token) return self.token
[ "def", "parse_request_uri_response", "(", "self", ",", "uri", ",", "state", "=", "None", ",", "scope", "=", "None", ")", ":", "self", ".", "token", "=", "parse_implicit_response", "(", "uri", ",", "state", "=", "state", ",", "scope", "=", "scope", ")", ...
Parse the response URI fragment. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the "application/x-www-form-urlencoded" format: :param uri: The callback URI that resulted from the user being redirected back from the provider to you, the client. :param state: The state provided in the authorization request. :param scope: The scopes provided in the authorization request. :return: Dictionary of token parameters. :raises: OAuth2Error if response is invalid. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. **state** If you provided the state parameter in the authorization phase, then the provider is required to include that exact state value in the response. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. A few example responses can be seen below:: >>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world' >>> from oauthlib.oauth2 import MobileApplicationClient >>> client = MobileApplicationClient('your_id') >>> client.parse_request_uri_response(response_uri) { 'access_token': 'sdlfkj452', 'token_type': 'Bearer', 'state': 'ss345asyht', 'scope': [u'hello', u'world'] } >>> client.parse_request_uri_response(response_uri, state='other') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response **scope** File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response raise ValueError("Mismatching or missing state in params.") ValueError: Mismatching or missing state in params. >>> def alert_scope_changed(message, old, new): ... print(message, old, new) ... >>> oauthlib.signals.scope_changed.connect(alert_scope_changed) >>> client.parse_request_body_response(response_body, scope=['other']) ('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world']) .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
[ "Parse", "the", "response", "URI", "fragment", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/mobile_application.py#L99-L174
train
224,664
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/request_validator.py
RequestValidator.confirm_redirect_uri
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, *args, **kwargs): """Ensure that the authorization process represented by this authorization code began with this 'redirect_uri'. If the client specifies a redirect_uri when obtaining code then that redirect URI must be bound to the code and verified equal in this method, according to RFC 6749 section 4.1.3. Do not compare against the client's allowed redirect URIs, but against the URI used when the code was saved. :param client_id: Unicode client identifier. :param code: Unicode authorization_code. :param redirect_uri: Unicode absolute URI. :param client: Client object set by you, see ``.authenticate_client``. :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is used by: - Authorization Code Grant (during token request) """ raise NotImplementedError('Subclasses must implement this method.')
python
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, *args, **kwargs): """Ensure that the authorization process represented by this authorization code began with this 'redirect_uri'. If the client specifies a redirect_uri when obtaining code then that redirect URI must be bound to the code and verified equal in this method, according to RFC 6749 section 4.1.3. Do not compare against the client's allowed redirect URIs, but against the URI used when the code was saved. :param client_id: Unicode client identifier. :param code: Unicode authorization_code. :param redirect_uri: Unicode absolute URI. :param client: Client object set by you, see ``.authenticate_client``. :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is used by: - Authorization Code Grant (during token request) """ raise NotImplementedError('Subclasses must implement this method.')
[ "def", "confirm_redirect_uri", "(", "self", ",", "client_id", ",", "code", ",", "redirect_uri", ",", "client", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'Subclasses must implement this method.'", "...
Ensure that the authorization process represented by this authorization code began with this 'redirect_uri'. If the client specifies a redirect_uri when obtaining code then that redirect URI must be bound to the code and verified equal in this method, according to RFC 6749 section 4.1.3. Do not compare against the client's allowed redirect URIs, but against the URI used when the code was saved. :param client_id: Unicode client identifier. :param code: Unicode authorization_code. :param redirect_uri: Unicode absolute URI. :param client: Client object set by you, see ``.authenticate_client``. :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is used by: - Authorization Code Grant (during token request)
[ "Ensure", "that", "the", "authorization", "process", "represented", "by", "this", "authorization", "code", "began", "with", "this", "redirect_uri", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/request_validator.py#L89-L111
train
224,665
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/request_validator.py
RequestValidator.save_token
def save_token(self, token, request, *args, **kwargs): """Persist the token with a token type specific method. Currently, only save_bearer_token is supported. :param token: A (Bearer) token dict. :param request: OAuthlib request. :type request: oauthlib.common.Request """ return self.save_bearer_token(token, request, *args, **kwargs)
python
def save_token(self, token, request, *args, **kwargs): """Persist the token with a token type specific method. Currently, only save_bearer_token is supported. :param token: A (Bearer) token dict. :param request: OAuthlib request. :type request: oauthlib.common.Request """ return self.save_bearer_token(token, request, *args, **kwargs)
[ "def", "save_token", "(", "self", ",", "token", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "save_bearer_token", "(", "token", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Persist the token with a token type specific method. Currently, only save_bearer_token is supported. :param token: A (Bearer) token dict. :param request: OAuthlib request. :type request: oauthlib.common.Request
[ "Persist", "the", "token", "with", "a", "token", "type", "specific", "method", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/request_validator.py#L294-L303
train
224,666
oauthlib/oauthlib
oauthlib/common.py
encode_params_utf8
def encode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are encoded to bytestrings using UTF-8 """ encoded = [] for k, v in params: encoded.append(( k.encode('utf-8') if isinstance(k, unicode_type) else k, v.encode('utf-8') if isinstance(v, unicode_type) else v)) return encoded
python
def encode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are encoded to bytestrings using UTF-8 """ encoded = [] for k, v in params: encoded.append(( k.encode('utf-8') if isinstance(k, unicode_type) else k, v.encode('utf-8') if isinstance(v, unicode_type) else v)) return encoded
[ "def", "encode_params_utf8", "(", "params", ")", ":", "encoded", "=", "[", "]", "for", "k", ",", "v", "in", "params", ":", "encoded", ".", "append", "(", "(", "k", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "k", ",", "unicode_type",...
Ensures that all parameters in a list of 2-element tuples are encoded to bytestrings using UTF-8
[ "Ensures", "that", "all", "parameters", "in", "a", "list", "of", "2", "-", "element", "tuples", "are", "encoded", "to", "bytestrings", "using", "UTF", "-", "8" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L92-L101
train
224,667
oauthlib/oauthlib
oauthlib/common.py
decode_params_utf8
def decode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8. """ decoded = [] for k, v in params: decoded.append(( k.decode('utf-8') if isinstance(k, bytes) else k, v.decode('utf-8') if isinstance(v, bytes) else v)) return decoded
python
def decode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8. """ decoded = [] for k, v in params: decoded.append(( k.decode('utf-8') if isinstance(k, bytes) else k, v.decode('utf-8') if isinstance(v, bytes) else v)) return decoded
[ "def", "decode_params_utf8", "(", "params", ")", ":", "decoded", "=", "[", "]", "for", "k", ",", "v", "in", "params", ":", "decoded", ".", "append", "(", "(", "k", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "k", ",", "bytes", ")",...
Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8.
[ "Ensures", "that", "all", "parameters", "in", "a", "list", "of", "2", "-", "element", "tuples", "are", "decoded", "to", "unicode", "using", "UTF", "-", "8", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L104-L113
train
224,668
oauthlib/oauthlib
oauthlib/common.py
urldecode
def urldecode(query): """Decode a query string in x-www-form-urlencoded format into a sequence of two-element tuples. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce correct formatting of the query string by validation. If validation fails a ValueError will be raised. urllib.parse_qsl will only raise errors if any of name-value pairs omits the equals sign. """ # Check if query contains invalid characters if query and not set(query) <= urlencoded: error = ("Error trying to decode a non urlencoded string. " "Found invalid characters: %s " "in the string: '%s'. " "Please ensure the request/response body is " "x-www-form-urlencoded.") raise ValueError(error % (set(query) - urlencoded, query)) # Check for correctly hex encoded values using a regular expression # All encoded values begin with % followed by two hex characters # correct = %00, %A0, %0A, %FF # invalid = %G0, %5H, %PO if INVALID_HEX_PATTERN.search(query): raise ValueError('Invalid hex encoding in query string.') # We encode to utf-8 prior to parsing because parse_qsl behaves # differently on unicode input in python 2 and 3. # Python 2.7 # >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6') # u'\xe5\x95\xa6\xe5\x95\xa6' # Python 2.7, non unicode input gives the same # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6') # '\xe5\x95\xa6\xe5\x95\xa6' # but now we can decode it to unicode # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8') # u'\u5566\u5566' # Python 3.3 however # >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6') # u'\u5566\u5566' query = query.encode( 'utf-8') if not PY3 and isinstance(query, unicode_type) else query # We want to allow queries such as "c2" whereas urlparse.parse_qsl # with the strict_parsing flag will not. params = urlparse.parse_qsl(query, keep_blank_values=True) # unicode all the things return decode_params_utf8(params)
python
def urldecode(query): """Decode a query string in x-www-form-urlencoded format into a sequence of two-element tuples. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce correct formatting of the query string by validation. If validation fails a ValueError will be raised. urllib.parse_qsl will only raise errors if any of name-value pairs omits the equals sign. """ # Check if query contains invalid characters if query and not set(query) <= urlencoded: error = ("Error trying to decode a non urlencoded string. " "Found invalid characters: %s " "in the string: '%s'. " "Please ensure the request/response body is " "x-www-form-urlencoded.") raise ValueError(error % (set(query) - urlencoded, query)) # Check for correctly hex encoded values using a regular expression # All encoded values begin with % followed by two hex characters # correct = %00, %A0, %0A, %FF # invalid = %G0, %5H, %PO if INVALID_HEX_PATTERN.search(query): raise ValueError('Invalid hex encoding in query string.') # We encode to utf-8 prior to parsing because parse_qsl behaves # differently on unicode input in python 2 and 3. # Python 2.7 # >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6') # u'\xe5\x95\xa6\xe5\x95\xa6' # Python 2.7, non unicode input gives the same # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6') # '\xe5\x95\xa6\xe5\x95\xa6' # but now we can decode it to unicode # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8') # u'\u5566\u5566' # Python 3.3 however # >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6') # u'\u5566\u5566' query = query.encode( 'utf-8') if not PY3 and isinstance(query, unicode_type) else query # We want to allow queries such as "c2" whereas urlparse.parse_qsl # with the strict_parsing flag will not. params = urlparse.parse_qsl(query, keep_blank_values=True) # unicode all the things return decode_params_utf8(params)
[ "def", "urldecode", "(", "query", ")", ":", "# Check if query contains invalid characters", "if", "query", "and", "not", "set", "(", "query", ")", "<=", "urlencoded", ":", "error", "=", "(", "\"Error trying to decode a non urlencoded string. \"", "\"Found invalid characte...
Decode a query string in x-www-form-urlencoded format into a sequence of two-element tuples. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce correct formatting of the query string by validation. If validation fails a ValueError will be raised. urllib.parse_qsl will only raise errors if any of name-value pairs omits the equals sign.
[ "Decode", "a", "query", "string", "in", "x", "-", "www", "-", "form", "-", "urlencoded", "format", "into", "a", "sequence", "of", "two", "-", "element", "tuples", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L119-L165
train
224,669
oauthlib/oauthlib
oauthlib/common.py
extract_params
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None. """ if isinstance(raw, (bytes, unicode_type)): try: params = urldecode(raw) except ValueError: params = None elif hasattr(raw, '__iter__'): try: dict(raw) except ValueError: params = None except TypeError: params = None else: params = list(raw.items() if isinstance(raw, dict) else raw) params = decode_params_utf8(params) else: params = None return params
python
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None. """ if isinstance(raw, (bytes, unicode_type)): try: params = urldecode(raw) except ValueError: params = None elif hasattr(raw, '__iter__'): try: dict(raw) except ValueError: params = None except TypeError: params = None else: params = list(raw.items() if isinstance(raw, dict) else raw) params = decode_params_utf8(params) else: params = None return params
[ "def", "extract_params", "(", "raw", ")", ":", "if", "isinstance", "(", "raw", ",", "(", "bytes", ",", "unicode_type", ")", ")", ":", "try", ":", "params", "=", "urldecode", "(", "raw", ")", "except", "ValueError", ":", "params", "=", "None", "elif", ...
Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None.
[ "Extract", "parameters", "and", "return", "them", "as", "a", "list", "of", "2", "-", "tuples", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L168-L194
train
224,670
oauthlib/oauthlib
oauthlib/common.py
generate_token
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET): """Generates a non-guessable OAuth token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is important. Which is why SystemRandom is used instead of the default random.choice method. """ rand = SystemRandom() return ''.join(rand.choice(chars) for x in range(length))
python
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET): """Generates a non-guessable OAuth token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is important. Which is why SystemRandom is used instead of the default random.choice method. """ rand = SystemRandom() return ''.join(rand.choice(chars) for x in range(length))
[ "def", "generate_token", "(", "length", "=", "30", ",", "chars", "=", "UNICODE_ASCII_CHARACTER_SET", ")", ":", "rand", "=", "SystemRandom", "(", ")", "return", "''", ".", "join", "(", "rand", ".", "choice", "(", "chars", ")", "for", "x", "in", "range", ...
Generates a non-guessable OAuth token OAuth (1 and 2) does not specify the format of tokens except that they should be strings of random characters. Tokens should not be guessable and entropy when generating the random characters is important. Which is why SystemRandom is used instead of the default random.choice method.
[ "Generates", "a", "non", "-", "guessable", "OAuth", "token" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L224-L233
train
224,671
oauthlib/oauthlib
oauthlib/common.py
add_params_to_qs
def add_params_to_qs(query, params): """Extend a query with a list of two-tuples.""" if isinstance(params, dict): params = params.items() queryparams = urlparse.parse_qsl(query, keep_blank_values=True) queryparams.extend(params) return urlencode(queryparams)
python
def add_params_to_qs(query, params): """Extend a query with a list of two-tuples.""" if isinstance(params, dict): params = params.items() queryparams = urlparse.parse_qsl(query, keep_blank_values=True) queryparams.extend(params) return urlencode(queryparams)
[ "def", "add_params_to_qs", "(", "query", ",", "params", ")", ":", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "params", "=", "params", ".", "items", "(", ")", "queryparams", "=", "urlparse", ".", "parse_qsl", "(", "query", ",", "keep_blank_...
Extend a query with a list of two-tuples.
[ "Extend", "a", "query", "with", "a", "list", "of", "two", "-", "tuples", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L269-L275
train
224,672
oauthlib/oauthlib
oauthlib/common.py
add_params_to_uri
def add_params_to_uri(uri, params, fragment=False): """Add a list of two-tuples to the uri query components.""" sch, net, path, par, query, fra = urlparse.urlparse(uri) if fragment: fra = add_params_to_qs(fra, params) else: query = add_params_to_qs(query, params) return urlparse.urlunparse((sch, net, path, par, query, fra))
python
def add_params_to_uri(uri, params, fragment=False): """Add a list of two-tuples to the uri query components.""" sch, net, path, par, query, fra = urlparse.urlparse(uri) if fragment: fra = add_params_to_qs(fra, params) else: query = add_params_to_qs(query, params) return urlparse.urlunparse((sch, net, path, par, query, fra))
[ "def", "add_params_to_uri", "(", "uri", ",", "params", ",", "fragment", "=", "False", ")", ":", "sch", ",", "net", ",", "path", ",", "par", ",", "query", ",", "fra", "=", "urlparse", ".", "urlparse", "(", "uri", ")", "if", "fragment", ":", "fra", "...
Add a list of two-tuples to the uri query components.
[ "Add", "a", "list", "of", "two", "-", "tuples", "to", "the", "uri", "query", "components", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L278-L285
train
224,673
oauthlib/oauthlib
oauthlib/common.py
to_unicode
def to_unicode(data, encoding='UTF-8'): """Convert a number of different types of objects to unicode.""" if isinstance(data, unicode_type): return data if isinstance(data, bytes): return unicode_type(data, encoding=encoding) if hasattr(data, '__iter__'): try: dict(data) except TypeError: pass except ValueError: # Assume it's a one dimensional data structure return (to_unicode(i, encoding) for i in data) else: # We support 2.6 which lacks dict comprehensions if hasattr(data, 'items'): data = data.items() return dict(((to_unicode(k, encoding), to_unicode(v, encoding)) for k, v in data)) return data
python
def to_unicode(data, encoding='UTF-8'): """Convert a number of different types of objects to unicode.""" if isinstance(data, unicode_type): return data if isinstance(data, bytes): return unicode_type(data, encoding=encoding) if hasattr(data, '__iter__'): try: dict(data) except TypeError: pass except ValueError: # Assume it's a one dimensional data structure return (to_unicode(i, encoding) for i in data) else: # We support 2.6 which lacks dict comprehensions if hasattr(data, 'items'): data = data.items() return dict(((to_unicode(k, encoding), to_unicode(v, encoding)) for k, v in data)) return data
[ "def", "to_unicode", "(", "data", ",", "encoding", "=", "'UTF-8'", ")", ":", "if", "isinstance", "(", "data", ",", "unicode_type", ")", ":", "return", "data", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "return", "unicode_type", "(", "data",...
Convert a number of different types of objects to unicode.
[ "Convert", "a", "number", "of", "different", "types", "of", "objects", "to", "unicode", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L306-L328
train
224,674
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/parameters.py
_append_params
def _append_params(oauth_params, params): """Append OAuth params to an existing set of parameters. Both params and oauth_params is must be lists of 2-tuples. Per `section 3.5.2`_ and `3.5.3`_ of the spec. .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 .. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 """ merged = list(params) merged.extend(oauth_params) # The request URI / entity-body MAY include other request-specific # parameters, in which case, the protocol parameters SHOULD be appended # following the request-specific parameters, properly separated by an "&" # character (ASCII code 38) merged.sort(key=lambda i: i[0].startswith('oauth_')) return merged
python
def _append_params(oauth_params, params): """Append OAuth params to an existing set of parameters. Both params and oauth_params is must be lists of 2-tuples. Per `section 3.5.2`_ and `3.5.3`_ of the spec. .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 .. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 """ merged = list(params) merged.extend(oauth_params) # The request URI / entity-body MAY include other request-specific # parameters, in which case, the protocol parameters SHOULD be appended # following the request-specific parameters, properly separated by an "&" # character (ASCII code 38) merged.sort(key=lambda i: i[0].startswith('oauth_')) return merged
[ "def", "_append_params", "(", "oauth_params", ",", "params", ")", ":", "merged", "=", "list", "(", "params", ")", "merged", ".", "extend", "(", "oauth_params", ")", "# The request URI / entity-body MAY include other request-specific", "# parameters, in which case, the proto...
Append OAuth params to an existing set of parameters. Both params and oauth_params is must be lists of 2-tuples. Per `section 3.5.2`_ and `3.5.3`_ of the spec. .. _`section 3.5.2`: https://tools.ietf.org/html/rfc5849#section-3.5.2 .. _`3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
[ "Append", "OAuth", "params", "to", "an", "existing", "set", "of", "parameters", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/parameters.py#L94-L112
train
224,675
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/parameters.py
prepare_request_uri_query
def prepare_request_uri_query(oauth_params, uri): """Prepare the Request URI Query. Per `section 3.5.3`_ of the spec. .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 """ # append OAuth params to the existing set of query components sch, net, path, par, query, fra = urlparse(uri) query = urlencode( _append_params(oauth_params, extract_params(query) or [])) return urlunparse((sch, net, path, par, query, fra))
python
def prepare_request_uri_query(oauth_params, uri): """Prepare the Request URI Query. Per `section 3.5.3`_ of the spec. .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3 """ # append OAuth params to the existing set of query components sch, net, path, par, query, fra = urlparse(uri) query = urlencode( _append_params(oauth_params, extract_params(query) or [])) return urlunparse((sch, net, path, par, query, fra))
[ "def", "prepare_request_uri_query", "(", "oauth_params", ",", "uri", ")", ":", "# append OAuth params to the existing set of query components", "sch", ",", "net", ",", "path", ",", "par", ",", "query", ",", "fra", "=", "urlparse", "(", "uri", ")", "query", "=", ...
Prepare the Request URI Query. Per `section 3.5.3`_ of the spec. .. _`section 3.5.3`: https://tools.ietf.org/html/rfc5849#section-3.5.3
[ "Prepare", "the", "Request", "URI", "Query", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/parameters.py#L127-L139
train
224,676
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/request_token.py
RequestTokenEndpoint.validate_request_token_request
def validate_request_token_request(self, request): """Validate a request token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation result (True or False). 2. The request object. """ self._check_transport_security(request) self._check_mandatory_parameters(request) if request.realm: request.realms = request.realm.split(' ') else: request.realms = self.request_validator.get_default_realms( request.client_key, request) if not self.request_validator.check_realms(request.realms): raise errors.InvalidRequestError( description='Invalid realm %s. Allowed are %r.' % ( request.realms, self.request_validator.realms)) if not request.redirect_uri: raise errors.InvalidRequestError( description='Missing callback URI.') if not self.request_validator.validate_timestamp_and_nonce( request.client_key, request.timestamp, request.nonce, request, request_token=request.resource_owner_key): return False, request # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid client credentials. # Note: This is postponed in order to avoid timing attacks, instead # a dummy client is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable client enumeration valid_client = self.request_validator.validate_client_key( request.client_key, request) if not valid_client: request.client_key = self.request_validator.dummy_client # Note that `realm`_ is only used in authorization headers and how # it should be interepreted is not included in the OAuth spec. # However they could be seen as a scope or realm to which the # client has access and as such every client should be checked # to ensure it is authorized access to that scope or realm. # .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2 # # Note that early exit would enable client realm access enumeration. # # The require_realm indicates this is the first step in the OAuth # workflow where a client requests access to a specific realm. # This first step (obtaining request token) need not require a realm # and can then be identified by checking the require_resource_owner # flag and abscence of realm. # # Clients obtaining an access token will not supply a realm and it will # not be checked. Instead the previously requested realm should be # transferred from the request token to the access token. # # Access to protected resources will always validate the realm but note # that the realm is now tied to the access token and not provided by # the client. valid_realm = self.request_validator.validate_requested_realms( request.client_key, request.realms, request) # Callback is normally never required, except for requests for # a Temporary Credential as described in `Section 2.1`_ # .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 valid_redirect = self.request_validator.validate_redirect_uri( request.client_key, request.redirect_uri, request) if not request.redirect_uri: raise NotImplementedError('Redirect URI must either be provided ' 'or set to a default during validation.') valid_signature = self._check_signature(request) # log the results to the validator_log # this lets us handle internal reporting and analysis request.validator_log['client'] = valid_client request.validator_log['realm'] = valid_realm request.validator_log['callback'] = valid_redirect request.validator_log['signature'] = valid_signature # We delay checking validity until the very end, using dummy values for # calculations and fetching secrets/keys to ensure the flow of every # request remains almost identical regardless of whether valid values # have been supplied. This ensures near constant time execution and # prevents malicious users from guessing sensitive information v = all((valid_client, valid_realm, valid_redirect, valid_signature)) if not v: log.info("[Failure] request verification failed.") log.info("Valid client: %s.", valid_client) log.info("Valid realm: %s.", valid_realm) log.info("Valid callback: %s.", valid_redirect) log.info("Valid signature: %s.", valid_signature) return v, request
python
def validate_request_token_request(self, request): """Validate a request token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation result (True or False). 2. The request object. """ self._check_transport_security(request) self._check_mandatory_parameters(request) if request.realm: request.realms = request.realm.split(' ') else: request.realms = self.request_validator.get_default_realms( request.client_key, request) if not self.request_validator.check_realms(request.realms): raise errors.InvalidRequestError( description='Invalid realm %s. Allowed are %r.' % ( request.realms, self.request_validator.realms)) if not request.redirect_uri: raise errors.InvalidRequestError( description='Missing callback URI.') if not self.request_validator.validate_timestamp_and_nonce( request.client_key, request.timestamp, request.nonce, request, request_token=request.resource_owner_key): return False, request # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid client credentials. # Note: This is postponed in order to avoid timing attacks, instead # a dummy client is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable client enumeration valid_client = self.request_validator.validate_client_key( request.client_key, request) if not valid_client: request.client_key = self.request_validator.dummy_client # Note that `realm`_ is only used in authorization headers and how # it should be interepreted is not included in the OAuth spec. # However they could be seen as a scope or realm to which the # client has access and as such every client should be checked # to ensure it is authorized access to that scope or realm. # .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2 # # Note that early exit would enable client realm access enumeration. # # The require_realm indicates this is the first step in the OAuth # workflow where a client requests access to a specific realm. # This first step (obtaining request token) need not require a realm # and can then be identified by checking the require_resource_owner # flag and abscence of realm. # # Clients obtaining an access token will not supply a realm and it will # not be checked. Instead the previously requested realm should be # transferred from the request token to the access token. # # Access to protected resources will always validate the realm but note # that the realm is now tied to the access token and not provided by # the client. valid_realm = self.request_validator.validate_requested_realms( request.client_key, request.realms, request) # Callback is normally never required, except for requests for # a Temporary Credential as described in `Section 2.1`_ # .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 valid_redirect = self.request_validator.validate_redirect_uri( request.client_key, request.redirect_uri, request) if not request.redirect_uri: raise NotImplementedError('Redirect URI must either be provided ' 'or set to a default during validation.') valid_signature = self._check_signature(request) # log the results to the validator_log # this lets us handle internal reporting and analysis request.validator_log['client'] = valid_client request.validator_log['realm'] = valid_realm request.validator_log['callback'] = valid_redirect request.validator_log['signature'] = valid_signature # We delay checking validity until the very end, using dummy values for # calculations and fetching secrets/keys to ensure the flow of every # request remains almost identical regardless of whether valid values # have been supplied. This ensures near constant time execution and # prevents malicious users from guessing sensitive information v = all((valid_client, valid_realm, valid_redirect, valid_signature)) if not v: log.info("[Failure] request verification failed.") log.info("Valid client: %s.", valid_client) log.info("Valid realm: %s.", valid_realm) log.info("Valid callback: %s.", valid_redirect) log.info("Valid signature: %s.", valid_signature) return v, request
[ "def", "validate_request_token_request", "(", "self", ",", "request", ")", ":", "self", ".", "_check_transport_security", "(", "request", ")", "self", ".", "_check_mandatory_parameters", "(", "request", ")", "if", "request", ".", "realm", ":", "request", ".", "r...
Validate a request token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation result (True or False). 2. The request object.
[ "Validate", "a", "request", "token", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/request_token.py#L112-L211
train
224,677
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/endpoints/signature_only.py
SignatureOnlyEndpoint.validate_request
def validate_request(self, uri, http_method='GET', body=None, headers=None): """Validate a signed OAuth request. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns: A tuple of 2 elements. 1. True if valid, False otherwise. 2. An oauthlib.common.Request object. """ try: request = self._create_request(uri, http_method, body, headers) except errors.OAuth1Error as err: log.info( 'Exception caught while validating request, %s.' % err) return False, None try: self._check_transport_security(request) self._check_mandatory_parameters(request) except errors.OAuth1Error as err: log.info( 'Exception caught while validating request, %s.' % err) return False, request if not self.request_validator.validate_timestamp_and_nonce( request.client_key, request.timestamp, request.nonce, request): log.debug('[Failure] verification failed: timestamp/nonce') return False, request # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid client credentials. # Note: This is postponed in order to avoid timing attacks, instead # a dummy client is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable client enumeration valid_client = self.request_validator.validate_client_key( request.client_key, request) if not valid_client: request.client_key = self.request_validator.dummy_client valid_signature = self._check_signature(request) # log the results to the validator_log # this lets us handle internal reporting and analysis request.validator_log['client'] = valid_client request.validator_log['signature'] = valid_signature # We delay checking validity until the very end, using dummy values for # calculations and fetching secrets/keys to ensure the flow of every # request remains almost identical regardless of whether valid values # have been supplied. This ensures near constant time execution and # prevents malicious users from guessing sensitive information v = all((valid_client, valid_signature)) if not v: log.info("[Failure] request verification failed.") log.info("Valid client: %s", valid_client) log.info("Valid signature: %s", valid_signature) return v, request
python
def validate_request(self, uri, http_method='GET', body=None, headers=None): """Validate a signed OAuth request. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns: A tuple of 2 elements. 1. True if valid, False otherwise. 2. An oauthlib.common.Request object. """ try: request = self._create_request(uri, http_method, body, headers) except errors.OAuth1Error as err: log.info( 'Exception caught while validating request, %s.' % err) return False, None try: self._check_transport_security(request) self._check_mandatory_parameters(request) except errors.OAuth1Error as err: log.info( 'Exception caught while validating request, %s.' % err) return False, request if not self.request_validator.validate_timestamp_and_nonce( request.client_key, request.timestamp, request.nonce, request): log.debug('[Failure] verification failed: timestamp/nonce') return False, request # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid client credentials. # Note: This is postponed in order to avoid timing attacks, instead # a dummy client is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable client enumeration valid_client = self.request_validator.validate_client_key( request.client_key, request) if not valid_client: request.client_key = self.request_validator.dummy_client valid_signature = self._check_signature(request) # log the results to the validator_log # this lets us handle internal reporting and analysis request.validator_log['client'] = valid_client request.validator_log['signature'] = valid_signature # We delay checking validity until the very end, using dummy values for # calculations and fetching secrets/keys to ensure the flow of every # request remains almost identical regardless of whether valid values # have been supplied. This ensures near constant time execution and # prevents malicious users from guessing sensitive information v = all((valid_client, valid_signature)) if not v: log.info("[Failure] request verification failed.") log.info("Valid client: %s", valid_client) log.info("Valid signature: %s", valid_signature) return v, request
[ "def", "validate_request", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "try", ":", "request", "=", "self", ".", "_create_request", "(", "uri", ",", "http_method", ",", "bod...
Validate a signed OAuth request. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :returns: A tuple of 2 elements. 1. True if valid, False otherwise. 2. An oauthlib.common.Request object.
[ "Validate", "a", "signed", "OAuth", "request", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/signature_only.py#L23-L84
train
224,678
oauthlib/oauthlib
oauthlib/openid/connect/core/tokens.py
JWTToken.create_token
def create_token(self, request, refresh_token=False): """Create a JWT Token, using requestvalidator method.""" if callable(self.expires_in): expires_in = self.expires_in(request) else: expires_in = self.expires_in request.expires_in = expires_in return self.request_validator.get_jwt_bearer_token(None, None, request)
python
def create_token(self, request, refresh_token=False): """Create a JWT Token, using requestvalidator method.""" if callable(self.expires_in): expires_in = self.expires_in(request) else: expires_in = self.expires_in request.expires_in = expires_in return self.request_validator.get_jwt_bearer_token(None, None, request)
[ "def", "create_token", "(", "self", ",", "request", ",", "refresh_token", "=", "False", ")", ":", "if", "callable", "(", "self", ".", "expires_in", ")", ":", "expires_in", "=", "self", ".", "expires_in", "(", "request", ")", "else", ":", "expires_in", "=...
Create a JWT Token, using requestvalidator method.
[ "Create", "a", "JWT", "Token", "using", "requestvalidator", "method", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/tokens.py#L28-L38
train
224,679
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client.get_oauth_signature
def get_oauth_signature(self, request): """Get an OAuth signature to be used in signing a request To satisfy `section 3.4.1.2`_ item 2, if the request argument's headers dict attribute contains a Host item, its value will replace any netloc part of the request argument's uri attribute value. .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 """ if self.signature_method == SIGNATURE_PLAINTEXT: # fast-path return signature.sign_plaintext(self.client_secret, self.resource_owner_secret) uri, headers, body = self._render(request) collected_params = signature.collect_parameters( uri_query=urlparse.urlparse(uri).query, body=body, headers=headers) log.debug("Collected params: {0}".format(collected_params)) normalized_params = signature.normalize_parameters(collected_params) normalized_uri = signature.base_string_uri(uri, headers.get('Host', None)) log.debug("Normalized params: {0}".format(normalized_params)) log.debug("Normalized URI: {0}".format(normalized_uri)) base_string = signature.signature_base_string(request.http_method, normalized_uri, normalized_params) log.debug("Signing: signature base string: {0}".format(base_string)) if self.signature_method not in self.SIGNATURE_METHODS: raise ValueError('Invalid signature method.') sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self) log.debug("Signature: {0}".format(sig)) return sig
python
def get_oauth_signature(self, request): """Get an OAuth signature to be used in signing a request To satisfy `section 3.4.1.2`_ item 2, if the request argument's headers dict attribute contains a Host item, its value will replace any netloc part of the request argument's uri attribute value. .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2 """ if self.signature_method == SIGNATURE_PLAINTEXT: # fast-path return signature.sign_plaintext(self.client_secret, self.resource_owner_secret) uri, headers, body = self._render(request) collected_params = signature.collect_parameters( uri_query=urlparse.urlparse(uri).query, body=body, headers=headers) log.debug("Collected params: {0}".format(collected_params)) normalized_params = signature.normalize_parameters(collected_params) normalized_uri = signature.base_string_uri(uri, headers.get('Host', None)) log.debug("Normalized params: {0}".format(normalized_params)) log.debug("Normalized URI: {0}".format(normalized_uri)) base_string = signature.signature_base_string(request.http_method, normalized_uri, normalized_params) log.debug("Signing: signature base string: {0}".format(base_string)) if self.signature_method not in self.SIGNATURE_METHODS: raise ValueError('Invalid signature method.') sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self) log.debug("Signature: {0}".format(sig)) return sig
[ "def", "get_oauth_signature", "(", "self", ",", "request", ")", ":", "if", "self", ".", "signature_method", "==", "SIGNATURE_PLAINTEXT", ":", "# fast-path", "return", "signature", ".", "sign_plaintext", "(", "self", ".", "client_secret", ",", "self", ".", "resou...
Get an OAuth signature to be used in signing a request To satisfy `section 3.4.1.2`_ item 2, if the request argument's headers dict attribute contains a Host item, its value will replace any netloc part of the request argument's uri attribute value. .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2
[ "Get", "an", "OAuth", "signature", "to", "be", "used", "in", "signing", "a", "request" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L112-L151
train
224,680
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client.get_oauth_params
def get_oauth_params(self, request): """Get the basic OAuth parameters to be used in generating a signature. """ nonce = (generate_nonce() if self.nonce is None else self.nonce) timestamp = (generate_timestamp() if self.timestamp is None else self.timestamp) params = [ ('oauth_nonce', nonce), ('oauth_timestamp', timestamp), ('oauth_version', '1.0'), ('oauth_signature_method', self.signature_method), ('oauth_consumer_key', self.client_key), ] if self.resource_owner_key: params.append(('oauth_token', self.resource_owner_key)) if self.callback_uri: params.append(('oauth_callback', self.callback_uri)) if self.verifier: params.append(('oauth_verifier', self.verifier)) # providing body hash for requests other than x-www-form-urlencoded # as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1 # 4.1.1. When to include the body hash # * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies # * [...] SHOULD include the oauth_body_hash parameter on all other requests. # Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2 # At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension. content_type = request.headers.get('Content-Type', None) content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0 if request.body is not None and content_type_eligible: params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8'))) return params
python
def get_oauth_params(self, request): """Get the basic OAuth parameters to be used in generating a signature. """ nonce = (generate_nonce() if self.nonce is None else self.nonce) timestamp = (generate_timestamp() if self.timestamp is None else self.timestamp) params = [ ('oauth_nonce', nonce), ('oauth_timestamp', timestamp), ('oauth_version', '1.0'), ('oauth_signature_method', self.signature_method), ('oauth_consumer_key', self.client_key), ] if self.resource_owner_key: params.append(('oauth_token', self.resource_owner_key)) if self.callback_uri: params.append(('oauth_callback', self.callback_uri)) if self.verifier: params.append(('oauth_verifier', self.verifier)) # providing body hash for requests other than x-www-form-urlencoded # as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1 # 4.1.1. When to include the body hash # * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies # * [...] SHOULD include the oauth_body_hash parameter on all other requests. # Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2 # At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension. content_type = request.headers.get('Content-Type', None) content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0 if request.body is not None and content_type_eligible: params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8'))) return params
[ "def", "get_oauth_params", "(", "self", ",", "request", ")", ":", "nonce", "=", "(", "generate_nonce", "(", ")", "if", "self", ".", "nonce", "is", "None", "else", "self", ".", "nonce", ")", "timestamp", "=", "(", "generate_timestamp", "(", ")", "if", "...
Get the basic OAuth parameters to be used in generating a signature.
[ "Get", "the", "basic", "OAuth", "parameters", "to", "be", "used", "in", "generating", "a", "signature", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L153-L186
train
224,681
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client._render
def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid formencoded string. """ # TODO what if there are body params on a header-type auth? # TODO what if there are query params on a body-type auth? uri, headers, body = request.uri, request.headers, request.body # TODO: right now these prepare_* methods are very narrow in scope--they # only affect their little thing. In some cases (for example, with # header auth) it might be advantageous to allow these methods to touch # other parts of the request, like the headers—so the prepare_headers # method could also set the Content-Type header to x-www-form-urlencoded # like the spec requires. This would be a fundamental change though, and # I'm not sure how I feel about it. if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER: headers = parameters.prepare_headers( request.oauth_params, request.headers, realm=realm) elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: body = parameters.prepare_form_encoded_body( request.oauth_params, request.decoded_body) if formencode: body = urlencode(body) headers['Content-Type'] = 'application/x-www-form-urlencoded' elif self.signature_type == SIGNATURE_TYPE_QUERY: uri = parameters.prepare_request_uri_query( request.oauth_params, request.uri) else: raise ValueError('Unknown signature type specified.') return uri, headers, body
python
def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid formencoded string. """ # TODO what if there are body params on a header-type auth? # TODO what if there are query params on a body-type auth? uri, headers, body = request.uri, request.headers, request.body # TODO: right now these prepare_* methods are very narrow in scope--they # only affect their little thing. In some cases (for example, with # header auth) it might be advantageous to allow these methods to touch # other parts of the request, like the headers—so the prepare_headers # method could also set the Content-Type header to x-www-form-urlencoded # like the spec requires. This would be a fundamental change though, and # I'm not sure how I feel about it. if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER: headers = parameters.prepare_headers( request.oauth_params, request.headers, realm=realm) elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None: body = parameters.prepare_form_encoded_body( request.oauth_params, request.decoded_body) if formencode: body = urlencode(body) headers['Content-Type'] = 'application/x-www-form-urlencoded' elif self.signature_type == SIGNATURE_TYPE_QUERY: uri = parameters.prepare_request_uri_query( request.oauth_params, request.uri) else: raise ValueError('Unknown signature type specified.') return uri, headers, body
[ "def", "_render", "(", "self", ",", "request", ",", "formencode", "=", "False", ",", "realm", "=", "None", ")", ":", "# TODO what if there are body params on a header-type auth?", "# TODO what if there are query params on a body-type auth?", "uri", ",", "headers", ",", "b...
Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid formencoded string.
[ "Render", "a", "signed", "request", "according", "to", "signature", "type" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L188-L223
train
224,682
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
Client.sign
def sign(self, uri, http_method='GET', body=None, headers=None, realm=None): """Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth signing process. Also worth noting is that duplicate parameters will be included in the signature, regardless of where they are specified (query, body). The body argument may be a dict, a list of 2-tuples, or a formencoded string. The Content-Type header must be 'application/x-www-form-urlencoded' if it is present. If the body argument is not one of the above, it will be returned verbatim as it is unaffected by the OAuth signing process. Attempting to sign a request with non-formencoded data using the OAuth body signature type is invalid and will raise an exception. If the body does contain parameters, it will be returned as a properly- formatted formencoded string. Body may not be included if the http_method is either GET or HEAD as this changes the semantic meaning of the request. All string data MUST be unicode or be encoded with the same encoding scheme supplied to the Client constructor, default utf-8. This includes strings inside body dicts, for example. """ # normalize request data request = Request(uri, http_method, body, headers, encoding=self.encoding) # sanity check content_type = request.headers.get('Content-Type', None) multipart = content_type and content_type.startswith('multipart/') should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED has_params = request.decoded_body is not None # 3.4.1.3.1. Parameter Sources # [Parameters are collected from the HTTP request entity-body, but only # if [...]: # * The entity-body is single-part. if multipart and has_params: raise ValueError( "Headers indicate a multipart body but body contains parameters.") # * The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. elif should_have_params and not has_params: raise ValueError( "Headers indicate a formencoded body but body was not decodable.") # * The HTTP request entity-header includes the "Content-Type" # header field set to "application/x-www-form-urlencoded". elif not should_have_params and has_params: raise ValueError( "Body contains parameters but Content-Type header was {0} " "instead of {1}".format(content_type or "not set", CONTENT_TYPE_FORM_URLENCODED)) # 3.5.2. Form-Encoded Body # Protocol parameters can be transmitted in the HTTP request entity- # body, but only if the following REQUIRED conditions are met: # o The entity-body is single-part. # o The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. # o The HTTP request entity-header includes the "Content-Type" header # field set to "application/x-www-form-urlencoded". elif self.signature_type == SIGNATURE_TYPE_BODY and not ( should_have_params and has_params and not multipart): raise ValueError( 'Body signatures may only be used with form-urlencoded content') # We amend https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 # with the clause that parameters from body should only be included # in non GET or HEAD requests. Extracting the request body parameters # and including them in the signature base string would give semantic # meaning to the body, which it should not have according to the # HTTP 1.1 spec. elif http_method.upper() in ('GET', 'HEAD') and has_params: raise ValueError('GET/HEAD requests should not include body.') # generate the basic OAuth parameters request.oauth_params = self.get_oauth_params(request) # generate the signature request.oauth_params.append( ('oauth_signature', self.get_oauth_signature(request))) # render the signed request and return it uri, headers, body = self._render(request, formencode=True, realm=(realm or self.realm)) if self.decoding: log.debug('Encoding URI, headers and body to %s.', self.decoding) uri = uri.encode(self.decoding) body = body.encode(self.decoding) if body else body new_headers = {} for k, v in headers.items(): new_headers[k.encode(self.decoding)] = v.encode(self.decoding) headers = new_headers return uri, headers, body
python
def sign(self, uri, http_method='GET', body=None, headers=None, realm=None): """Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth signing process. Also worth noting is that duplicate parameters will be included in the signature, regardless of where they are specified (query, body). The body argument may be a dict, a list of 2-tuples, or a formencoded string. The Content-Type header must be 'application/x-www-form-urlencoded' if it is present. If the body argument is not one of the above, it will be returned verbatim as it is unaffected by the OAuth signing process. Attempting to sign a request with non-formencoded data using the OAuth body signature type is invalid and will raise an exception. If the body does contain parameters, it will be returned as a properly- formatted formencoded string. Body may not be included if the http_method is either GET or HEAD as this changes the semantic meaning of the request. All string data MUST be unicode or be encoded with the same encoding scheme supplied to the Client constructor, default utf-8. This includes strings inside body dicts, for example. """ # normalize request data request = Request(uri, http_method, body, headers, encoding=self.encoding) # sanity check content_type = request.headers.get('Content-Type', None) multipart = content_type and content_type.startswith('multipart/') should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED has_params = request.decoded_body is not None # 3.4.1.3.1. Parameter Sources # [Parameters are collected from the HTTP request entity-body, but only # if [...]: # * The entity-body is single-part. if multipart and has_params: raise ValueError( "Headers indicate a multipart body but body contains parameters.") # * The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. elif should_have_params and not has_params: raise ValueError( "Headers indicate a formencoded body but body was not decodable.") # * The HTTP request entity-header includes the "Content-Type" # header field set to "application/x-www-form-urlencoded". elif not should_have_params and has_params: raise ValueError( "Body contains parameters but Content-Type header was {0} " "instead of {1}".format(content_type or "not set", CONTENT_TYPE_FORM_URLENCODED)) # 3.5.2. Form-Encoded Body # Protocol parameters can be transmitted in the HTTP request entity- # body, but only if the following REQUIRED conditions are met: # o The entity-body is single-part. # o The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # [W3C.REC-html40-19980424]. # o The HTTP request entity-header includes the "Content-Type" header # field set to "application/x-www-form-urlencoded". elif self.signature_type == SIGNATURE_TYPE_BODY and not ( should_have_params and has_params and not multipart): raise ValueError( 'Body signatures may only be used with form-urlencoded content') # We amend https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 # with the clause that parameters from body should only be included # in non GET or HEAD requests. Extracting the request body parameters # and including them in the signature base string would give semantic # meaning to the body, which it should not have according to the # HTTP 1.1 spec. elif http_method.upper() in ('GET', 'HEAD') and has_params: raise ValueError('GET/HEAD requests should not include body.') # generate the basic OAuth parameters request.oauth_params = self.get_oauth_params(request) # generate the signature request.oauth_params.append( ('oauth_signature', self.get_oauth_signature(request))) # render the signed request and return it uri, headers, body = self._render(request, formencode=True, realm=(realm or self.realm)) if self.decoding: log.debug('Encoding URI, headers and body to %s.', self.decoding) uri = uri.encode(self.decoding) body = body.encode(self.decoding) if body else body new_headers = {} for k, v in headers.items(): new_headers[k.encode(self.decoding)] = v.encode(self.decoding) headers = new_headers return uri, headers, body
[ "def", "sign", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "realm", "=", "None", ")", ":", "# normalize request data", "request", "=", "Request", "(", "uri", ",", "http_method", ...
Sign a request Signs an HTTP request with the specified parts. Returns a 3-tuple of the signed request's URI, headers, and body. Note that http_method is not returned as it is unaffected by the OAuth signing process. Also worth noting is that duplicate parameters will be included in the signature, regardless of where they are specified (query, body). The body argument may be a dict, a list of 2-tuples, or a formencoded string. The Content-Type header must be 'application/x-www-form-urlencoded' if it is present. If the body argument is not one of the above, it will be returned verbatim as it is unaffected by the OAuth signing process. Attempting to sign a request with non-formencoded data using the OAuth body signature type is invalid and will raise an exception. If the body does contain parameters, it will be returned as a properly- formatted formencoded string. Body may not be included if the http_method is either GET or HEAD as this changes the semantic meaning of the request. All string data MUST be unicode or be encoded with the same encoding scheme supplied to the Client constructor, default utf-8. This includes strings inside body dicts, for example.
[ "Sign", "a", "request" ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L225-L327
train
224,683
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/base.py
BaseEndpoint._raise_on_invalid_client
def _raise_on_invalid_client(self, request): """Raise on failed client authentication.""" if self.request_validator.client_authentication_required(request): if not self.request_validator.authenticate_client(request): log.debug('Client authentication failed, %r.', request) raise InvalidClientError(request=request) elif not self.request_validator.authenticate_client_id(request.client_id, request): log.debug('Client authentication failed, %r.', request) raise InvalidClientError(request=request)
python
def _raise_on_invalid_client(self, request): """Raise on failed client authentication.""" if self.request_validator.client_authentication_required(request): if not self.request_validator.authenticate_client(request): log.debug('Client authentication failed, %r.', request) raise InvalidClientError(request=request) elif not self.request_validator.authenticate_client_id(request.client_id, request): log.debug('Client authentication failed, %r.', request) raise InvalidClientError(request=request)
[ "def", "_raise_on_invalid_client", "(", "self", ",", "request", ")", ":", "if", "self", ".", "request_validator", ".", "client_authentication_required", "(", "request", ")", ":", "if", "not", "self", ".", "request_validator", ".", "authenticate_client", "(", "requ...
Raise on failed client authentication.
[ "Raise", "on", "failed", "client", "authentication", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/base.py#L48-L56
train
224,684
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/base.py
BaseEndpoint._raise_on_unsupported_token
def _raise_on_unsupported_token(self, request): """Raise on unsupported tokens.""" if (request.token_type_hint and request.token_type_hint in self.valid_token_types and request.token_type_hint not in self.supported_token_types): raise UnsupportedTokenTypeError(request=request)
python
def _raise_on_unsupported_token(self, request): """Raise on unsupported tokens.""" if (request.token_type_hint and request.token_type_hint in self.valid_token_types and request.token_type_hint not in self.supported_token_types): raise UnsupportedTokenTypeError(request=request)
[ "def", "_raise_on_unsupported_token", "(", "self", ",", "request", ")", ":", "if", "(", "request", ".", "token_type_hint", "and", "request", ".", "token_type_hint", "in", "self", ".", "valid_token_types", "and", "request", ".", "token_type_hint", "not", "in", "s...
Raise on unsupported tokens.
[ "Raise", "on", "unsupported", "tokens", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/base.py#L58-L63
train
224,685
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/endpoints/revocation.py
RevocationEndpoint.create_revocation_response
def create_revocation_response(self, uri, http_method='POST', body=None, headers=None): """Revoke supplied access or refresh token. The authorization server responds with HTTP status code 200 if the token has been revoked sucessfully or if the client submitted an invalid token. Note: invalid tokens do not cause an error response since the client cannot handle such an error in a reasonable way. Moreover, the purpose of the revocation request, invalidating the particular token, is already achieved. The content of the response body is ignored by the client as all necessary information is conveyed in the response code. An invalid token type hint value is ignored by the authorization server and does not influence the revocation response. """ resp_headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Pragma': 'no-cache', } request = Request( uri, http_method=http_method, body=body, headers=headers) try: self.validate_revocation_request(request) log.debug('Token revocation valid for %r.', request) except OAuth2Error as e: log.debug('Client error during validation of %r. %r.', request, e) response_body = e.json if self.enable_jsonp and request.callback: response_body = '%s(%s);' % (request.callback, response_body) resp_headers.update(e.headers) return resp_headers, response_body, e.status_code self.request_validator.revoke_token(request.token, request.token_type_hint, request) response_body = '' if self.enable_jsonp and request.callback: response_body = request.callback + '();' return {}, response_body, 200
python
def create_revocation_response(self, uri, http_method='POST', body=None, headers=None): """Revoke supplied access or refresh token. The authorization server responds with HTTP status code 200 if the token has been revoked sucessfully or if the client submitted an invalid token. Note: invalid tokens do not cause an error response since the client cannot handle such an error in a reasonable way. Moreover, the purpose of the revocation request, invalidating the particular token, is already achieved. The content of the response body is ignored by the client as all necessary information is conveyed in the response code. An invalid token type hint value is ignored by the authorization server and does not influence the revocation response. """ resp_headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Pragma': 'no-cache', } request = Request( uri, http_method=http_method, body=body, headers=headers) try: self.validate_revocation_request(request) log.debug('Token revocation valid for %r.', request) except OAuth2Error as e: log.debug('Client error during validation of %r. %r.', request, e) response_body = e.json if self.enable_jsonp and request.callback: response_body = '%s(%s);' % (request.callback, response_body) resp_headers.update(e.headers) return resp_headers, response_body, e.status_code self.request_validator.revoke_token(request.token, request.token_type_hint, request) response_body = '' if self.enable_jsonp and request.callback: response_body = request.callback + '();' return {}, response_body, 200
[ "def", "create_revocation_response", "(", "self", ",", "uri", ",", "http_method", "=", "'POST'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "resp_headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Cache-Control'", ":"...
Revoke supplied access or refresh token. The authorization server responds with HTTP status code 200 if the token has been revoked sucessfully or if the client submitted an invalid token. Note: invalid tokens do not cause an error response since the client cannot handle such an error in a reasonable way. Moreover, the purpose of the revocation request, invalidating the particular token, is already achieved. The content of the response body is ignored by the client as all necessary information is conveyed in the response code. An invalid token type hint value is ignored by the authorization server and does not influence the revocation response.
[ "Revoke", "supplied", "access", "or", "refresh", "token", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/revocation.py#L41-L85
train
224,686
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/base.py
GrantTypeBase.prepare_authorization_response
def prepare_authorization_response(self, request, token, headers, body, status): """Place token according to response mode. Base classes can define a default response mode for their authorization response by overriding the static `default_response_mode` member. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token: :param headers: :param body: :param status: """ request.response_mode = request.response_mode or self.default_response_mode if request.response_mode not in ('query', 'fragment'): log.debug('Overriding invalid response mode %s with %s', request.response_mode, self.default_response_mode) request.response_mode = self.default_response_mode token_items = token.items() if request.response_type == 'none': state = token.get('state', None) if state: token_items = [('state', state)] else: token_items = [] if request.response_mode == 'query': headers['Location'] = add_params_to_uri( request.redirect_uri, token_items, fragment=False) return headers, body, status if request.response_mode == 'fragment': headers['Location'] = add_params_to_uri( request.redirect_uri, token_items, fragment=True) return headers, body, status raise NotImplementedError( 'Subclasses must set a valid default_response_mode')
python
def prepare_authorization_response(self, request, token, headers, body, status): """Place token according to response mode. Base classes can define a default response mode for their authorization response by overriding the static `default_response_mode` member. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token: :param headers: :param body: :param status: """ request.response_mode = request.response_mode or self.default_response_mode if request.response_mode not in ('query', 'fragment'): log.debug('Overriding invalid response mode %s with %s', request.response_mode, self.default_response_mode) request.response_mode = self.default_response_mode token_items = token.items() if request.response_type == 'none': state = token.get('state', None) if state: token_items = [('state', state)] else: token_items = [] if request.response_mode == 'query': headers['Location'] = add_params_to_uri( request.redirect_uri, token_items, fragment=False) return headers, body, status if request.response_mode == 'fragment': headers['Location'] = add_params_to_uri( request.redirect_uri, token_items, fragment=True) return headers, body, status raise NotImplementedError( 'Subclasses must set a valid default_response_mode')
[ "def", "prepare_authorization_response", "(", "self", ",", "request", ",", "token", ",", "headers", ",", "body", ",", "status", ")", ":", "request", ".", "response_mode", "=", "request", ".", "response_mode", "or", "self", ".", "default_response_mode", "if", "...
Place token according to response mode. Base classes can define a default response mode for their authorization response by overriding the static `default_response_mode` member. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token: :param headers: :param body: :param status:
[ "Place", "token", "according", "to", "response", "mode", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/base.py#L180-L220
train
224,687
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/tokens.py
prepare_mac_header
def prepare_mac_header(token, uri, key, http_method, nonce=None, headers=None, body=None, ext='', hash_algorithm='hmac-sha-1', issue_time=None, draft=0): """Add an `MAC Access Authentication`_ signature to headers. Unlike OAuth 1, this HMAC signature does not require inclusion of the request payload/body, neither does it use a combination of client_secret and token_secret but rather a mac_key provided together with the access token. Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256", `extension algorithms`_ are not supported. Example MAC Authorization header, linebreaks added for clarity Authorization: MAC id="h480djs93hd8", nonce="1336363200:dj83hs9s", mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM=" .. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01 .. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1 :param token: :param uri: Request URI. :param key: MAC given provided by token endpoint. :param http_method: HTTP Request method. :param nonce: :param headers: Request headers as a dictionary. :param body: :param ext: :param hash_algorithm: HMAC algorithm provided by token endpoint. :param issue_time: Time when the MAC credentials were issued (datetime). :param draft: MAC authentication specification version. :return: headers dictionary with the authorization field added. """ http_method = http_method.upper() host, port = utils.host_from_uri(uri) if hash_algorithm.lower() == 'hmac-sha-1': h = hashlib.sha1 elif hash_algorithm.lower() == 'hmac-sha-256': h = hashlib.sha256 else: raise ValueError('unknown hash algorithm') if draft == 0: nonce = nonce or '{0}:{1}'.format(utils.generate_age(issue_time), common.generate_nonce()) else: ts = common.generate_timestamp() nonce = common.generate_nonce() sch, net, path, par, query, fra = urlparse(uri) if query: request_uri = path + '?' + query else: request_uri = path # Hash the body/payload if body is not None and draft == 0: body = body.encode('utf-8') bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8') else: bodyhash = '' # Create the normalized base string base = [] if draft == 0: base.append(nonce) else: base.append(ts) base.append(nonce) base.append(http_method.upper()) base.append(request_uri) base.append(host) base.append(port) if draft == 0: base.append(bodyhash) base.append(ext or '') base_string = '\n'.join(base) + '\n' # hmac struggles with unicode strings - http://bugs.python.org/issue5285 if isinstance(key, unicode_type): key = key.encode('utf-8') sign = hmac.new(key, base_string.encode('utf-8'), h) sign = b2a_base64(sign.digest())[:-1].decode('utf-8') header = [] header.append('MAC id="%s"' % token) if draft != 0: header.append('ts="%s"' % ts) header.append('nonce="%s"' % nonce) if bodyhash: header.append('bodyhash="%s"' % bodyhash) if ext: header.append('ext="%s"' % ext) header.append('mac="%s"' % sign) headers = headers or {} headers['Authorization'] = ', '.join(header) return headers
python
def prepare_mac_header(token, uri, key, http_method, nonce=None, headers=None, body=None, ext='', hash_algorithm='hmac-sha-1', issue_time=None, draft=0): """Add an `MAC Access Authentication`_ signature to headers. Unlike OAuth 1, this HMAC signature does not require inclusion of the request payload/body, neither does it use a combination of client_secret and token_secret but rather a mac_key provided together with the access token. Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256", `extension algorithms`_ are not supported. Example MAC Authorization header, linebreaks added for clarity Authorization: MAC id="h480djs93hd8", nonce="1336363200:dj83hs9s", mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM=" .. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01 .. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1 :param token: :param uri: Request URI. :param key: MAC given provided by token endpoint. :param http_method: HTTP Request method. :param nonce: :param headers: Request headers as a dictionary. :param body: :param ext: :param hash_algorithm: HMAC algorithm provided by token endpoint. :param issue_time: Time when the MAC credentials were issued (datetime). :param draft: MAC authentication specification version. :return: headers dictionary with the authorization field added. """ http_method = http_method.upper() host, port = utils.host_from_uri(uri) if hash_algorithm.lower() == 'hmac-sha-1': h = hashlib.sha1 elif hash_algorithm.lower() == 'hmac-sha-256': h = hashlib.sha256 else: raise ValueError('unknown hash algorithm') if draft == 0: nonce = nonce or '{0}:{1}'.format(utils.generate_age(issue_time), common.generate_nonce()) else: ts = common.generate_timestamp() nonce = common.generate_nonce() sch, net, path, par, query, fra = urlparse(uri) if query: request_uri = path + '?' + query else: request_uri = path # Hash the body/payload if body is not None and draft == 0: body = body.encode('utf-8') bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8') else: bodyhash = '' # Create the normalized base string base = [] if draft == 0: base.append(nonce) else: base.append(ts) base.append(nonce) base.append(http_method.upper()) base.append(request_uri) base.append(host) base.append(port) if draft == 0: base.append(bodyhash) base.append(ext or '') base_string = '\n'.join(base) + '\n' # hmac struggles with unicode strings - http://bugs.python.org/issue5285 if isinstance(key, unicode_type): key = key.encode('utf-8') sign = hmac.new(key, base_string.encode('utf-8'), h) sign = b2a_base64(sign.digest())[:-1].decode('utf-8') header = [] header.append('MAC id="%s"' % token) if draft != 0: header.append('ts="%s"' % ts) header.append('nonce="%s"' % nonce) if bodyhash: header.append('bodyhash="%s"' % bodyhash) if ext: header.append('ext="%s"' % ext) header.append('mac="%s"' % sign) headers = headers or {} headers['Authorization'] = ', '.join(header) return headers
[ "def", "prepare_mac_header", "(", "token", ",", "uri", ",", "key", ",", "http_method", ",", "nonce", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "None", ",", "ext", "=", "''", ",", "hash_algorithm", "=", "'hmac-sha-1'", ",", "issue_time",...
Add an `MAC Access Authentication`_ signature to headers. Unlike OAuth 1, this HMAC signature does not require inclusion of the request payload/body, neither does it use a combination of client_secret and token_secret but rather a mac_key provided together with the access token. Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256", `extension algorithms`_ are not supported. Example MAC Authorization header, linebreaks added for clarity Authorization: MAC id="h480djs93hd8", nonce="1336363200:dj83hs9s", mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM=" .. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01 .. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1 :param token: :param uri: Request URI. :param key: MAC given provided by token endpoint. :param http_method: HTTP Request method. :param nonce: :param headers: Request headers as a dictionary. :param body: :param ext: :param hash_algorithm: HMAC algorithm provided by token endpoint. :param issue_time: Time when the MAC credentials were issued (datetime). :param draft: MAC authentication specification version. :return: headers dictionary with the authorization field added.
[ "Add", "an", "MAC", "Access", "Authentication", "_", "signature", "to", "headers", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L73-L179
train
224,688
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/tokens.py
get_token_from_header
def get_token_from_header(request): """ Helper function to extract a token from the request header. :param request: OAuthlib request. :type request: oauthlib.common.Request :return: Return the token or None if the Authorization header is malformed. """ token = None if 'Authorization' in request.headers: split_header = request.headers.get('Authorization').split() if len(split_header) == 2 and split_header[0] == 'Bearer': token = split_header[1] else: token = request.access_token return token
python
def get_token_from_header(request): """ Helper function to extract a token from the request header. :param request: OAuthlib request. :type request: oauthlib.common.Request :return: Return the token or None if the Authorization header is malformed. """ token = None if 'Authorization' in request.headers: split_header = request.headers.get('Authorization').split() if len(split_header) == 2 and split_header[0] == 'Bearer': token = split_header[1] else: token = request.access_token return token
[ "def", "get_token_from_header", "(", "request", ")", ":", "token", "=", "None", "if", "'Authorization'", "in", "request", ".", "headers", ":", "split_header", "=", "request", ".", "headers", ".", "get", "(", "'Authorization'", ")", ".", "split", "(", ")", ...
Helper function to extract a token from the request header. :param request: OAuthlib request. :type request: oauthlib.common.Request :return: Return the token or None if the Authorization header is malformed.
[ "Helper", "function", "to", "extract", "a", "token", "from", "the", "request", "header", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L245-L262
train
224,689
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/tokens.py
BearerToken.create_token
def create_token(self, request, refresh_token=False, **kwargs): """ Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token: """ if "save_token" in kwargs: warnings.warn("`save_token` has been deprecated, it was not called internally." "If you do, call `request_validator.save_token()` instead.", DeprecationWarning) if callable(self.expires_in): expires_in = self.expires_in(request) else: expires_in = self.expires_in request.expires_in = expires_in token = { 'access_token': self.token_generator(request), 'expires_in': expires_in, 'token_type': 'Bearer', } # If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but # there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so # all tokens issued are for the entire set of requested scopes. if request.scopes is not None: token['scope'] = ' '.join(request.scopes) if refresh_token: if (request.refresh_token and not self.request_validator.rotate_refresh_token(request)): token['refresh_token'] = request.refresh_token else: token['refresh_token'] = self.refresh_token_generator(request) token.update(request.extra_credentials or {}) return OAuth2Token(token)
python
def create_token(self, request, refresh_token=False, **kwargs): """ Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token: """ if "save_token" in kwargs: warnings.warn("`save_token` has been deprecated, it was not called internally." "If you do, call `request_validator.save_token()` instead.", DeprecationWarning) if callable(self.expires_in): expires_in = self.expires_in(request) else: expires_in = self.expires_in request.expires_in = expires_in token = { 'access_token': self.token_generator(request), 'expires_in': expires_in, 'token_type': 'Bearer', } # If provided, include - this is optional in some cases https://tools.ietf.org/html/rfc6749#section-3.3 but # there is currently no mechanism to coordinate issuing a token for only a subset of the requested scopes so # all tokens issued are for the entire set of requested scopes. if request.scopes is not None: token['scope'] = ' '.join(request.scopes) if refresh_token: if (request.refresh_token and not self.request_validator.rotate_refresh_token(request)): token['refresh_token'] = request.refresh_token else: token['refresh_token'] = self.refresh_token_generator(request) token.update(request.extra_credentials or {}) return OAuth2Token(token)
[ "def", "create_token", "(", "self", ",", "request", ",", "refresh_token", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "\"save_token\"", "in", "kwargs", ":", "warnings", ".", "warn", "(", "\"`save_token` has been deprecated, it was not called internally.\"...
Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token:
[ "Create", "a", "BearerToken", "by", "default", "without", "refresh", "token", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/tokens.py#L300-L340
train
224,690
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
list_to_scope
def list_to_scope(scope): """Convert a list of scopes to a space separated string.""" if isinstance(scope, unicode_type) or scope is None: return scope elif isinstance(scope, (set, tuple, list)): return " ".join([unicode_type(s) for s in scope]) else: raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope)
python
def list_to_scope(scope): """Convert a list of scopes to a space separated string.""" if isinstance(scope, unicode_type) or scope is None: return scope elif isinstance(scope, (set, tuple, list)): return " ".join([unicode_type(s) for s in scope]) else: raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope)
[ "def", "list_to_scope", "(", "scope", ")", ":", "if", "isinstance", "(", "scope", ",", "unicode_type", ")", "or", "scope", "is", "None", ":", "return", "scope", "elif", "isinstance", "(", "scope", ",", "(", "set", ",", "tuple", ",", "list", ")", ")", ...
Convert a list of scopes to a space separated string.
[ "Convert", "a", "list", "of", "scopes", "to", "a", "space", "separated", "string", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L25-L32
train
224,691
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
scope_to_list
def scope_to_list(scope): """Convert a space separated string to a list of scopes.""" if isinstance(scope, (tuple, list, set)): return [unicode_type(s) for s in scope] elif scope is None: return None else: return scope.strip().split(" ")
python
def scope_to_list(scope): """Convert a space separated string to a list of scopes.""" if isinstance(scope, (tuple, list, set)): return [unicode_type(s) for s in scope] elif scope is None: return None else: return scope.strip().split(" ")
[ "def", "scope_to_list", "(", "scope", ")", ":", "if", "isinstance", "(", "scope", ",", "(", "tuple", ",", "list", ",", "set", ")", ")", ":", "return", "[", "unicode_type", "(", "s", ")", "for", "s", "in", "scope", "]", "elif", "scope", "is", "None"...
Convert a space separated string to a list of scopes.
[ "Convert", "a", "space", "separated", "string", "to", "a", "list", "of", "scopes", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L35-L42
train
224,692
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
host_from_uri
def host_from_uri(uri): """Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI. """ default_ports = { 'HTTP': '80', 'HTTPS': '443', } sch, netloc, path, par, query, fra = urlparse(uri) if ':' in netloc: netloc, port = netloc.split(':', 1) else: port = default_ports.get(sch.upper()) return netloc, port
python
def host_from_uri(uri): """Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI. """ default_ports = { 'HTTP': '80', 'HTTPS': '443', } sch, netloc, path, par, query, fra = urlparse(uri) if ':' in netloc: netloc, port = netloc.split(':', 1) else: port = default_ports.get(sch.upper()) return netloc, port
[ "def", "host_from_uri", "(", "uri", ")", ":", "default_ports", "=", "{", "'HTTP'", ":", "'80'", ",", "'HTTPS'", ":", "'443'", ",", "}", "sch", ",", "netloc", ",", "path", ",", "par", ",", "query", ",", "fra", "=", "urlparse", "(", "uri", ")", "if",...
Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI.
[ "Extract", "hostname", "and", "port", "from", "URI", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L52-L68
train
224,693
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
escape
def escape(u): """Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2 """ if not isinstance(u, unicode_type): raise ValueError('Only unicode objects are escapable.') return quote(u.encode('utf-8'), safe=b'~')
python
def escape(u): """Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2 """ if not isinstance(u, unicode_type): raise ValueError('Only unicode objects are escapable.') return quote(u.encode('utf-8'), safe=b'~')
[ "def", "escape", "(", "u", ")", ":", "if", "not", "isinstance", "(", "u", ",", "unicode_type", ")", ":", "raise", "ValueError", "(", "'Only unicode objects are escapable.'", ")", "return", "quote", "(", "u", ".", "encode", "(", "'utf-8'", ")", ",", "safe",...
Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2
[ "Escape", "a", "string", "in", "an", "OAuth", "-", "compatible", "fashion", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L71-L79
train
224,694
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/utils.py
generate_age
def generate_age(issue_time): """Generate a age parameter for MAC authentication draft 00.""" td = datetime.datetime.now() - issue_time age = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6 return unicode_type(age)
python
def generate_age(issue_time): """Generate a age parameter for MAC authentication draft 00.""" td = datetime.datetime.now() - issue_time age = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6 return unicode_type(age)
[ "def", "generate_age", "(", "issue_time", ")", ":", "td", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "issue_time", "age", "=", "(", "td", ".", "microseconds", "+", "(", "td", ".", "seconds", "+", "td", ".", "days", "*", "24", "*",...
Generate a age parameter for MAC authentication draft 00.
[ "Generate", "a", "age", "parameter", "for", "MAC", "authentication", "draft", "00", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/utils.py#L82-L87
train
224,695
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/implicit.py
ImplicitGrant.create_token_response
def create_token_response(self, request, token_handler): """Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the "application/x-www-form-urlencoded" format, per `Appendix B`_: access_token REQUIRED. The access token issued by the authorization server. token_type REQUIRED. The type of the token issued as described in `Section 7.1`_. Value is case insensitive. expires_in RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. scope OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The scope of the access token as described by `Section 3.3`_. state REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. The authorization server MUST NOT issue a refresh token. .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 """ try: self.validate_token_request(request) # If the request fails due to a missing, invalid, or mismatching # redirection URI, or if the client identifier is missing or invalid, # the authorization server SHOULD inform the resource owner of the # error and MUST NOT automatically redirect the user-agent to the # invalid redirection URI. except errors.FatalClientError as e: log.debug('Fatal client error during validation of %r. %r.', request, e) raise # If the resource owner denies the access request or if the request # fails for reasons other than a missing or invalid redirection URI, # the authorization server informs the client by adding the following # parameters to the fragment component of the redirection URI using the # "application/x-www-form-urlencoded" format, per Appendix B: # https://tools.ietf.org/html/rfc6749#appendix-B except errors.OAuth2Error as e: log.debug('Client error during validation of %r. %r.', request, e) return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples, fragment=True)}, None, 302 # In OIDC implicit flow it is possible to have a request_type that does not include the access_token! # "id_token token" - return the access token and the id token # "id_token" - don't return the access token if "token" in request.response_type.split(): token = token_handler.create_token(request, refresh_token=False) else: token = {} if request.state is not None: token['state'] = request.state for modifier in self._token_modifiers: token = modifier(token, token_handler, request) # In OIDC implicit flow it is possible to have a request_type that does # not include the access_token! In this case there is no need to save a token. if "token" in request.response_type.split(): self.request_validator.save_token(token, request) return self.prepare_authorization_response( request, token, {}, None, 302)
python
def create_token_response(self, request, token_handler): """Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the "application/x-www-form-urlencoded" format, per `Appendix B`_: access_token REQUIRED. The access token issued by the authorization server. token_type REQUIRED. The type of the token issued as described in `Section 7.1`_. Value is case insensitive. expires_in RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. scope OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The scope of the access token as described by `Section 3.3`_. state REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. The authorization server MUST NOT issue a refresh token. .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 """ try: self.validate_token_request(request) # If the request fails due to a missing, invalid, or mismatching # redirection URI, or if the client identifier is missing or invalid, # the authorization server SHOULD inform the resource owner of the # error and MUST NOT automatically redirect the user-agent to the # invalid redirection URI. except errors.FatalClientError as e: log.debug('Fatal client error during validation of %r. %r.', request, e) raise # If the resource owner denies the access request or if the request # fails for reasons other than a missing or invalid redirection URI, # the authorization server informs the client by adding the following # parameters to the fragment component of the redirection URI using the # "application/x-www-form-urlencoded" format, per Appendix B: # https://tools.ietf.org/html/rfc6749#appendix-B except errors.OAuth2Error as e: log.debug('Client error during validation of %r. %r.', request, e) return {'Location': common.add_params_to_uri(request.redirect_uri, e.twotuples, fragment=True)}, None, 302 # In OIDC implicit flow it is possible to have a request_type that does not include the access_token! # "id_token token" - return the access token and the id token # "id_token" - don't return the access token if "token" in request.response_type.split(): token = token_handler.create_token(request, refresh_token=False) else: token = {} if request.state is not None: token['state'] = request.state for modifier in self._token_modifiers: token = modifier(token, token_handler, request) # In OIDC implicit flow it is possible to have a request_type that does # not include the access_token! In this case there is no need to save a token. if "token" in request.response_type.split(): self.request_validator.save_token(token, request) return self.prepare_authorization_response( request, token, {}, None, 302)
[ "def", "create_token_response", "(", "self", ",", "request", ",", "token_handler", ")", ":", "try", ":", "self", ".", "validate_token_request", "(", "request", ")", "# If the request fails due to a missing, invalid, or mismatching", "# redirection URI, or if the client identifi...
Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. If the resource owner grants the access request, the authorization server issues an access token and delivers it to the client by adding the following parameters to the fragment component of the redirection URI using the "application/x-www-form-urlencoded" format, per `Appendix B`_: access_token REQUIRED. The access token issued by the authorization server. token_type REQUIRED. The type of the token issued as described in `Section 7.1`_. Value is case insensitive. expires_in RECOMMENDED. The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. scope OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The scope of the access token as described by `Section 3.3`_. state REQUIRED if the "state" parameter was present in the client authorization request. The exact value received from the client. The authorization server MUST NOT issue a refresh token. .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1
[ "Return", "token", "or", "error", "embedded", "in", "the", "URI", "fragment", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/implicit.py#L168-L256
train
224,696
oauthlib/oauthlib
oauthlib/oauth2/rfc6749/grant_types/implicit.py
ImplicitGrant.validate_token_request
def validate_token_request(self, request): """Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in a few subtle areas. A normal error could be a missing response_type parameter or the client attempting to access scope it is not allowed to ask authorization for. Normal errors can safely be included in the redirection URI and sent back to the client. Fatal errors occur when the client_id or redirect_uri is invalid or missing. These must be caught by the provider and handled, how this is done is outside of the scope of OAuthLib but showing an error page describing the issue is a good idea. """ # First check for fatal errors # If the request fails due to a missing, invalid, or mismatching # redirection URI, or if the client identifier is missing or invalid, # the authorization server SHOULD inform the resource owner of the # error and MUST NOT automatically redirect the user-agent to the # invalid redirection URI. # First check duplicate parameters for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'): try: duplicate_params = request.duplicate_params except ValueError: raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request) if param in duplicate_params: raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request) # REQUIRED. The client identifier as described in Section 2.2. # https://tools.ietf.org/html/rfc6749#section-2.2 if not request.client_id: raise errors.MissingClientIdError(request=request) if not self.request_validator.validate_client_id(request.client_id, request): raise errors.InvalidClientIdError(request=request) # OPTIONAL. As described in Section 3.1.2. # https://tools.ietf.org/html/rfc6749#section-3.1.2 self._handle_redirects(request) # Then check for normal errors. request_info = self._run_custom_validators(request, self.custom_validators.all_pre) # If the resource owner denies the access request or if the request # fails for reasons other than a missing or invalid redirection URI, # the authorization server informs the client by adding the following # parameters to the fragment component of the redirection URI using the # "application/x-www-form-urlencoded" format, per Appendix B. # https://tools.ietf.org/html/rfc6749#appendix-B # Note that the correct parameters to be added are automatically # populated through the use of specific exceptions # REQUIRED. if request.response_type is None: raise errors.MissingResponseTypeError(request=request) # Value MUST be one of our registered types: "token" by default or if using OIDC "id_token" or "id_token token" elif not set(request.response_type.split()).issubset(self.response_types): raise errors.UnsupportedResponseTypeError(request=request) log.debug('Validating use of response_type token for client %r (%r).', request.client_id, request.client) if not self.request_validator.validate_response_type(request.client_id, request.response_type, request.client, request): log.debug('Client %s is not authorized to use response_type %s.', request.client_id, request.response_type) raise errors.UnauthorizedClientError(request=request) # OPTIONAL. The scope of the access request as described by Section 3.3 # https://tools.ietf.org/html/rfc6749#section-3.3 self.validate_scopes(request) request_info.update({ 'client_id': request.client_id, 'redirect_uri': request.redirect_uri, 'response_type': request.response_type, 'state': request.state, 'request': request, }) request_info = self._run_custom_validators( request, self.custom_validators.all_post, request_info ) return request.scopes, request_info
python
def validate_token_request(self, request): """Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in a few subtle areas. A normal error could be a missing response_type parameter or the client attempting to access scope it is not allowed to ask authorization for. Normal errors can safely be included in the redirection URI and sent back to the client. Fatal errors occur when the client_id or redirect_uri is invalid or missing. These must be caught by the provider and handled, how this is done is outside of the scope of OAuthLib but showing an error page describing the issue is a good idea. """ # First check for fatal errors # If the request fails due to a missing, invalid, or mismatching # redirection URI, or if the client identifier is missing or invalid, # the authorization server SHOULD inform the resource owner of the # error and MUST NOT automatically redirect the user-agent to the # invalid redirection URI. # First check duplicate parameters for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'): try: duplicate_params = request.duplicate_params except ValueError: raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request) if param in duplicate_params: raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request) # REQUIRED. The client identifier as described in Section 2.2. # https://tools.ietf.org/html/rfc6749#section-2.2 if not request.client_id: raise errors.MissingClientIdError(request=request) if not self.request_validator.validate_client_id(request.client_id, request): raise errors.InvalidClientIdError(request=request) # OPTIONAL. As described in Section 3.1.2. # https://tools.ietf.org/html/rfc6749#section-3.1.2 self._handle_redirects(request) # Then check for normal errors. request_info = self._run_custom_validators(request, self.custom_validators.all_pre) # If the resource owner denies the access request or if the request # fails for reasons other than a missing or invalid redirection URI, # the authorization server informs the client by adding the following # parameters to the fragment component of the redirection URI using the # "application/x-www-form-urlencoded" format, per Appendix B. # https://tools.ietf.org/html/rfc6749#appendix-B # Note that the correct parameters to be added are automatically # populated through the use of specific exceptions # REQUIRED. if request.response_type is None: raise errors.MissingResponseTypeError(request=request) # Value MUST be one of our registered types: "token" by default or if using OIDC "id_token" or "id_token token" elif not set(request.response_type.split()).issubset(self.response_types): raise errors.UnsupportedResponseTypeError(request=request) log.debug('Validating use of response_type token for client %r (%r).', request.client_id, request.client) if not self.request_validator.validate_response_type(request.client_id, request.response_type, request.client, request): log.debug('Client %s is not authorized to use response_type %s.', request.client_id, request.response_type) raise errors.UnauthorizedClientError(request=request) # OPTIONAL. The scope of the access request as described by Section 3.3 # https://tools.ietf.org/html/rfc6749#section-3.3 self.validate_scopes(request) request_info.update({ 'client_id': request.client_id, 'redirect_uri': request.redirect_uri, 'response_type': request.response_type, 'state': request.state, 'request': request, }) request_info = self._run_custom_validators( request, self.custom_validators.all_post, request_info ) return request.scopes, request_info
[ "def", "validate_token_request", "(", "self", ",", "request", ")", ":", "# First check for fatal errors", "# If the request fails due to a missing, invalid, or mismatching", "# redirection URI, or if the client identifier is missing or invalid,", "# the authorization server SHOULD inform the r...
Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in a few subtle areas. A normal error could be a missing response_type parameter or the client attempting to access scope it is not allowed to ask authorization for. Normal errors can safely be included in the redirection URI and sent back to the client. Fatal errors occur when the client_id or redirect_uri is invalid or missing. These must be caught by the provider and handled, how this is done is outside of the scope of OAuthLib but showing an error page describing the issue is a good idea.
[ "Check", "the", "token", "request", "for", "normal", "and", "fatal", "errors", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/implicit.py#L265-L364
train
224,697
oauthlib/oauthlib
oauthlib/openid/connect/core/grant_types/base.py
GrantTypeBase.validate_authorization_request
def validate_authorization_request(self, request): """Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info) """ # If request.prompt is 'none' then no login/authorization form should # be presented to the user. Instead, a silent login/authorization # should be performed. if request.prompt == 'none': raise OIDCNoPrompt() else: return self.proxy_target.validate_authorization_request(request)
python
def validate_authorization_request(self, request): """Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info) """ # If request.prompt is 'none' then no login/authorization form should # be presented to the user. Instead, a silent login/authorization # should be performed. if request.prompt == 'none': raise OIDCNoPrompt() else: return self.proxy_target.validate_authorization_request(request)
[ "def", "validate_authorization_request", "(", "self", ",", "request", ")", ":", "# If request.prompt is 'none' then no login/authorization form should", "# be presented to the user. Instead, a silent login/authorization", "# should be performed.", "if", "request", ".", "prompt", "==", ...
Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info)
[ "Validates", "the", "OpenID", "Connect", "authorization", "request", "parameters", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/base.py#L27-L38
train
224,698
oauthlib/oauthlib
oauthlib/openid/connect/core/grant_types/base.py
GrantTypeBase.openid_authorization_validator
def openid_authorization_validator(self, request): """Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. Sufficient entropy MUST be present in the nonce values used to prevent attackers from guessing values display OPTIONAL. ASCII string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page - The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup - The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch - The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap - The Authorization Server SHOULD display the authentication and consent UI consistent with a "feature phone" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. prompt OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none - The Authorization Server MUST NOT display any authentication or consent user interface pages. An error is returned if an End-User is not already authenticated or the Client does not have pre-configured consent for the requested Claims or does not fulfill other conditions for processing the request. The error code will typically be login_required, interaction_required, or another code defined in Section 3.1.2.6. This can be used as a method to check for existing authentication and/or consent. login - The Authorization Server SHOULD prompt the End-User for reauthentication. If it cannot reauthenticate the End-User, it MUST return an error, typically login_required. consent - The Authorization Server SHOULD prompt the End-User for consent before returning information to the Client. If it cannot obtain consent, it MUST return an error, typically consent_required. select_account - The Authorization Server SHOULD prompt the End-User to select a user account. This enables an End-User who has multiple accounts at the Authorization Server to select amongst the multiple accounts that they might have current sessions for. If it cannot obtain an account selection choice made by the End-User, it MUST return an error, typically account_selection_required. The prompt parameter can be used by the Client to make sure that the End-User is still present for the current session or to bring attention to the request. If this parameter contains none with any other value, an error is returned. max_age OPTIONAL. Maximum Authentication Age. Specifies the allowable elapsed time in seconds since the last time the End-User was actively authenticated by the OP. If the elapsed time is greater than this value, the OP MUST attempt to actively re-authenticate the End-User. (The max_age request parameter corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age request parameter.) When max_age is used, the ID Token returned MUST include an auth_time Claim Value. ui_locales OPTIONAL. End-User's preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value "fr-CA fr en" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. id_token_hint OPTIONAL. ID Token previously issued by the Authorization Server being passed as a hint about the End-User's current or past authenticated session with the Client. If the End-User identified by the ID Token is logged in or is logged in by the request, then the Authorization Server returns a positive response; otherwise, it SHOULD return an error, such as login_required. When possible, an id_token_hint SHOULD be present when prompt=none is used and an invalid_request error MAY be returned if it is not; however, the server SHOULD respond successfully when possible, even if it is not present. The Authorization Server need not be listed as an audience of the ID Token when it is used as an id_token_hint value. If the ID Token received by the RP from the OP is encrypted, to use it as an id_token_hint, the Client MUST decrypt the signed ID Token contained within the encrypted ID Token. The Client MAY re-encrypt the signed ID token to the Authentication Server using a key that enables the server to decrypt the ID Token, and use the re-encrypted ID token as the id_token_hint value. login_hint OPTIONAL. Hint to the Authorization Server about the login identifier the End-User might use to log in (if necessary). This hint can be used by an RP if it first asks the End-User for their e-mail address (or other identifier) and then wants to pass that value as a hint to the discovered authorization service. It is RECOMMENDED that the hint value match the value used for discovery. This value MAY also be a phone number in the format specified for the phone_number Claim. The use of this parameter is left to the OP's discretion. acr_values OPTIONAL. Requested Authentication Context Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication Context Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. """ # Treat it as normal OAuth 2 auth code request if openid is not present if not request.scopes or 'openid' not in request.scopes: return {} prompt = request.prompt if request.prompt else [] if hasattr(prompt, 'split'): prompt = prompt.strip().split() prompt = set(prompt) if 'none' in prompt: if len(prompt) > 1: msg = "Prompt none is mutually exclusive with other values." raise InvalidRequestError(request=request, description=msg) if not self.request_validator.validate_silent_login(request): raise LoginRequired(request=request) if not self.request_validator.validate_silent_authorization(request): raise ConsentRequired(request=request) self._inflate_claims(request) if not self.request_validator.validate_user_match( request.id_token_hint, request.scopes, request.claims, request): msg = "Session user does not match client supplied user." raise LoginRequired(request=request, description=msg) request_info = { 'display': request.display, 'nonce': request.nonce, 'prompt': prompt, 'ui_locales': request.ui_locales.split() if request.ui_locales else [], 'id_token_hint': request.id_token_hint, 'login_hint': request.login_hint, 'claims': request.claims } return request_info
python
def openid_authorization_validator(self, request): """Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. Sufficient entropy MUST be present in the nonce values used to prevent attackers from guessing values display OPTIONAL. ASCII string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page - The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup - The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch - The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap - The Authorization Server SHOULD display the authentication and consent UI consistent with a "feature phone" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. prompt OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none - The Authorization Server MUST NOT display any authentication or consent user interface pages. An error is returned if an End-User is not already authenticated or the Client does not have pre-configured consent for the requested Claims or does not fulfill other conditions for processing the request. The error code will typically be login_required, interaction_required, or another code defined in Section 3.1.2.6. This can be used as a method to check for existing authentication and/or consent. login - The Authorization Server SHOULD prompt the End-User for reauthentication. If it cannot reauthenticate the End-User, it MUST return an error, typically login_required. consent - The Authorization Server SHOULD prompt the End-User for consent before returning information to the Client. If it cannot obtain consent, it MUST return an error, typically consent_required. select_account - The Authorization Server SHOULD prompt the End-User to select a user account. This enables an End-User who has multiple accounts at the Authorization Server to select amongst the multiple accounts that they might have current sessions for. If it cannot obtain an account selection choice made by the End-User, it MUST return an error, typically account_selection_required. The prompt parameter can be used by the Client to make sure that the End-User is still present for the current session or to bring attention to the request. If this parameter contains none with any other value, an error is returned. max_age OPTIONAL. Maximum Authentication Age. Specifies the allowable elapsed time in seconds since the last time the End-User was actively authenticated by the OP. If the elapsed time is greater than this value, the OP MUST attempt to actively re-authenticate the End-User. (The max_age request parameter corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age request parameter.) When max_age is used, the ID Token returned MUST include an auth_time Claim Value. ui_locales OPTIONAL. End-User's preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value "fr-CA fr en" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. id_token_hint OPTIONAL. ID Token previously issued by the Authorization Server being passed as a hint about the End-User's current or past authenticated session with the Client. If the End-User identified by the ID Token is logged in or is logged in by the request, then the Authorization Server returns a positive response; otherwise, it SHOULD return an error, such as login_required. When possible, an id_token_hint SHOULD be present when prompt=none is used and an invalid_request error MAY be returned if it is not; however, the server SHOULD respond successfully when possible, even if it is not present. The Authorization Server need not be listed as an audience of the ID Token when it is used as an id_token_hint value. If the ID Token received by the RP from the OP is encrypted, to use it as an id_token_hint, the Client MUST decrypt the signed ID Token contained within the encrypted ID Token. The Client MAY re-encrypt the signed ID token to the Authentication Server using a key that enables the server to decrypt the ID Token, and use the re-encrypted ID token as the id_token_hint value. login_hint OPTIONAL. Hint to the Authorization Server about the login identifier the End-User might use to log in (if necessary). This hint can be used by an RP if it first asks the End-User for their e-mail address (or other identifier) and then wants to pass that value as a hint to the discovered authorization service. It is RECOMMENDED that the hint value match the value used for discovery. This value MAY also be a phone number in the format specified for the phone_number Claim. The use of this parameter is left to the OP's discretion. acr_values OPTIONAL. Requested Authentication Context Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication Context Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. """ # Treat it as normal OAuth 2 auth code request if openid is not present if not request.scopes or 'openid' not in request.scopes: return {} prompt = request.prompt if request.prompt else [] if hasattr(prompt, 'split'): prompt = prompt.strip().split() prompt = set(prompt) if 'none' in prompt: if len(prompt) > 1: msg = "Prompt none is mutually exclusive with other values." raise InvalidRequestError(request=request, description=msg) if not self.request_validator.validate_silent_login(request): raise LoginRequired(request=request) if not self.request_validator.validate_silent_authorization(request): raise ConsentRequired(request=request) self._inflate_claims(request) if not self.request_validator.validate_user_match( request.id_token_hint, request.scopes, request.claims, request): msg = "Session user does not match client supplied user." raise LoginRequired(request=request, description=msg) request_info = { 'display': request.display, 'nonce': request.nonce, 'prompt': prompt, 'ui_locales': request.ui_locales.split() if request.ui_locales else [], 'id_token_hint': request.id_token_hint, 'login_hint': request.login_hint, 'claims': request.claims } return request_info
[ "def", "openid_authorization_validator", "(", "self", ",", "request", ")", ":", "# Treat it as normal OAuth 2 auth code request if openid is not present", "if", "not", "request", ".", "scopes", "or", "'openid'", "not", "in", "request", ".", "scopes", ":", "return", "{",...
Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. Sufficient entropy MUST be present in the nonce values used to prevent attackers from guessing values display OPTIONAL. ASCII string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page - The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup - The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch - The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap - The Authorization Server SHOULD display the authentication and consent UI consistent with a "feature phone" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. prompt OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none - The Authorization Server MUST NOT display any authentication or consent user interface pages. An error is returned if an End-User is not already authenticated or the Client does not have pre-configured consent for the requested Claims or does not fulfill other conditions for processing the request. The error code will typically be login_required, interaction_required, or another code defined in Section 3.1.2.6. This can be used as a method to check for existing authentication and/or consent. login - The Authorization Server SHOULD prompt the End-User for reauthentication. If it cannot reauthenticate the End-User, it MUST return an error, typically login_required. consent - The Authorization Server SHOULD prompt the End-User for consent before returning information to the Client. If it cannot obtain consent, it MUST return an error, typically consent_required. select_account - The Authorization Server SHOULD prompt the End-User to select a user account. This enables an End-User who has multiple accounts at the Authorization Server to select amongst the multiple accounts that they might have current sessions for. If it cannot obtain an account selection choice made by the End-User, it MUST return an error, typically account_selection_required. The prompt parameter can be used by the Client to make sure that the End-User is still present for the current session or to bring attention to the request. If this parameter contains none with any other value, an error is returned. max_age OPTIONAL. Maximum Authentication Age. Specifies the allowable elapsed time in seconds since the last time the End-User was actively authenticated by the OP. If the elapsed time is greater than this value, the OP MUST attempt to actively re-authenticate the End-User. (The max_age request parameter corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age request parameter.) When max_age is used, the ID Token returned MUST include an auth_time Claim Value. ui_locales OPTIONAL. End-User's preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value "fr-CA fr en" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. id_token_hint OPTIONAL. ID Token previously issued by the Authorization Server being passed as a hint about the End-User's current or past authenticated session with the Client. If the End-User identified by the ID Token is logged in or is logged in by the request, then the Authorization Server returns a positive response; otherwise, it SHOULD return an error, such as login_required. When possible, an id_token_hint SHOULD be present when prompt=none is used and an invalid_request error MAY be returned if it is not; however, the server SHOULD respond successfully when possible, even if it is not present. The Authorization Server need not be listed as an audience of the ID Token when it is used as an id_token_hint value. If the ID Token received by the RP from the OP is encrypted, to use it as an id_token_hint, the Client MUST decrypt the signed ID Token contained within the encrypted ID Token. The Client MAY re-encrypt the signed ID token to the Authentication Server using a key that enables the server to decrypt the ID Token, and use the re-encrypted ID token as the id_token_hint value. login_hint OPTIONAL. Hint to the Authorization Server about the login identifier the End-User might use to log in (if necessary). This hint can be used by an RP if it first asks the End-User for their e-mail address (or other identifier) and then wants to pass that value as a hint to the discovered authorization service. It is RECOMMENDED that the hint value match the value used for discovery. This value MAY also be a phone number in the format specified for the phone_number Claim. The use of this parameter is left to the OP's discretion. acr_values OPTIONAL. Requested Authentication Context Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication Context Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter.
[ "Perform", "OpenID", "Connect", "specific", "authorization", "request", "validation", "." ]
30321dd3c0ca784d3508a1970cf90d9f76835c79
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/openid/connect/core/grant_types/base.py#L71-L248
train
224,699