id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,500
|
janpipek/physt
|
physt/special.py
|
_prepare_data
|
def _prepare_data(data, transformed, klass, *args, **kwargs):
"""Transform data for binning.
Returns
-------
np.ndarray
"""
# TODO: Maybe include in the class itself?
data = np.asarray(data)
if not transformed:
data = klass.transform(data)
dropna = kwargs.get("dropna", False)
if dropna:
data = data[~np.isnan(data).any(axis=1)]
return data
|
python
|
def _prepare_data(data, transformed, klass, *args, **kwargs):
"""Transform data for binning.
Returns
-------
np.ndarray
"""
# TODO: Maybe include in the class itself?
data = np.asarray(data)
if not transformed:
data = klass.transform(data)
dropna = kwargs.get("dropna", False)
if dropna:
data = data[~np.isnan(data).any(axis=1)]
return data
|
[
"def",
"_prepare_data",
"(",
"data",
",",
"transformed",
",",
"klass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Maybe include in the class itself?",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"if",
"not",
"transformed",
":",
"data",
"=",
"klass",
".",
"transform",
"(",
"data",
")",
"dropna",
"=",
"kwargs",
".",
"get",
"(",
"\"dropna\"",
",",
"False",
")",
"if",
"dropna",
":",
"data",
"=",
"data",
"[",
"~",
"np",
".",
"isnan",
"(",
"data",
")",
".",
"any",
"(",
"axis",
"=",
"1",
")",
"]",
"return",
"data"
] |
Transform data for binning.
Returns
-------
np.ndarray
|
[
"Transform",
"data",
"for",
"binning",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/special.py#L331-L345
|
16,501
|
janpipek/physt
|
physt/special.py
|
polar_histogram
|
def polar_histogram(xdata, ydata, radial_bins="numpy", phi_bins=16,
transformed=False, *args, **kwargs):
"""Facade construction function for the PolarHistogram.
Parameters
----------
transformed : bool
phi_range : Optional[tuple]
range
"""
dropna = kwargs.pop("dropna", True)
data = np.concatenate([xdata[:, np.newaxis], ydata[:, np.newaxis]], axis=1)
data = _prepare_data(data, transformed=transformed, klass=PolarHistogram, dropna=dropna)
if isinstance(phi_bins, int):
phi_range = (0, 2 * np.pi)
if "phi_range" in "kwargs":
phi_range = kwargs["phi_range"]
elif "range" in "kwargs":
phi_range = kwargs["range"][1]
phi_range = list(phi_range) + [phi_bins + 1]
phi_bins = np.linspace(*phi_range)
bin_schemas = binnings.calculate_bins_nd(data, [radial_bins, phi_bins], *args,
check_nan=not dropna, **kwargs)
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=2,
binnings=bin_schemas,
weights=weights)
return PolarHistogram(binnings=bin_schemas, frequencies=frequencies, errors2=errors2, missed=missed)
|
python
|
def polar_histogram(xdata, ydata, radial_bins="numpy", phi_bins=16,
transformed=False, *args, **kwargs):
"""Facade construction function for the PolarHistogram.
Parameters
----------
transformed : bool
phi_range : Optional[tuple]
range
"""
dropna = kwargs.pop("dropna", True)
data = np.concatenate([xdata[:, np.newaxis], ydata[:, np.newaxis]], axis=1)
data = _prepare_data(data, transformed=transformed, klass=PolarHistogram, dropna=dropna)
if isinstance(phi_bins, int):
phi_range = (0, 2 * np.pi)
if "phi_range" in "kwargs":
phi_range = kwargs["phi_range"]
elif "range" in "kwargs":
phi_range = kwargs["range"][1]
phi_range = list(phi_range) + [phi_bins + 1]
phi_bins = np.linspace(*phi_range)
bin_schemas = binnings.calculate_bins_nd(data, [radial_bins, phi_bins], *args,
check_nan=not dropna, **kwargs)
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=2,
binnings=bin_schemas,
weights=weights)
return PolarHistogram(binnings=bin_schemas, frequencies=frequencies, errors2=errors2, missed=missed)
|
[
"def",
"polar_histogram",
"(",
"xdata",
",",
"ydata",
",",
"radial_bins",
"=",
"\"numpy\"",
",",
"phi_bins",
"=",
"16",
",",
"transformed",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dropna",
"=",
"kwargs",
".",
"pop",
"(",
"\"dropna\"",
",",
"True",
")",
"data",
"=",
"np",
".",
"concatenate",
"(",
"[",
"xdata",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"ydata",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"]",
",",
"axis",
"=",
"1",
")",
"data",
"=",
"_prepare_data",
"(",
"data",
",",
"transformed",
"=",
"transformed",
",",
"klass",
"=",
"PolarHistogram",
",",
"dropna",
"=",
"dropna",
")",
"if",
"isinstance",
"(",
"phi_bins",
",",
"int",
")",
":",
"phi_range",
"=",
"(",
"0",
",",
"2",
"*",
"np",
".",
"pi",
")",
"if",
"\"phi_range\"",
"in",
"\"kwargs\"",
":",
"phi_range",
"=",
"kwargs",
"[",
"\"phi_range\"",
"]",
"elif",
"\"range\"",
"in",
"\"kwargs\"",
":",
"phi_range",
"=",
"kwargs",
"[",
"\"range\"",
"]",
"[",
"1",
"]",
"phi_range",
"=",
"list",
"(",
"phi_range",
")",
"+",
"[",
"phi_bins",
"+",
"1",
"]",
"phi_bins",
"=",
"np",
".",
"linspace",
"(",
"*",
"phi_range",
")",
"bin_schemas",
"=",
"binnings",
".",
"calculate_bins_nd",
"(",
"data",
",",
"[",
"radial_bins",
",",
"phi_bins",
"]",
",",
"*",
"args",
",",
"check_nan",
"=",
"not",
"dropna",
",",
"*",
"*",
"kwargs",
")",
"weights",
"=",
"kwargs",
".",
"pop",
"(",
"\"weights\"",
",",
"None",
")",
"frequencies",
",",
"errors2",
",",
"missed",
"=",
"histogram_nd",
".",
"calculate_frequencies",
"(",
"data",
",",
"ndim",
"=",
"2",
",",
"binnings",
"=",
"bin_schemas",
",",
"weights",
"=",
"weights",
")",
"return",
"PolarHistogram",
"(",
"binnings",
"=",
"bin_schemas",
",",
"frequencies",
"=",
"frequencies",
",",
"errors2",
"=",
"errors2",
",",
"missed",
"=",
"missed",
")"
] |
Facade construction function for the PolarHistogram.
Parameters
----------
transformed : bool
phi_range : Optional[tuple]
range
|
[
"Facade",
"construction",
"function",
"for",
"the",
"PolarHistogram",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/special.py#L348-L377
|
16,502
|
janpipek/physt
|
physt/special.py
|
spherical_histogram
|
def spherical_histogram(data=None, radial_bins="numpy", theta_bins=16, phi_bins=16, transformed=False, *args, **kwargs):
"""Facade construction function for the SphericalHistogram.
"""
dropna = kwargs.pop("dropna", True)
data = _prepare_data(data, transformed=transformed, klass=SphericalHistogram, dropna=dropna)
if isinstance(theta_bins, int):
theta_range = (0, np.pi)
if "theta_range" in "kwargs":
theta_range = kwargs["theta_range"]
elif "range" in "kwargs":
theta_range = kwargs["range"][1]
theta_range = list(theta_range) + [theta_bins + 1]
theta_bins = np.linspace(*theta_range)
if isinstance(phi_bins, int):
phi_range = (0, 2 * np.pi)
if "phi_range" in "kwargs":
phi_range = kwargs["phi_range"]
elif "range" in "kwargs":
phi_range = kwargs["range"][2]
phi_range = list(phi_range) + [phi_bins + 1]
phi_bins = np.linspace(*phi_range)
bin_schemas = binnings.calculate_bins_nd(data, [radial_bins, theta_bins, phi_bins], *args,
check_nan=not dropna, **kwargs)
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=3,
binnings=bin_schemas,
weights=weights)
return SphericalHistogram(binnings=bin_schemas, frequencies=frequencies, errors2=errors2, missed=missed)
|
python
|
def spherical_histogram(data=None, radial_bins="numpy", theta_bins=16, phi_bins=16, transformed=False, *args, **kwargs):
"""Facade construction function for the SphericalHistogram.
"""
dropna = kwargs.pop("dropna", True)
data = _prepare_data(data, transformed=transformed, klass=SphericalHistogram, dropna=dropna)
if isinstance(theta_bins, int):
theta_range = (0, np.pi)
if "theta_range" in "kwargs":
theta_range = kwargs["theta_range"]
elif "range" in "kwargs":
theta_range = kwargs["range"][1]
theta_range = list(theta_range) + [theta_bins + 1]
theta_bins = np.linspace(*theta_range)
if isinstance(phi_bins, int):
phi_range = (0, 2 * np.pi)
if "phi_range" in "kwargs":
phi_range = kwargs["phi_range"]
elif "range" in "kwargs":
phi_range = kwargs["range"][2]
phi_range = list(phi_range) + [phi_bins + 1]
phi_bins = np.linspace(*phi_range)
bin_schemas = binnings.calculate_bins_nd(data, [radial_bins, theta_bins, phi_bins], *args,
check_nan=not dropna, **kwargs)
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=3,
binnings=bin_schemas,
weights=weights)
return SphericalHistogram(binnings=bin_schemas, frequencies=frequencies, errors2=errors2, missed=missed)
|
[
"def",
"spherical_histogram",
"(",
"data",
"=",
"None",
",",
"radial_bins",
"=",
"\"numpy\"",
",",
"theta_bins",
"=",
"16",
",",
"phi_bins",
"=",
"16",
",",
"transformed",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dropna",
"=",
"kwargs",
".",
"pop",
"(",
"\"dropna\"",
",",
"True",
")",
"data",
"=",
"_prepare_data",
"(",
"data",
",",
"transformed",
"=",
"transformed",
",",
"klass",
"=",
"SphericalHistogram",
",",
"dropna",
"=",
"dropna",
")",
"if",
"isinstance",
"(",
"theta_bins",
",",
"int",
")",
":",
"theta_range",
"=",
"(",
"0",
",",
"np",
".",
"pi",
")",
"if",
"\"theta_range\"",
"in",
"\"kwargs\"",
":",
"theta_range",
"=",
"kwargs",
"[",
"\"theta_range\"",
"]",
"elif",
"\"range\"",
"in",
"\"kwargs\"",
":",
"theta_range",
"=",
"kwargs",
"[",
"\"range\"",
"]",
"[",
"1",
"]",
"theta_range",
"=",
"list",
"(",
"theta_range",
")",
"+",
"[",
"theta_bins",
"+",
"1",
"]",
"theta_bins",
"=",
"np",
".",
"linspace",
"(",
"*",
"theta_range",
")",
"if",
"isinstance",
"(",
"phi_bins",
",",
"int",
")",
":",
"phi_range",
"=",
"(",
"0",
",",
"2",
"*",
"np",
".",
"pi",
")",
"if",
"\"phi_range\"",
"in",
"\"kwargs\"",
":",
"phi_range",
"=",
"kwargs",
"[",
"\"phi_range\"",
"]",
"elif",
"\"range\"",
"in",
"\"kwargs\"",
":",
"phi_range",
"=",
"kwargs",
"[",
"\"range\"",
"]",
"[",
"2",
"]",
"phi_range",
"=",
"list",
"(",
"phi_range",
")",
"+",
"[",
"phi_bins",
"+",
"1",
"]",
"phi_bins",
"=",
"np",
".",
"linspace",
"(",
"*",
"phi_range",
")",
"bin_schemas",
"=",
"binnings",
".",
"calculate_bins_nd",
"(",
"data",
",",
"[",
"radial_bins",
",",
"theta_bins",
",",
"phi_bins",
"]",
",",
"*",
"args",
",",
"check_nan",
"=",
"not",
"dropna",
",",
"*",
"*",
"kwargs",
")",
"weights",
"=",
"kwargs",
".",
"pop",
"(",
"\"weights\"",
",",
"None",
")",
"frequencies",
",",
"errors2",
",",
"missed",
"=",
"histogram_nd",
".",
"calculate_frequencies",
"(",
"data",
",",
"ndim",
"=",
"3",
",",
"binnings",
"=",
"bin_schemas",
",",
"weights",
"=",
"weights",
")",
"return",
"SphericalHistogram",
"(",
"binnings",
"=",
"bin_schemas",
",",
"frequencies",
"=",
"frequencies",
",",
"errors2",
"=",
"errors2",
",",
"missed",
"=",
"missed",
")"
] |
Facade construction function for the SphericalHistogram.
|
[
"Facade",
"construction",
"function",
"for",
"the",
"SphericalHistogram",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/special.py#L380-L412
|
16,503
|
janpipek/physt
|
physt/special.py
|
cylindrical_histogram
|
def cylindrical_histogram(data=None, rho_bins="numpy", phi_bins=16, z_bins="numpy", transformed=False, *args, **kwargs):
"""Facade construction function for the CylindricalHistogram.
"""
dropna = kwargs.pop("dropna", True)
data = _prepare_data(data, transformed=transformed, klass=CylindricalHistogram, dropna=dropna)
if isinstance(phi_bins, int):
phi_range = (0, 2 * np.pi)
if "phi_range" in "kwargs":
phi_range = kwargs["phi_range"]
elif "range" in "kwargs":
phi_range = kwargs["range"][1]
phi_range = list(phi_range) + [phi_bins + 1]
phi_bins = np.linspace(*phi_range)
bin_schemas = binnings.calculate_bins_nd(data, [rho_bins, phi_bins, z_bins], *args,
check_nan=not dropna, **kwargs)
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=3,
binnings=bin_schemas,
weights=weights)
return CylindricalHistogram(binnings=bin_schemas, frequencies=frequencies,
errors2=errors2, missed=missed)
|
python
|
def cylindrical_histogram(data=None, rho_bins="numpy", phi_bins=16, z_bins="numpy", transformed=False, *args, **kwargs):
"""Facade construction function for the CylindricalHistogram.
"""
dropna = kwargs.pop("dropna", True)
data = _prepare_data(data, transformed=transformed, klass=CylindricalHistogram, dropna=dropna)
if isinstance(phi_bins, int):
phi_range = (0, 2 * np.pi)
if "phi_range" in "kwargs":
phi_range = kwargs["phi_range"]
elif "range" in "kwargs":
phi_range = kwargs["range"][1]
phi_range = list(phi_range) + [phi_bins + 1]
phi_bins = np.linspace(*phi_range)
bin_schemas = binnings.calculate_bins_nd(data, [rho_bins, phi_bins, z_bins], *args,
check_nan=not dropna, **kwargs)
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=3,
binnings=bin_schemas,
weights=weights)
return CylindricalHistogram(binnings=bin_schemas, frequencies=frequencies,
errors2=errors2, missed=missed)
|
[
"def",
"cylindrical_histogram",
"(",
"data",
"=",
"None",
",",
"rho_bins",
"=",
"\"numpy\"",
",",
"phi_bins",
"=",
"16",
",",
"z_bins",
"=",
"\"numpy\"",
",",
"transformed",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dropna",
"=",
"kwargs",
".",
"pop",
"(",
"\"dropna\"",
",",
"True",
")",
"data",
"=",
"_prepare_data",
"(",
"data",
",",
"transformed",
"=",
"transformed",
",",
"klass",
"=",
"CylindricalHistogram",
",",
"dropna",
"=",
"dropna",
")",
"if",
"isinstance",
"(",
"phi_bins",
",",
"int",
")",
":",
"phi_range",
"=",
"(",
"0",
",",
"2",
"*",
"np",
".",
"pi",
")",
"if",
"\"phi_range\"",
"in",
"\"kwargs\"",
":",
"phi_range",
"=",
"kwargs",
"[",
"\"phi_range\"",
"]",
"elif",
"\"range\"",
"in",
"\"kwargs\"",
":",
"phi_range",
"=",
"kwargs",
"[",
"\"range\"",
"]",
"[",
"1",
"]",
"phi_range",
"=",
"list",
"(",
"phi_range",
")",
"+",
"[",
"phi_bins",
"+",
"1",
"]",
"phi_bins",
"=",
"np",
".",
"linspace",
"(",
"*",
"phi_range",
")",
"bin_schemas",
"=",
"binnings",
".",
"calculate_bins_nd",
"(",
"data",
",",
"[",
"rho_bins",
",",
"phi_bins",
",",
"z_bins",
"]",
",",
"*",
"args",
",",
"check_nan",
"=",
"not",
"dropna",
",",
"*",
"*",
"kwargs",
")",
"weights",
"=",
"kwargs",
".",
"pop",
"(",
"\"weights\"",
",",
"None",
")",
"frequencies",
",",
"errors2",
",",
"missed",
"=",
"histogram_nd",
".",
"calculate_frequencies",
"(",
"data",
",",
"ndim",
"=",
"3",
",",
"binnings",
"=",
"bin_schemas",
",",
"weights",
"=",
"weights",
")",
"return",
"CylindricalHistogram",
"(",
"binnings",
"=",
"bin_schemas",
",",
"frequencies",
"=",
"frequencies",
",",
"errors2",
"=",
"errors2",
",",
"missed",
"=",
"missed",
")"
] |
Facade construction function for the CylindricalHistogram.
|
[
"Facade",
"construction",
"function",
"for",
"the",
"CylindricalHistogram",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/special.py#L415-L439
|
16,504
|
janpipek/physt
|
physt/special.py
|
TransformedHistogramMixin.projection
|
def projection(self, *axes, **kwargs):
"""Projection to lower-dimensional histogram.
The inheriting class should implement the _projection_class_map
class attribute to suggest class for the projection. If the
arguments don't match any of the map keys, HistogramND is used.
"""
axes, _ = self._get_projection_axes(*axes)
axes = tuple(sorted(axes))
if axes in self._projection_class_map:
klass = self._projection_class_map[axes]
return HistogramND.projection(self, *axes, type=klass, **kwargs)
else:
return HistogramND.projection(self, *axes, **kwargs)
|
python
|
def projection(self, *axes, **kwargs):
"""Projection to lower-dimensional histogram.
The inheriting class should implement the _projection_class_map
class attribute to suggest class for the projection. If the
arguments don't match any of the map keys, HistogramND is used.
"""
axes, _ = self._get_projection_axes(*axes)
axes = tuple(sorted(axes))
if axes in self._projection_class_map:
klass = self._projection_class_map[axes]
return HistogramND.projection(self, *axes, type=klass, **kwargs)
else:
return HistogramND.projection(self, *axes, **kwargs)
|
[
"def",
"projection",
"(",
"self",
",",
"*",
"axes",
",",
"*",
"*",
"kwargs",
")",
":",
"axes",
",",
"_",
"=",
"self",
".",
"_get_projection_axes",
"(",
"*",
"axes",
")",
"axes",
"=",
"tuple",
"(",
"sorted",
"(",
"axes",
")",
")",
"if",
"axes",
"in",
"self",
".",
"_projection_class_map",
":",
"klass",
"=",
"self",
".",
"_projection_class_map",
"[",
"axes",
"]",
"return",
"HistogramND",
".",
"projection",
"(",
"self",
",",
"*",
"axes",
",",
"type",
"=",
"klass",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"HistogramND",
".",
"projection",
"(",
"self",
",",
"*",
"axes",
",",
"*",
"*",
"kwargs",
")"
] |
Projection to lower-dimensional histogram.
The inheriting class should implement the _projection_class_map
class attribute to suggest class for the projection. If the
arguments don't match any of the map keys, HistogramND is used.
|
[
"Projection",
"to",
"lower",
"-",
"dimensional",
"histogram",
".",
"The",
"inheriting",
"class",
"should",
"implement",
"the",
"_projection_class_map",
"class",
"attribute",
"to",
"suggest",
"class",
"for",
"the",
"projection",
".",
"If",
"the",
"arguments",
"don",
"t",
"match",
"any",
"of",
"the",
"map",
"keys",
"HistogramND",
"is",
"used",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/special.py#L86-L99
|
16,505
|
janpipek/physt
|
physt/plotting/plotly.py
|
enable_collection
|
def enable_collection(f):
"""Call the wrapped function with a HistogramCollection as argument."""
@wraps(f)
def new_f(h: AbstractHistogram1D, **kwargs):
from physt.histogram_collection import HistogramCollection
if isinstance(h, HistogramCollection):
return f(h, **kwargs)
else:
return f(HistogramCollection(h), **kwargs)
return new_f
|
python
|
def enable_collection(f):
"""Call the wrapped function with a HistogramCollection as argument."""
@wraps(f)
def new_f(h: AbstractHistogram1D, **kwargs):
from physt.histogram_collection import HistogramCollection
if isinstance(h, HistogramCollection):
return f(h, **kwargs)
else:
return f(HistogramCollection(h), **kwargs)
return new_f
|
[
"def",
"enable_collection",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"new_f",
"(",
"h",
":",
"AbstractHistogram1D",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"physt",
".",
"histogram_collection",
"import",
"HistogramCollection",
"if",
"isinstance",
"(",
"h",
",",
"HistogramCollection",
")",
":",
"return",
"f",
"(",
"h",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"f",
"(",
"HistogramCollection",
"(",
"h",
")",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_f"
] |
Call the wrapped function with a HistogramCollection as argument.
|
[
"Call",
"the",
"wrapped",
"function",
"with",
"a",
"HistogramCollection",
"as",
"argument",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/plotly.py#L80-L89
|
16,506
|
janpipek/physt
|
physt/plotting/plotly.py
|
bar
|
def bar(h: Histogram2D, *,
barmode: str = DEFAULT_BARMODE,
alpha: float = DEFAULT_ALPHA,
**kwargs):
"""Bar plot.
Parameters
----------
alpha: Opacity (0.0 - 1.0)
barmode : "overlay" | "group" | "stack"
"""
get_data_kwargs = pop_many(kwargs, "density", "cumulative", "flatten")
data = [go.Bar(
x=histogram.bin_centers,
y=get_data(histogram, **get_data_kwargs),
width=histogram.bin_widths,
name=histogram.name,
opacity=alpha,
**kwargs
) for histogram in h]
layout = go.Layout(barmode=barmode)
_add_ticks(layout.xaxis, h[0], kwargs)
figure = go.Figure(data=data, layout=layout)
return figure
|
python
|
def bar(h: Histogram2D, *,
barmode: str = DEFAULT_BARMODE,
alpha: float = DEFAULT_ALPHA,
**kwargs):
"""Bar plot.
Parameters
----------
alpha: Opacity (0.0 - 1.0)
barmode : "overlay" | "group" | "stack"
"""
get_data_kwargs = pop_many(kwargs, "density", "cumulative", "flatten")
data = [go.Bar(
x=histogram.bin_centers,
y=get_data(histogram, **get_data_kwargs),
width=histogram.bin_widths,
name=histogram.name,
opacity=alpha,
**kwargs
) for histogram in h]
layout = go.Layout(barmode=barmode)
_add_ticks(layout.xaxis, h[0], kwargs)
figure = go.Figure(data=data, layout=layout)
return figure
|
[
"def",
"bar",
"(",
"h",
":",
"Histogram2D",
",",
"*",
",",
"barmode",
":",
"str",
"=",
"DEFAULT_BARMODE",
",",
"alpha",
":",
"float",
"=",
"DEFAULT_ALPHA",
",",
"*",
"*",
"kwargs",
")",
":",
"get_data_kwargs",
"=",
"pop_many",
"(",
"kwargs",
",",
"\"density\"",
",",
"\"cumulative\"",
",",
"\"flatten\"",
")",
"data",
"=",
"[",
"go",
".",
"Bar",
"(",
"x",
"=",
"histogram",
".",
"bin_centers",
",",
"y",
"=",
"get_data",
"(",
"histogram",
",",
"*",
"*",
"get_data_kwargs",
")",
",",
"width",
"=",
"histogram",
".",
"bin_widths",
",",
"name",
"=",
"histogram",
".",
"name",
",",
"opacity",
"=",
"alpha",
",",
"*",
"*",
"kwargs",
")",
"for",
"histogram",
"in",
"h",
"]",
"layout",
"=",
"go",
".",
"Layout",
"(",
"barmode",
"=",
"barmode",
")",
"_add_ticks",
"(",
"layout",
".",
"xaxis",
",",
"h",
"[",
"0",
"]",
",",
"kwargs",
")",
"figure",
"=",
"go",
".",
"Figure",
"(",
"data",
"=",
"data",
",",
"layout",
"=",
"layout",
")",
"return",
"figure"
] |
Bar plot.
Parameters
----------
alpha: Opacity (0.0 - 1.0)
barmode : "overlay" | "group" | "stack"
|
[
"Bar",
"plot",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/plotly.py#L143-L169
|
16,507
|
janpipek/physt
|
physt/plotting/folium.py
|
_bins_to_json
|
def _bins_to_json(h2):
"""Create GeoJSON representation of histogram bins
Parameters
----------
h2: physt.histogram_nd.Histogram2D
A histogram of coordinates (in degrees)
Returns
-------
geo_json : dict
"""
south = h2.get_bin_left_edges(0)
north = h2.get_bin_right_edges(0)
west = h2.get_bin_left_edges(1)
east = h2.get_bin_right_edges(1)
return {
"type":"FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
# Note that folium and GeoJson have them swapped
"coordinates": [[
[east[j], south[i]],
[east[j], north[i]],
[west[j], north[i]],
[west[j], south[i]],
[east[j], south[i]]]],
},
"properties" : {
"count": float(h2.frequencies[i, j])
}
}
for i in range(h2.shape[0])
for j in range(h2.shape[1])
]
}
|
python
|
def _bins_to_json(h2):
"""Create GeoJSON representation of histogram bins
Parameters
----------
h2: physt.histogram_nd.Histogram2D
A histogram of coordinates (in degrees)
Returns
-------
geo_json : dict
"""
south = h2.get_bin_left_edges(0)
north = h2.get_bin_right_edges(0)
west = h2.get_bin_left_edges(1)
east = h2.get_bin_right_edges(1)
return {
"type":"FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
# Note that folium and GeoJson have them swapped
"coordinates": [[
[east[j], south[i]],
[east[j], north[i]],
[west[j], north[i]],
[west[j], south[i]],
[east[j], south[i]]]],
},
"properties" : {
"count": float(h2.frequencies[i, j])
}
}
for i in range(h2.shape[0])
for j in range(h2.shape[1])
]
}
|
[
"def",
"_bins_to_json",
"(",
"h2",
")",
":",
"south",
"=",
"h2",
".",
"get_bin_left_edges",
"(",
"0",
")",
"north",
"=",
"h2",
".",
"get_bin_right_edges",
"(",
"0",
")",
"west",
"=",
"h2",
".",
"get_bin_left_edges",
"(",
"1",
")",
"east",
"=",
"h2",
".",
"get_bin_right_edges",
"(",
"1",
")",
"return",
"{",
"\"type\"",
":",
"\"FeatureCollection\"",
",",
"\"features\"",
":",
"[",
"{",
"\"type\"",
":",
"\"Feature\"",
",",
"\"geometry\"",
":",
"{",
"\"type\"",
":",
"\"Polygon\"",
",",
"# Note that folium and GeoJson have them swapped",
"\"coordinates\"",
":",
"[",
"[",
"[",
"east",
"[",
"j",
"]",
",",
"south",
"[",
"i",
"]",
"]",
",",
"[",
"east",
"[",
"j",
"]",
",",
"north",
"[",
"i",
"]",
"]",
",",
"[",
"west",
"[",
"j",
"]",
",",
"north",
"[",
"i",
"]",
"]",
",",
"[",
"west",
"[",
"j",
"]",
",",
"south",
"[",
"i",
"]",
"]",
",",
"[",
"east",
"[",
"j",
"]",
",",
"south",
"[",
"i",
"]",
"]",
"]",
"]",
",",
"}",
",",
"\"properties\"",
":",
"{",
"\"count\"",
":",
"float",
"(",
"h2",
".",
"frequencies",
"[",
"i",
",",
"j",
"]",
")",
"}",
"}",
"for",
"i",
"in",
"range",
"(",
"h2",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"j",
"in",
"range",
"(",
"h2",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"}"
] |
Create GeoJSON representation of histogram bins
Parameters
----------
h2: physt.histogram_nd.Histogram2D
A histogram of coordinates (in degrees)
Returns
-------
geo_json : dict
|
[
"Create",
"GeoJSON",
"representation",
"of",
"histogram",
"bins"
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/folium.py#L16-L54
|
16,508
|
janpipek/physt
|
physt/plotting/folium.py
|
geo_map
|
def geo_map(h2, map=None, tiles='stamenterrain', cmap="wk", alpha=0.5, lw=1, fit_bounds=None, layer_name=None):
"""Show rectangular grid over a map.
Parameters
----------
h2: physt.histogram_nd.Histogram2D
A histogram of coordinates (in degrees: latitude, longitude)
map : folium.folium.Map
Returns
-------
map : folium.folium.Map
"""
if not map:
latitude = h2.get_bin_centers(0).mean()
longitude = h2.get_bin_centers(1).mean()
zoom_start = 10
map = folium.Map(location=[latitude, longitude], tiles=tiles)
if fit_bounds == None:
fit_bounds = True
geo_json = _bins_to_json(h2)
if not layer_name:
layer_name = h2.name
from branca.colormap import LinearColormap
color_map = LinearColormap(cmap, vmin=h2.frequencies.min(), vmax=h2.frequencies.max())
# legend = folium.Html("<div>Legend</div>")
# legend_div = folium.Div("20%", "20%", "75%", "5%")
#
# legend_div.add_to(map)
# legend_div.add_child(legend)
#xx = h2.frequencies.max()
def styling_function(bin):
count = bin["properties"]["count"]
return {
"fillColor": color_map(count),
"color": "black",
"fillOpacity": alpha if count > 0 else 0,
"weight": lw,
# "strokeWidth": lw,
"opacity": alpha if count > 0 else 0,
}# .update(styling)
layer = folium.GeoJson(geo_json, style_function=styling_function, name=layer_name)
layer.add_to(map)
if fit_bounds:
map.fit_bounds(layer.get_bounds())
return map
|
python
|
def geo_map(h2, map=None, tiles='stamenterrain', cmap="wk", alpha=0.5, lw=1, fit_bounds=None, layer_name=None):
"""Show rectangular grid over a map.
Parameters
----------
h2: physt.histogram_nd.Histogram2D
A histogram of coordinates (in degrees: latitude, longitude)
map : folium.folium.Map
Returns
-------
map : folium.folium.Map
"""
if not map:
latitude = h2.get_bin_centers(0).mean()
longitude = h2.get_bin_centers(1).mean()
zoom_start = 10
map = folium.Map(location=[latitude, longitude], tiles=tiles)
if fit_bounds == None:
fit_bounds = True
geo_json = _bins_to_json(h2)
if not layer_name:
layer_name = h2.name
from branca.colormap import LinearColormap
color_map = LinearColormap(cmap, vmin=h2.frequencies.min(), vmax=h2.frequencies.max())
# legend = folium.Html("<div>Legend</div>")
# legend_div = folium.Div("20%", "20%", "75%", "5%")
#
# legend_div.add_to(map)
# legend_div.add_child(legend)
#xx = h2.frequencies.max()
def styling_function(bin):
count = bin["properties"]["count"]
return {
"fillColor": color_map(count),
"color": "black",
"fillOpacity": alpha if count > 0 else 0,
"weight": lw,
# "strokeWidth": lw,
"opacity": alpha if count > 0 else 0,
}# .update(styling)
layer = folium.GeoJson(geo_json, style_function=styling_function, name=layer_name)
layer.add_to(map)
if fit_bounds:
map.fit_bounds(layer.get_bounds())
return map
|
[
"def",
"geo_map",
"(",
"h2",
",",
"map",
"=",
"None",
",",
"tiles",
"=",
"'stamenterrain'",
",",
"cmap",
"=",
"\"wk\"",
",",
"alpha",
"=",
"0.5",
",",
"lw",
"=",
"1",
",",
"fit_bounds",
"=",
"None",
",",
"layer_name",
"=",
"None",
")",
":",
"if",
"not",
"map",
":",
"latitude",
"=",
"h2",
".",
"get_bin_centers",
"(",
"0",
")",
".",
"mean",
"(",
")",
"longitude",
"=",
"h2",
".",
"get_bin_centers",
"(",
"1",
")",
".",
"mean",
"(",
")",
"zoom_start",
"=",
"10",
"map",
"=",
"folium",
".",
"Map",
"(",
"location",
"=",
"[",
"latitude",
",",
"longitude",
"]",
",",
"tiles",
"=",
"tiles",
")",
"if",
"fit_bounds",
"==",
"None",
":",
"fit_bounds",
"=",
"True",
"geo_json",
"=",
"_bins_to_json",
"(",
"h2",
")",
"if",
"not",
"layer_name",
":",
"layer_name",
"=",
"h2",
".",
"name",
"from",
"branca",
".",
"colormap",
"import",
"LinearColormap",
"color_map",
"=",
"LinearColormap",
"(",
"cmap",
",",
"vmin",
"=",
"h2",
".",
"frequencies",
".",
"min",
"(",
")",
",",
"vmax",
"=",
"h2",
".",
"frequencies",
".",
"max",
"(",
")",
")",
"# legend = folium.Html(\"<div>Legend</div>\")",
"# legend_div = folium.Div(\"20%\", \"20%\", \"75%\", \"5%\")",
"#",
"# legend_div.add_to(map)",
"# legend_div.add_child(legend)",
"#xx = h2.frequencies.max()",
"def",
"styling_function",
"(",
"bin",
")",
":",
"count",
"=",
"bin",
"[",
"\"properties\"",
"]",
"[",
"\"count\"",
"]",
"return",
"{",
"\"fillColor\"",
":",
"color_map",
"(",
"count",
")",
",",
"\"color\"",
":",
"\"black\"",
",",
"\"fillOpacity\"",
":",
"alpha",
"if",
"count",
">",
"0",
"else",
"0",
",",
"\"weight\"",
":",
"lw",
",",
"# \"strokeWidth\": lw,",
"\"opacity\"",
":",
"alpha",
"if",
"count",
">",
"0",
"else",
"0",
",",
"}",
"# .update(styling)",
"layer",
"=",
"folium",
".",
"GeoJson",
"(",
"geo_json",
",",
"style_function",
"=",
"styling_function",
",",
"name",
"=",
"layer_name",
")",
"layer",
".",
"add_to",
"(",
"map",
")",
"if",
"fit_bounds",
":",
"map",
".",
"fit_bounds",
"(",
"layer",
".",
"get_bounds",
"(",
")",
")",
"return",
"map"
] |
Show rectangular grid over a map.
Parameters
----------
h2: physt.histogram_nd.Histogram2D
A histogram of coordinates (in degrees: latitude, longitude)
map : folium.folium.Map
Returns
-------
map : folium.folium.Map
|
[
"Show",
"rectangular",
"grid",
"over",
"a",
"map",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/folium.py#L57-L110
|
16,509
|
janpipek/physt
|
physt/compat/geant4.py
|
load_csv
|
def load_csv(path):
"""Loads a histogram as output from Geant4 analysis tools in CSV format.
Parameters
----------
path: str
Path to the CSV file
Returns
-------
physt.histogram1d.Histogram1D or physt.histogram_nd.Histogram2D
"""
meta = []
data = []
with codecs.open(path, encoding="ASCII") as in_file:
for line in in_file:
if line.startswith("#"):
key, value = line[1:].strip().split(" ", 1)
meta.append((key, value)) # TODO: There are duplicit entries :-()
else:
try:
data.append([float(frag) for frag in line.split(",")])
except:
pass
data = np.asarray(data)
ndim = int(_get(meta, "dimension"))
if ndim == 1:
return _create_h1(data, meta)
elif ndim == 2:
return _create_h2(data, meta)
|
python
|
def load_csv(path):
"""Loads a histogram as output from Geant4 analysis tools in CSV format.
Parameters
----------
path: str
Path to the CSV file
Returns
-------
physt.histogram1d.Histogram1D or physt.histogram_nd.Histogram2D
"""
meta = []
data = []
with codecs.open(path, encoding="ASCII") as in_file:
for line in in_file:
if line.startswith("#"):
key, value = line[1:].strip().split(" ", 1)
meta.append((key, value)) # TODO: There are duplicit entries :-()
else:
try:
data.append([float(frag) for frag in line.split(",")])
except:
pass
data = np.asarray(data)
ndim = int(_get(meta, "dimension"))
if ndim == 1:
return _create_h1(data, meta)
elif ndim == 2:
return _create_h2(data, meta)
|
[
"def",
"load_csv",
"(",
"path",
")",
":",
"meta",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"with",
"codecs",
".",
"open",
"(",
"path",
",",
"encoding",
"=",
"\"ASCII\"",
")",
"as",
"in_file",
":",
"for",
"line",
"in",
"in_file",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"key",
",",
"value",
"=",
"line",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
",",
"1",
")",
"meta",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"# TODO: There are duplicit entries :-()",
"else",
":",
"try",
":",
"data",
".",
"append",
"(",
"[",
"float",
"(",
"frag",
")",
"for",
"frag",
"in",
"line",
".",
"split",
"(",
"\",\"",
")",
"]",
")",
"except",
":",
"pass",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"ndim",
"=",
"int",
"(",
"_get",
"(",
"meta",
",",
"\"dimension\"",
")",
")",
"if",
"ndim",
"==",
"1",
":",
"return",
"_create_h1",
"(",
"data",
",",
"meta",
")",
"elif",
"ndim",
"==",
"2",
":",
"return",
"_create_h2",
"(",
"data",
",",
"meta",
")"
] |
Loads a histogram as output from Geant4 analysis tools in CSV format.
Parameters
----------
path: str
Path to the CSV file
Returns
-------
physt.histogram1d.Histogram1D or physt.histogram_nd.Histogram2D
|
[
"Loads",
"a",
"histogram",
"as",
"output",
"from",
"Geant4",
"analysis",
"tools",
"in",
"CSV",
"format",
"."
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/compat/geant4.py#L11-L40
|
16,510
|
janpipek/physt
|
physt/compat/geant4.py
|
_get
|
def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
return matches[0]
else:
return matches
|
python
|
def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
return matches[0]
else:
return matches
|
[
"def",
"_get",
"(",
"pseudodict",
",",
"key",
",",
"single",
"=",
"True",
")",
":",
"matches",
"=",
"[",
"item",
"[",
"1",
"]",
"for",
"item",
"in",
"pseudodict",
"if",
"item",
"[",
"0",
"]",
"==",
"key",
"]",
"if",
"single",
":",
"return",
"matches",
"[",
"0",
"]",
"else",
":",
"return",
"matches"
] |
Helper method for getting values from "multi-dict"s
|
[
"Helper",
"method",
"for",
"getting",
"values",
"from",
"multi",
"-",
"dict",
"s"
] |
6dd441b073514e7728235f50b2352d56aacf38d4
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/compat/geant4.py#L43-L49
|
16,511
|
openid/python-openid
|
openid/yadis/xrires.py
|
ProxyResolver.queryURL
|
def queryURL(self, xri, service_type=None):
"""Build a URL to query the proxy resolver.
@param xri: An XRI to resolve.
@type xri: unicode
@param service_type: The service type to resolve, if you desire
service endpoint selection. A service type is a URI.
@type service_type: str
@returns: a URL
@returntype: str
"""
# Trim off the xri:// prefix. The proxy resolver didn't accept it
# when this code was written, but that may (or may not) change for
# XRI Resolution 2.0 Working Draft 11.
qxri = toURINormal(xri)[6:]
hxri = self.proxy_url + qxri
args = {
# XXX: If the proxy resolver will ensure that it doesn't return
# bogus CanonicalIDs (as per Steve's message of 15 Aug 2006
# 11:13:42), then we could ask for application/xrd+xml instead,
# which would give us a bit less to process.
'_xrd_r': 'application/xrds+xml',
}
if service_type:
args['_xrd_t'] = service_type
else:
# Don't perform service endpoint selection.
args['_xrd_r'] += ';sep=false'
query = _appendArgs(hxri, args)
return query
|
python
|
def queryURL(self, xri, service_type=None):
"""Build a URL to query the proxy resolver.
@param xri: An XRI to resolve.
@type xri: unicode
@param service_type: The service type to resolve, if you desire
service endpoint selection. A service type is a URI.
@type service_type: str
@returns: a URL
@returntype: str
"""
# Trim off the xri:// prefix. The proxy resolver didn't accept it
# when this code was written, but that may (or may not) change for
# XRI Resolution 2.0 Working Draft 11.
qxri = toURINormal(xri)[6:]
hxri = self.proxy_url + qxri
args = {
# XXX: If the proxy resolver will ensure that it doesn't return
# bogus CanonicalIDs (as per Steve's message of 15 Aug 2006
# 11:13:42), then we could ask for application/xrd+xml instead,
# which would give us a bit less to process.
'_xrd_r': 'application/xrds+xml',
}
if service_type:
args['_xrd_t'] = service_type
else:
# Don't perform service endpoint selection.
args['_xrd_r'] += ';sep=false'
query = _appendArgs(hxri, args)
return query
|
[
"def",
"queryURL",
"(",
"self",
",",
"xri",
",",
"service_type",
"=",
"None",
")",
":",
"# Trim off the xri:// prefix. The proxy resolver didn't accept it",
"# when this code was written, but that may (or may not) change for",
"# XRI Resolution 2.0 Working Draft 11.",
"qxri",
"=",
"toURINormal",
"(",
"xri",
")",
"[",
"6",
":",
"]",
"hxri",
"=",
"self",
".",
"proxy_url",
"+",
"qxri",
"args",
"=",
"{",
"# XXX: If the proxy resolver will ensure that it doesn't return",
"# bogus CanonicalIDs (as per Steve's message of 15 Aug 2006",
"# 11:13:42), then we could ask for application/xrd+xml instead,",
"# which would give us a bit less to process.",
"'_xrd_r'",
":",
"'application/xrds+xml'",
",",
"}",
"if",
"service_type",
":",
"args",
"[",
"'_xrd_t'",
"]",
"=",
"service_type",
"else",
":",
"# Don't perform service endpoint selection.",
"args",
"[",
"'_xrd_r'",
"]",
"+=",
"';sep=false'",
"query",
"=",
"_appendArgs",
"(",
"hxri",
",",
"args",
")",
"return",
"query"
] |
Build a URL to query the proxy resolver.
@param xri: An XRI to resolve.
@type xri: unicode
@param service_type: The service type to resolve, if you desire
service endpoint selection. A service type is a URI.
@type service_type: str
@returns: a URL
@returntype: str
|
[
"Build",
"a",
"URL",
"to",
"query",
"the",
"proxy",
"resolver",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xrires.py#L20-L51
|
16,512
|
openid/python-openid
|
openid/yadis/xrires.py
|
ProxyResolver.query
|
def query(self, xri, service_types):
"""Resolve some services for an XRI.
Note: I don't implement any service endpoint selection beyond what
the resolver I'm querying does, so the Services I return may well
include Services that were not of the types you asked for.
May raise fetchers.HTTPFetchingError or L{etxrd.XRDSError} if
the fetching or parsing don't go so well.
@param xri: An XRI to resolve.
@type xri: unicode
@param service_types: A list of services types to query for. Service
types are URIs.
@type service_types: list of str
@returns: tuple of (CanonicalID, Service elements)
@returntype: (unicode, list of C{ElementTree.Element}s)
"""
# FIXME: No test coverage!
services = []
# Make a seperate request to the proxy resolver for each service
# type, as, if it is following Refs, it could return a different
# XRDS for each.
canonicalID = None
for service_type in service_types:
url = self.queryURL(xri, service_type)
response = fetchers.fetch(url)
if response.status not in (200, 206):
# XXX: sucks to fail silently.
# print "response not OK:", response
continue
et = etxrd.parseXRDS(response.body)
canonicalID = etxrd.getCanonicalID(xri, et)
some_services = list(iterServices(et))
services.extend(some_services)
# TODO:
# * If we do get hits for multiple service_types, we're almost
# certainly going to have duplicated service entries and
# broken priority ordering.
return canonicalID, services
|
python
|
def query(self, xri, service_types):
"""Resolve some services for an XRI.
Note: I don't implement any service endpoint selection beyond what
the resolver I'm querying does, so the Services I return may well
include Services that were not of the types you asked for.
May raise fetchers.HTTPFetchingError or L{etxrd.XRDSError} if
the fetching or parsing don't go so well.
@param xri: An XRI to resolve.
@type xri: unicode
@param service_types: A list of services types to query for. Service
types are URIs.
@type service_types: list of str
@returns: tuple of (CanonicalID, Service elements)
@returntype: (unicode, list of C{ElementTree.Element}s)
"""
# FIXME: No test coverage!
services = []
# Make a seperate request to the proxy resolver for each service
# type, as, if it is following Refs, it could return a different
# XRDS for each.
canonicalID = None
for service_type in service_types:
url = self.queryURL(xri, service_type)
response = fetchers.fetch(url)
if response.status not in (200, 206):
# XXX: sucks to fail silently.
# print "response not OK:", response
continue
et = etxrd.parseXRDS(response.body)
canonicalID = etxrd.getCanonicalID(xri, et)
some_services = list(iterServices(et))
services.extend(some_services)
# TODO:
# * If we do get hits for multiple service_types, we're almost
# certainly going to have duplicated service entries and
# broken priority ordering.
return canonicalID, services
|
[
"def",
"query",
"(",
"self",
",",
"xri",
",",
"service_types",
")",
":",
"# FIXME: No test coverage!",
"services",
"=",
"[",
"]",
"# Make a seperate request to the proxy resolver for each service",
"# type, as, if it is following Refs, it could return a different",
"# XRDS for each.",
"canonicalID",
"=",
"None",
"for",
"service_type",
"in",
"service_types",
":",
"url",
"=",
"self",
".",
"queryURL",
"(",
"xri",
",",
"service_type",
")",
"response",
"=",
"fetchers",
".",
"fetch",
"(",
"url",
")",
"if",
"response",
".",
"status",
"not",
"in",
"(",
"200",
",",
"206",
")",
":",
"# XXX: sucks to fail silently.",
"# print \"response not OK:\", response",
"continue",
"et",
"=",
"etxrd",
".",
"parseXRDS",
"(",
"response",
".",
"body",
")",
"canonicalID",
"=",
"etxrd",
".",
"getCanonicalID",
"(",
"xri",
",",
"et",
")",
"some_services",
"=",
"list",
"(",
"iterServices",
"(",
"et",
")",
")",
"services",
".",
"extend",
"(",
"some_services",
")",
"# TODO:",
"# * If we do get hits for multiple service_types, we're almost",
"# certainly going to have duplicated service entries and",
"# broken priority ordering.",
"return",
"canonicalID",
",",
"services"
] |
Resolve some services for an XRI.
Note: I don't implement any service endpoint selection beyond what
the resolver I'm querying does, so the Services I return may well
include Services that were not of the types you asked for.
May raise fetchers.HTTPFetchingError or L{etxrd.XRDSError} if
the fetching or parsing don't go so well.
@param xri: An XRI to resolve.
@type xri: unicode
@param service_types: A list of services types to query for. Service
types are URIs.
@type service_types: list of str
@returns: tuple of (CanonicalID, Service elements)
@returntype: (unicode, list of C{ElementTree.Element}s)
|
[
"Resolve",
"some",
"services",
"for",
"an",
"XRI",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xrires.py#L54-L97
|
16,513
|
openid/python-openid
|
openid/yadis/accept.py
|
generateAcceptHeader
|
def generateAcceptHeader(*elements):
"""Generate an accept header value
[str or (str, float)] -> str
"""
parts = []
for element in elements:
if type(element) is str:
qs = "1.0"
mtype = element
else:
mtype, q = element
q = float(q)
if q > 1 or q <= 0:
raise ValueError('Invalid preference factor: %r' % q)
qs = '%0.1f' % (q,)
parts.append((qs, mtype))
parts.sort()
chunks = []
for q, mtype in parts:
if q == '1.0':
chunks.append(mtype)
else:
chunks.append('%s; q=%s' % (mtype, q))
return ', '.join(chunks)
|
python
|
def generateAcceptHeader(*elements):
"""Generate an accept header value
[str or (str, float)] -> str
"""
parts = []
for element in elements:
if type(element) is str:
qs = "1.0"
mtype = element
else:
mtype, q = element
q = float(q)
if q > 1 or q <= 0:
raise ValueError('Invalid preference factor: %r' % q)
qs = '%0.1f' % (q,)
parts.append((qs, mtype))
parts.sort()
chunks = []
for q, mtype in parts:
if q == '1.0':
chunks.append(mtype)
else:
chunks.append('%s; q=%s' % (mtype, q))
return ', '.join(chunks)
|
[
"def",
"generateAcceptHeader",
"(",
"*",
"elements",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"element",
"in",
"elements",
":",
"if",
"type",
"(",
"element",
")",
"is",
"str",
":",
"qs",
"=",
"\"1.0\"",
"mtype",
"=",
"element",
"else",
":",
"mtype",
",",
"q",
"=",
"element",
"q",
"=",
"float",
"(",
"q",
")",
"if",
"q",
">",
"1",
"or",
"q",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid preference factor: %r'",
"%",
"q",
")",
"qs",
"=",
"'%0.1f'",
"%",
"(",
"q",
",",
")",
"parts",
".",
"append",
"(",
"(",
"qs",
",",
"mtype",
")",
")",
"parts",
".",
"sort",
"(",
")",
"chunks",
"=",
"[",
"]",
"for",
"q",
",",
"mtype",
"in",
"parts",
":",
"if",
"q",
"==",
"'1.0'",
":",
"chunks",
".",
"append",
"(",
"mtype",
")",
"else",
":",
"chunks",
".",
"append",
"(",
"'%s; q=%s'",
"%",
"(",
"mtype",
",",
"q",
")",
")",
"return",
"', '",
".",
"join",
"(",
"chunks",
")"
] |
Generate an accept header value
[str or (str, float)] -> str
|
[
"Generate",
"an",
"accept",
"header",
"value"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/accept.py#L5-L33
|
16,514
|
openid/python-openid
|
openid/yadis/accept.py
|
parseAcceptHeader
|
def parseAcceptHeader(value):
"""Parse an accept header, ignoring any accept-extensions
returns a list of tuples containing main MIME type, MIME subtype,
and quality markdown.
str -> [(str, str, float)]
"""
chunks = [chunk.strip() for chunk in value.split(',')]
accept = []
for chunk in chunks:
parts = [s.strip() for s in chunk.split(';')]
mtype = parts.pop(0)
if '/' not in mtype:
# This is not a MIME type, so ignore the bad data
continue
main, sub = mtype.split('/', 1)
for ext in parts:
if '=' in ext:
k, v = ext.split('=', 1)
if k == 'q':
try:
q = float(v)
break
except ValueError:
# Ignore poorly formed q-values
pass
else:
q = 1.0
accept.append((q, main, sub))
accept.sort()
accept.reverse()
return [(main, sub, q) for (q, main, sub) in accept]
|
python
|
def parseAcceptHeader(value):
"""Parse an accept header, ignoring any accept-extensions
returns a list of tuples containing main MIME type, MIME subtype,
and quality markdown.
str -> [(str, str, float)]
"""
chunks = [chunk.strip() for chunk in value.split(',')]
accept = []
for chunk in chunks:
parts = [s.strip() for s in chunk.split(';')]
mtype = parts.pop(0)
if '/' not in mtype:
# This is not a MIME type, so ignore the bad data
continue
main, sub = mtype.split('/', 1)
for ext in parts:
if '=' in ext:
k, v = ext.split('=', 1)
if k == 'q':
try:
q = float(v)
break
except ValueError:
# Ignore poorly formed q-values
pass
else:
q = 1.0
accept.append((q, main, sub))
accept.sort()
accept.reverse()
return [(main, sub, q) for (q, main, sub) in accept]
|
[
"def",
"parseAcceptHeader",
"(",
"value",
")",
":",
"chunks",
"=",
"[",
"chunk",
".",
"strip",
"(",
")",
"for",
"chunk",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"accept",
"=",
"[",
"]",
"for",
"chunk",
"in",
"chunks",
":",
"parts",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"chunk",
".",
"split",
"(",
"';'",
")",
"]",
"mtype",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
"if",
"'/'",
"not",
"in",
"mtype",
":",
"# This is not a MIME type, so ignore the bad data",
"continue",
"main",
",",
"sub",
"=",
"mtype",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"for",
"ext",
"in",
"parts",
":",
"if",
"'='",
"in",
"ext",
":",
"k",
",",
"v",
"=",
"ext",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"k",
"==",
"'q'",
":",
"try",
":",
"q",
"=",
"float",
"(",
"v",
")",
"break",
"except",
"ValueError",
":",
"# Ignore poorly formed q-values",
"pass",
"else",
":",
"q",
"=",
"1.0",
"accept",
".",
"append",
"(",
"(",
"q",
",",
"main",
",",
"sub",
")",
")",
"accept",
".",
"sort",
"(",
")",
"accept",
".",
"reverse",
"(",
")",
"return",
"[",
"(",
"main",
",",
"sub",
",",
"q",
")",
"for",
"(",
"q",
",",
"main",
",",
"sub",
")",
"in",
"accept",
"]"
] |
Parse an accept header, ignoring any accept-extensions
returns a list of tuples containing main MIME type, MIME subtype,
and quality markdown.
str -> [(str, str, float)]
|
[
"Parse",
"an",
"accept",
"header",
"ignoring",
"any",
"accept",
"-",
"extensions"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/accept.py#L35-L72
|
16,515
|
openid/python-openid
|
openid/yadis/accept.py
|
getAcceptable
|
def getAcceptable(accept_header, have_types):
"""Parse the accept header and return a list of available types in
preferred order. If a type is unacceptable, it will not be in the
resulting list.
This is a convenience wrapper around matchTypes and
parseAcceptHeader.
(str, [str]) -> [str]
"""
accepted = parseAcceptHeader(accept_header)
preferred = matchTypes(accepted, have_types)
return [mtype for (mtype, _) in preferred]
|
python
|
def getAcceptable(accept_header, have_types):
"""Parse the accept header and return a list of available types in
preferred order. If a type is unacceptable, it will not be in the
resulting list.
This is a convenience wrapper around matchTypes and
parseAcceptHeader.
(str, [str]) -> [str]
"""
accepted = parseAcceptHeader(accept_header)
preferred = matchTypes(accepted, have_types)
return [mtype for (mtype, _) in preferred]
|
[
"def",
"getAcceptable",
"(",
"accept_header",
",",
"have_types",
")",
":",
"accepted",
"=",
"parseAcceptHeader",
"(",
"accept_header",
")",
"preferred",
"=",
"matchTypes",
"(",
"accepted",
",",
"have_types",
")",
"return",
"[",
"mtype",
"for",
"(",
"mtype",
",",
"_",
")",
"in",
"preferred",
"]"
] |
Parse the accept header and return a list of available types in
preferred order. If a type is unacceptable, it will not be in the
resulting list.
This is a convenience wrapper around matchTypes and
parseAcceptHeader.
(str, [str]) -> [str]
|
[
"Parse",
"the",
"accept",
"header",
"and",
"return",
"a",
"list",
"of",
"available",
"types",
"in",
"preferred",
"order",
".",
"If",
"a",
"type",
"is",
"unacceptable",
"it",
"will",
"not",
"be",
"in",
"the",
"resulting",
"list",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/accept.py#L121-L133
|
16,516
|
openid/python-openid
|
openid/message.py
|
Message.fromPostArgs
|
def fromPostArgs(cls, args):
"""Construct a Message containing a set of POST arguments.
"""
self = cls()
# Partition into "openid." args and bare args
openid_args = {}
for key, value in args.items():
if isinstance(value, list):
raise TypeError("query dict must have one value for each key, "
"not lists of values. Query is %r" % (args,))
try:
prefix, rest = key.split('.', 1)
except ValueError:
prefix = None
if prefix != 'openid':
self.args[(BARE_NS, key)] = value
else:
openid_args[rest] = value
self._fromOpenIDArgs(openid_args)
return self
|
python
|
def fromPostArgs(cls, args):
"""Construct a Message containing a set of POST arguments.
"""
self = cls()
# Partition into "openid." args and bare args
openid_args = {}
for key, value in args.items():
if isinstance(value, list):
raise TypeError("query dict must have one value for each key, "
"not lists of values. Query is %r" % (args,))
try:
prefix, rest = key.split('.', 1)
except ValueError:
prefix = None
if prefix != 'openid':
self.args[(BARE_NS, key)] = value
else:
openid_args[rest] = value
self._fromOpenIDArgs(openid_args)
return self
|
[
"def",
"fromPostArgs",
"(",
"cls",
",",
"args",
")",
":",
"self",
"=",
"cls",
"(",
")",
"# Partition into \"openid.\" args and bare args",
"openid_args",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"query dict must have one value for each key, \"",
"\"not lists of values. Query is %r\"",
"%",
"(",
"args",
",",
")",
")",
"try",
":",
"prefix",
",",
"rest",
"=",
"key",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":",
"prefix",
"=",
"None",
"if",
"prefix",
"!=",
"'openid'",
":",
"self",
".",
"args",
"[",
"(",
"BARE_NS",
",",
"key",
")",
"]",
"=",
"value",
"else",
":",
"openid_args",
"[",
"rest",
"]",
"=",
"value",
"self",
".",
"_fromOpenIDArgs",
"(",
"openid_args",
")",
"return",
"self"
] |
Construct a Message containing a set of POST arguments.
|
[
"Construct",
"a",
"Message",
"containing",
"a",
"set",
"of",
"POST",
"arguments",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/message.py#L143-L169
|
16,517
|
openid/python-openid
|
openid/message.py
|
Message.getKey
|
def getKey(self, namespace, ns_key):
"""Get the key for a particular namespaced argument"""
namespace = self._fixNS(namespace)
if namespace == BARE_NS:
return ns_key
ns_alias = self.namespaces.getAlias(namespace)
# No alias is defined, so no key can exist
if ns_alias is None:
return None
if ns_alias == NULL_NAMESPACE:
tail = ns_key
else:
tail = '%s.%s' % (ns_alias, ns_key)
return 'openid.' + tail
|
python
|
def getKey(self, namespace, ns_key):
"""Get the key for a particular namespaced argument"""
namespace = self._fixNS(namespace)
if namespace == BARE_NS:
return ns_key
ns_alias = self.namespaces.getAlias(namespace)
# No alias is defined, so no key can exist
if ns_alias is None:
return None
if ns_alias == NULL_NAMESPACE:
tail = ns_key
else:
tail = '%s.%s' % (ns_alias, ns_key)
return 'openid.' + tail
|
[
"def",
"getKey",
"(",
"self",
",",
"namespace",
",",
"ns_key",
")",
":",
"namespace",
"=",
"self",
".",
"_fixNS",
"(",
"namespace",
")",
"if",
"namespace",
"==",
"BARE_NS",
":",
"return",
"ns_key",
"ns_alias",
"=",
"self",
".",
"namespaces",
".",
"getAlias",
"(",
"namespace",
")",
"# No alias is defined, so no key can exist",
"if",
"ns_alias",
"is",
"None",
":",
"return",
"None",
"if",
"ns_alias",
"==",
"NULL_NAMESPACE",
":",
"tail",
"=",
"ns_key",
"else",
":",
"tail",
"=",
"'%s.%s'",
"%",
"(",
"ns_alias",
",",
"ns_key",
")",
"return",
"'openid.'",
"+",
"tail"
] |
Get the key for a particular namespaced argument
|
[
"Get",
"the",
"key",
"for",
"a",
"particular",
"namespaced",
"argument"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/message.py#L402-L419
|
16,518
|
openid/python-openid
|
openid/message.py
|
Message.getArg
|
def getArg(self, namespace, key, default=None):
"""Get a value for a namespaced key.
@param namespace: The namespace in the message for this key
@type namespace: str
@param key: The key to get within this namespace
@type key: str
@param default: The value to use if this key is absent from
this message. Using the special value
openid.message.no_default will result in this method
raising a KeyError instead of returning the default.
@rtype: str or the type of default
@raises KeyError: if default is no_default
@raises UndefinedOpenIDNamespace: if the message has not yet
had an OpenID namespace set
"""
namespace = self._fixNS(namespace)
args_key = (namespace, key)
try:
return self.args[args_key]
except KeyError:
if default is no_default:
raise KeyError((namespace, key))
else:
return default
|
python
|
def getArg(self, namespace, key, default=None):
"""Get a value for a namespaced key.
@param namespace: The namespace in the message for this key
@type namespace: str
@param key: The key to get within this namespace
@type key: str
@param default: The value to use if this key is absent from
this message. Using the special value
openid.message.no_default will result in this method
raising a KeyError instead of returning the default.
@rtype: str or the type of default
@raises KeyError: if default is no_default
@raises UndefinedOpenIDNamespace: if the message has not yet
had an OpenID namespace set
"""
namespace = self._fixNS(namespace)
args_key = (namespace, key)
try:
return self.args[args_key]
except KeyError:
if default is no_default:
raise KeyError((namespace, key))
else:
return default
|
[
"def",
"getArg",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"namespace",
"=",
"self",
".",
"_fixNS",
"(",
"namespace",
")",
"args_key",
"=",
"(",
"namespace",
",",
"key",
")",
"try",
":",
"return",
"self",
".",
"args",
"[",
"args_key",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"no_default",
":",
"raise",
"KeyError",
"(",
"(",
"namespace",
",",
"key",
")",
")",
"else",
":",
"return",
"default"
] |
Get a value for a namespaced key.
@param namespace: The namespace in the message for this key
@type namespace: str
@param key: The key to get within this namespace
@type key: str
@param default: The value to use if this key is absent from
this message. Using the special value
openid.message.no_default will result in this method
raising a KeyError instead of returning the default.
@rtype: str or the type of default
@raises KeyError: if default is no_default
@raises UndefinedOpenIDNamespace: if the message has not yet
had an OpenID namespace set
|
[
"Get",
"a",
"value",
"for",
"a",
"namespaced",
"key",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/message.py#L421-L448
|
16,519
|
openid/python-openid
|
openid/message.py
|
NamespaceMap.add
|
def add(self, namespace_uri):
"""Add this namespace URI to the mapping, without caring what
alias it ends up with"""
# See if this namespace is already mapped to an alias
alias = self.namespace_to_alias.get(namespace_uri)
if alias is not None:
return alias
# Fall back to generating a numerical alias
i = 0
while True:
alias = 'ext' + str(i)
try:
self.addAlias(namespace_uri, alias)
except KeyError:
i += 1
else:
return alias
assert False, "Not reached"
|
python
|
def add(self, namespace_uri):
"""Add this namespace URI to the mapping, without caring what
alias it ends up with"""
# See if this namespace is already mapped to an alias
alias = self.namespace_to_alias.get(namespace_uri)
if alias is not None:
return alias
# Fall back to generating a numerical alias
i = 0
while True:
alias = 'ext' + str(i)
try:
self.addAlias(namespace_uri, alias)
except KeyError:
i += 1
else:
return alias
assert False, "Not reached"
|
[
"def",
"add",
"(",
"self",
",",
"namespace_uri",
")",
":",
"# See if this namespace is already mapped to an alias",
"alias",
"=",
"self",
".",
"namespace_to_alias",
".",
"get",
"(",
"namespace_uri",
")",
"if",
"alias",
"is",
"not",
"None",
":",
"return",
"alias",
"# Fall back to generating a numerical alias",
"i",
"=",
"0",
"while",
"True",
":",
"alias",
"=",
"'ext'",
"+",
"str",
"(",
"i",
")",
"try",
":",
"self",
".",
"addAlias",
"(",
"namespace_uri",
",",
"alias",
")",
"except",
"KeyError",
":",
"i",
"+=",
"1",
"else",
":",
"return",
"alias",
"assert",
"False",
",",
"\"Not reached\""
] |
Add this namespace URI to the mapping, without caring what
alias it ends up with
|
[
"Add",
"this",
"namespace",
"URI",
"to",
"the",
"mapping",
"without",
"caring",
"what",
"alias",
"it",
"ends",
"up",
"with"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/message.py#L604-L623
|
16,520
|
openid/python-openid
|
openid/yadis/parsehtml.py
|
findHTMLMeta
|
def findHTMLMeta(stream):
"""Look for a meta http-equiv tag with the YADIS header name.
@param stream: Source of the html text
@type stream: Object that implements a read() method that works
like file.read
@return: The URI from which to fetch the XRDS document
@rtype: str
@raises MetaNotFound: raised with the content that was
searched as the first parameter.
"""
parser = YadisHTMLParser()
chunks = []
while 1:
chunk = stream.read(CHUNK_SIZE)
if not chunk:
# End of file
break
chunks.append(chunk)
try:
parser.feed(chunk)
except HTMLParseError, why:
# HTML parse error, so bail
chunks.append(stream.read())
break
except ParseDone, why:
uri = why[0]
if uri is None:
# Parse finished, but we may need the rest of the file
chunks.append(stream.read())
break
else:
return uri
content = ''.join(chunks)
raise MetaNotFound(content)
|
python
|
def findHTMLMeta(stream):
"""Look for a meta http-equiv tag with the YADIS header name.
@param stream: Source of the html text
@type stream: Object that implements a read() method that works
like file.read
@return: The URI from which to fetch the XRDS document
@rtype: str
@raises MetaNotFound: raised with the content that was
searched as the first parameter.
"""
parser = YadisHTMLParser()
chunks = []
while 1:
chunk = stream.read(CHUNK_SIZE)
if not chunk:
# End of file
break
chunks.append(chunk)
try:
parser.feed(chunk)
except HTMLParseError, why:
# HTML parse error, so bail
chunks.append(stream.read())
break
except ParseDone, why:
uri = why[0]
if uri is None:
# Parse finished, but we may need the rest of the file
chunks.append(stream.read())
break
else:
return uri
content = ''.join(chunks)
raise MetaNotFound(content)
|
[
"def",
"findHTMLMeta",
"(",
"stream",
")",
":",
"parser",
"=",
"YadisHTMLParser",
"(",
")",
"chunks",
"=",
"[",
"]",
"while",
"1",
":",
"chunk",
"=",
"stream",
".",
"read",
"(",
"CHUNK_SIZE",
")",
"if",
"not",
"chunk",
":",
"# End of file",
"break",
"chunks",
".",
"append",
"(",
"chunk",
")",
"try",
":",
"parser",
".",
"feed",
"(",
"chunk",
")",
"except",
"HTMLParseError",
",",
"why",
":",
"# HTML parse error, so bail",
"chunks",
".",
"append",
"(",
"stream",
".",
"read",
"(",
")",
")",
"break",
"except",
"ParseDone",
",",
"why",
":",
"uri",
"=",
"why",
"[",
"0",
"]",
"if",
"uri",
"is",
"None",
":",
"# Parse finished, but we may need the rest of the file",
"chunks",
".",
"append",
"(",
"stream",
".",
"read",
"(",
")",
")",
"break",
"else",
":",
"return",
"uri",
"content",
"=",
"''",
".",
"join",
"(",
"chunks",
")",
"raise",
"MetaNotFound",
"(",
"content",
")"
] |
Look for a meta http-equiv tag with the YADIS header name.
@param stream: Source of the html text
@type stream: Object that implements a read() method that works
like file.read
@return: The URI from which to fetch the XRDS document
@rtype: str
@raises MetaNotFound: raised with the content that was
searched as the first parameter.
|
[
"Look",
"for",
"a",
"meta",
"http",
"-",
"equiv",
"tag",
"with",
"the",
"YADIS",
"header",
"name",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/parsehtml.py#L158-L197
|
16,521
|
openid/python-openid
|
openid/extensions/ax.py
|
toTypeURIs
|
def toTypeURIs(namespace_map, alias_list_s):
"""Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.message.NamespaceMap
@param alias_list_s: The string containing the comma-separated
list of aliases. May also be None for convenience.
@type alias_list_s: str or NoneType
@returns: The list of namespace URIs that corresponds to the
supplied list of aliases. If the string was zero-length or
None, an empty list will be returned.
@raise KeyError: If an alias is present in the list of aliases but
is not present in the namespace map.
"""
uris = []
if alias_list_s:
for alias in alias_list_s.split(','):
type_uri = namespace_map.getNamespaceURI(alias)
if type_uri is None:
raise KeyError(
'No type is defined for attribute name %r' % (alias,))
else:
uris.append(type_uri)
return uris
|
python
|
def toTypeURIs(namespace_map, alias_list_s):
"""Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.message.NamespaceMap
@param alias_list_s: The string containing the comma-separated
list of aliases. May also be None for convenience.
@type alias_list_s: str or NoneType
@returns: The list of namespace URIs that corresponds to the
supplied list of aliases. If the string was zero-length or
None, an empty list will be returned.
@raise KeyError: If an alias is present in the list of aliases but
is not present in the namespace map.
"""
uris = []
if alias_list_s:
for alias in alias_list_s.split(','):
type_uri = namespace_map.getNamespaceURI(alias)
if type_uri is None:
raise KeyError(
'No type is defined for attribute name %r' % (alias,))
else:
uris.append(type_uri)
return uris
|
[
"def",
"toTypeURIs",
"(",
"namespace_map",
",",
"alias_list_s",
")",
":",
"uris",
"=",
"[",
"]",
"if",
"alias_list_s",
":",
"for",
"alias",
"in",
"alias_list_s",
".",
"split",
"(",
"','",
")",
":",
"type_uri",
"=",
"namespace_map",
".",
"getNamespaceURI",
"(",
"alias",
")",
"if",
"type_uri",
"is",
"None",
":",
"raise",
"KeyError",
"(",
"'No type is defined for attribute name %r'",
"%",
"(",
"alias",
",",
")",
")",
"else",
":",
"uris",
".",
"append",
"(",
"type_uri",
")",
"return",
"uris"
] |
Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.message.NamespaceMap
@param alias_list_s: The string containing the comma-separated
list of aliases. May also be None for convenience.
@type alias_list_s: str or NoneType
@returns: The list of namespace URIs that corresponds to the
supplied list of aliases. If the string was zero-length or
None, an empty list will be returned.
@raise KeyError: If an alias is present in the list of aliases but
is not present in the namespace map.
|
[
"Given",
"a",
"namespace",
"mapping",
"and",
"a",
"string",
"containing",
"a",
"comma",
"-",
"separated",
"list",
"of",
"namespace",
"aliases",
"return",
"a",
"list",
"of",
"type",
"URIs",
"that",
"correspond",
"to",
"those",
"aliases",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L149-L179
|
16,522
|
openid/python-openid
|
openid/extensions/ax.py
|
FetchRequest.add
|
def add(self, attribute):
"""Add an attribute to this attribute exchange request.
@param attribute: The attribute that is being requested
@type attribute: C{L{AttrInfo}}
@returns: None
@raise KeyError: when the requested attribute is already
present in this fetch request.
"""
if attribute.type_uri in self.requested_attributes:
raise KeyError('The attribute %r has already been requested'
% (attribute.type_uri,))
self.requested_attributes[attribute.type_uri] = attribute
|
python
|
def add(self, attribute):
"""Add an attribute to this attribute exchange request.
@param attribute: The attribute that is being requested
@type attribute: C{L{AttrInfo}}
@returns: None
@raise KeyError: when the requested attribute is already
present in this fetch request.
"""
if attribute.type_uri in self.requested_attributes:
raise KeyError('The attribute %r has already been requested'
% (attribute.type_uri,))
self.requested_attributes[attribute.type_uri] = attribute
|
[
"def",
"add",
"(",
"self",
",",
"attribute",
")",
":",
"if",
"attribute",
".",
"type_uri",
"in",
"self",
".",
"requested_attributes",
":",
"raise",
"KeyError",
"(",
"'The attribute %r has already been requested'",
"%",
"(",
"attribute",
".",
"type_uri",
",",
")",
")",
"self",
".",
"requested_attributes",
"[",
"attribute",
".",
"type_uri",
"]",
"=",
"attribute"
] |
Add an attribute to this attribute exchange request.
@param attribute: The attribute that is being requested
@type attribute: C{L{AttrInfo}}
@returns: None
@raise KeyError: when the requested attribute is already
present in this fetch request.
|
[
"Add",
"an",
"attribute",
"to",
"this",
"attribute",
"exchange",
"request",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L202-L217
|
16,523
|
openid/python-openid
|
openid/extensions/ax.py
|
AXKeyValueMessage.addValue
|
def addValue(self, type_uri, value):
"""Add a single value for the given attribute type to the
message. If there are already values specified for this type,
this value will be sent in addition to the values already
specified.
@param type_uri: The URI for the attribute
@param value: The value to add to the response to the relying
party for this attribute
@type value: unicode
@returns: None
"""
try:
values = self.data[type_uri]
except KeyError:
values = self.data[type_uri] = []
values.append(value)
|
python
|
def addValue(self, type_uri, value):
"""Add a single value for the given attribute type to the
message. If there are already values specified for this type,
this value will be sent in addition to the values already
specified.
@param type_uri: The URI for the attribute
@param value: The value to add to the response to the relying
party for this attribute
@type value: unicode
@returns: None
"""
try:
values = self.data[type_uri]
except KeyError:
values = self.data[type_uri] = []
values.append(value)
|
[
"def",
"addValue",
"(",
"self",
",",
"type_uri",
",",
"value",
")",
":",
"try",
":",
"values",
"=",
"self",
".",
"data",
"[",
"type_uri",
"]",
"except",
"KeyError",
":",
"values",
"=",
"self",
".",
"data",
"[",
"type_uri",
"]",
"=",
"[",
"]",
"values",
".",
"append",
"(",
"value",
")"
] |
Add a single value for the given attribute type to the
message. If there are already values specified for this type,
this value will be sent in addition to the values already
specified.
@param type_uri: The URI for the attribute
@param value: The value to add to the response to the relying
party for this attribute
@type value: unicode
@returns: None
|
[
"Add",
"a",
"single",
"value",
"for",
"the",
"given",
"attribute",
"type",
"to",
"the",
"message",
".",
"If",
"there",
"are",
"already",
"values",
"specified",
"for",
"this",
"type",
"this",
"value",
"will",
"be",
"sent",
"in",
"addition",
"to",
"the",
"values",
"already",
"specified",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L425-L444
|
16,524
|
openid/python-openid
|
openid/extensions/ax.py
|
AXKeyValueMessage.getSingle
|
def getSingle(self, type_uri, default=None):
"""Get a single value for an attribute. If no value was sent
for this attribute, use the supplied default. If there is more
than one value for this attribute, this method will fail.
@type type_uri: str
@param type_uri: The URI for the attribute
@param default: The value to return if the attribute was not
sent in the fetch_response.
@returns: The value of the attribute in the fetch_response
message, or the default supplied
@rtype: unicode or NoneType
@raises ValueError: If there is more than one value for this
parameter in the fetch_response message.
@raises KeyError: If the attribute was not sent in this response
"""
values = self.data.get(type_uri)
if not values:
return default
elif len(values) == 1:
return values[0]
else:
raise AXError(
'More than one value present for %r' % (type_uri,))
|
python
|
def getSingle(self, type_uri, default=None):
"""Get a single value for an attribute. If no value was sent
for this attribute, use the supplied default. If there is more
than one value for this attribute, this method will fail.
@type type_uri: str
@param type_uri: The URI for the attribute
@param default: The value to return if the attribute was not
sent in the fetch_response.
@returns: The value of the attribute in the fetch_response
message, or the default supplied
@rtype: unicode or NoneType
@raises ValueError: If there is more than one value for this
parameter in the fetch_response message.
@raises KeyError: If the attribute was not sent in this response
"""
values = self.data.get(type_uri)
if not values:
return default
elif len(values) == 1:
return values[0]
else:
raise AXError(
'More than one value present for %r' % (type_uri,))
|
[
"def",
"getSingle",
"(",
"self",
",",
"type_uri",
",",
"default",
"=",
"None",
")",
":",
"values",
"=",
"self",
".",
"data",
".",
"get",
"(",
"type_uri",
")",
"if",
"not",
"values",
":",
"return",
"default",
"elif",
"len",
"(",
"values",
")",
"==",
"1",
":",
"return",
"values",
"[",
"0",
"]",
"else",
":",
"raise",
"AXError",
"(",
"'More than one value present for %r'",
"%",
"(",
"type_uri",
",",
")",
")"
] |
Get a single value for an attribute. If no value was sent
for this attribute, use the supplied default. If there is more
than one value for this attribute, this method will fail.
@type type_uri: str
@param type_uri: The URI for the attribute
@param default: The value to return if the attribute was not
sent in the fetch_response.
@returns: The value of the attribute in the fetch_response
message, or the default supplied
@rtype: unicode or NoneType
@raises ValueError: If there is more than one value for this
parameter in the fetch_response message.
@raises KeyError: If the attribute was not sent in this response
|
[
"Get",
"a",
"single",
"value",
"for",
"an",
"attribute",
".",
"If",
"no",
"value",
"was",
"sent",
"for",
"this",
"attribute",
"use",
"the",
"supplied",
"default",
".",
"If",
"there",
"is",
"more",
"than",
"one",
"value",
"for",
"this",
"attribute",
"this",
"method",
"will",
"fail",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L529-L555
|
16,525
|
openid/python-openid
|
openid/extensions/ax.py
|
FetchResponse.getExtensionArgs
|
def getExtensionArgs(self):
"""Serialize this object into arguments in the attribute
exchange namespace
@returns: The dictionary of unqualified attribute exchange
arguments that represent this fetch_response.
@rtype: {unicode;unicode}
"""
aliases = NamespaceMap()
zero_value_types = []
if self.request is not None:
# Validate the data in the context of the request (the
# same attributes should be present in each, and the
# counts in the response must be no more than the counts
# in the request)
for type_uri in self.data:
if type_uri not in self.request:
raise KeyError(
'Response attribute not present in request: %r'
% (type_uri,))
for attr_info in self.request.iterAttrs():
# Copy the aliases from the request so that reading
# the response in light of the request is easier
if attr_info.alias is None:
aliases.add(attr_info.type_uri)
else:
aliases.addAlias(attr_info.type_uri, attr_info.alias)
try:
values = self.data[attr_info.type_uri]
except KeyError:
values = []
zero_value_types.append(attr_info)
if (attr_info.count != UNLIMITED_VALUES) and \
(attr_info.count < len(values)):
raise AXError(
'More than the number of requested values were '
'specified for %r' % (attr_info.type_uri,))
kv_args = self._getExtensionKVArgs(aliases)
# Add the KV args into the response with the args that are
# unique to the fetch_response
ax_args = self._newArgs()
# For each requested attribute, put its type/alias and count
# into the response even if no data were returned.
for attr_info in zero_value_types:
alias = aliases.getAlias(attr_info.type_uri)
kv_args['type.' + alias] = attr_info.type_uri
kv_args['count.' + alias] = '0'
update_url = ((self.request and self.request.update_url)
or self.update_url)
if update_url:
ax_args['update_url'] = update_url
ax_args.update(kv_args)
return ax_args
|
python
|
def getExtensionArgs(self):
"""Serialize this object into arguments in the attribute
exchange namespace
@returns: The dictionary of unqualified attribute exchange
arguments that represent this fetch_response.
@rtype: {unicode;unicode}
"""
aliases = NamespaceMap()
zero_value_types = []
if self.request is not None:
# Validate the data in the context of the request (the
# same attributes should be present in each, and the
# counts in the response must be no more than the counts
# in the request)
for type_uri in self.data:
if type_uri not in self.request:
raise KeyError(
'Response attribute not present in request: %r'
% (type_uri,))
for attr_info in self.request.iterAttrs():
# Copy the aliases from the request so that reading
# the response in light of the request is easier
if attr_info.alias is None:
aliases.add(attr_info.type_uri)
else:
aliases.addAlias(attr_info.type_uri, attr_info.alias)
try:
values = self.data[attr_info.type_uri]
except KeyError:
values = []
zero_value_types.append(attr_info)
if (attr_info.count != UNLIMITED_VALUES) and \
(attr_info.count < len(values)):
raise AXError(
'More than the number of requested values were '
'specified for %r' % (attr_info.type_uri,))
kv_args = self._getExtensionKVArgs(aliases)
# Add the KV args into the response with the args that are
# unique to the fetch_response
ax_args = self._newArgs()
# For each requested attribute, put its type/alias and count
# into the response even if no data were returned.
for attr_info in zero_value_types:
alias = aliases.getAlias(attr_info.type_uri)
kv_args['type.' + alias] = attr_info.type_uri
kv_args['count.' + alias] = '0'
update_url = ((self.request and self.request.update_url)
or self.update_url)
if update_url:
ax_args['update_url'] = update_url
ax_args.update(kv_args)
return ax_args
|
[
"def",
"getExtensionArgs",
"(",
"self",
")",
":",
"aliases",
"=",
"NamespaceMap",
"(",
")",
"zero_value_types",
"=",
"[",
"]",
"if",
"self",
".",
"request",
"is",
"not",
"None",
":",
"# Validate the data in the context of the request (the",
"# same attributes should be present in each, and the",
"# counts in the response must be no more than the counts",
"# in the request)",
"for",
"type_uri",
"in",
"self",
".",
"data",
":",
"if",
"type_uri",
"not",
"in",
"self",
".",
"request",
":",
"raise",
"KeyError",
"(",
"'Response attribute not present in request: %r'",
"%",
"(",
"type_uri",
",",
")",
")",
"for",
"attr_info",
"in",
"self",
".",
"request",
".",
"iterAttrs",
"(",
")",
":",
"# Copy the aliases from the request so that reading",
"# the response in light of the request is easier",
"if",
"attr_info",
".",
"alias",
"is",
"None",
":",
"aliases",
".",
"add",
"(",
"attr_info",
".",
"type_uri",
")",
"else",
":",
"aliases",
".",
"addAlias",
"(",
"attr_info",
".",
"type_uri",
",",
"attr_info",
".",
"alias",
")",
"try",
":",
"values",
"=",
"self",
".",
"data",
"[",
"attr_info",
".",
"type_uri",
"]",
"except",
"KeyError",
":",
"values",
"=",
"[",
"]",
"zero_value_types",
".",
"append",
"(",
"attr_info",
")",
"if",
"(",
"attr_info",
".",
"count",
"!=",
"UNLIMITED_VALUES",
")",
"and",
"(",
"attr_info",
".",
"count",
"<",
"len",
"(",
"values",
")",
")",
":",
"raise",
"AXError",
"(",
"'More than the number of requested values were '",
"'specified for %r'",
"%",
"(",
"attr_info",
".",
"type_uri",
",",
")",
")",
"kv_args",
"=",
"self",
".",
"_getExtensionKVArgs",
"(",
"aliases",
")",
"# Add the KV args into the response with the args that are",
"# unique to the fetch_response",
"ax_args",
"=",
"self",
".",
"_newArgs",
"(",
")",
"# For each requested attribute, put its type/alias and count",
"# into the response even if no data were returned.",
"for",
"attr_info",
"in",
"zero_value_types",
":",
"alias",
"=",
"aliases",
".",
"getAlias",
"(",
"attr_info",
".",
"type_uri",
")",
"kv_args",
"[",
"'type.'",
"+",
"alias",
"]",
"=",
"attr_info",
".",
"type_uri",
"kv_args",
"[",
"'count.'",
"+",
"alias",
"]",
"=",
"'0'",
"update_url",
"=",
"(",
"(",
"self",
".",
"request",
"and",
"self",
".",
"request",
".",
"update_url",
")",
"or",
"self",
".",
"update_url",
")",
"if",
"update_url",
":",
"ax_args",
"[",
"'update_url'",
"]",
"=",
"update_url",
"ax_args",
".",
"update",
"(",
"kv_args",
")",
"return",
"ax_args"
] |
Serialize this object into arguments in the attribute
exchange namespace
@returns: The dictionary of unqualified attribute exchange
arguments that represent this fetch_response.
@rtype: {unicode;unicode}
|
[
"Serialize",
"this",
"object",
"into",
"arguments",
"in",
"the",
"attribute",
"exchange",
"namespace"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L616-L682
|
16,526
|
openid/python-openid
|
openid/extensions/ax.py
|
FetchResponse.fromSuccessResponse
|
def fromSuccessResponse(cls, success_response, signed=True):
"""Construct a FetchResponse object from an OpenID library
SuccessResponse object.
@param success_response: A successful id_res response object
@type success_response: openid.consumer.consumer.SuccessResponse
@param signed: Whether non-signed args should be
processsed. If True (the default), only signed arguments
will be processsed.
@type signed: bool
@returns: A FetchResponse containing the data from the OpenID
message, or None if the SuccessResponse did not contain AX
extension data.
@raises AXError: when the AX data cannot be parsed.
"""
self = cls()
ax_args = success_response.extensionResponse(self.ns_uri, signed)
try:
self.parseExtensionArgs(ax_args)
except NotAXMessage, err:
return None
else:
return self
|
python
|
def fromSuccessResponse(cls, success_response, signed=True):
"""Construct a FetchResponse object from an OpenID library
SuccessResponse object.
@param success_response: A successful id_res response object
@type success_response: openid.consumer.consumer.SuccessResponse
@param signed: Whether non-signed args should be
processsed. If True (the default), only signed arguments
will be processsed.
@type signed: bool
@returns: A FetchResponse containing the data from the OpenID
message, or None if the SuccessResponse did not contain AX
extension data.
@raises AXError: when the AX data cannot be parsed.
"""
self = cls()
ax_args = success_response.extensionResponse(self.ns_uri, signed)
try:
self.parseExtensionArgs(ax_args)
except NotAXMessage, err:
return None
else:
return self
|
[
"def",
"fromSuccessResponse",
"(",
"cls",
",",
"success_response",
",",
"signed",
"=",
"True",
")",
":",
"self",
"=",
"cls",
"(",
")",
"ax_args",
"=",
"success_response",
".",
"extensionResponse",
"(",
"self",
".",
"ns_uri",
",",
"signed",
")",
"try",
":",
"self",
".",
"parseExtensionArgs",
"(",
"ax_args",
")",
"except",
"NotAXMessage",
",",
"err",
":",
"return",
"None",
"else",
":",
"return",
"self"
] |
Construct a FetchResponse object from an OpenID library
SuccessResponse object.
@param success_response: A successful id_res response object
@type success_response: openid.consumer.consumer.SuccessResponse
@param signed: Whether non-signed args should be
processsed. If True (the default), only signed arguments
will be processsed.
@type signed: bool
@returns: A FetchResponse containing the data from the OpenID
message, or None if the SuccessResponse did not contain AX
extension data.
@raises AXError: when the AX data cannot be parsed.
|
[
"Construct",
"a",
"FetchResponse",
"object",
"from",
"an",
"OpenID",
"library",
"SuccessResponse",
"object",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L689-L715
|
16,527
|
openid/python-openid
|
openid/extensions/sreg.py
|
SRegRequest.parseExtensionArgs
|
def parseExtensionArgs(self, args, strict=False):
"""Parse the unqualified simple registration request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized simple
registration request fields.
If you are extracting arguments from a standard OpenID
checkid_* request, you probably want to use C{L{fromOpenIDRequest}},
which will extract the sreg namespace and arguments from the
OpenID request. This method is intended for cases where the
OpenID server needs more control over how the arguments are
parsed than that method provides.
>>> args = message.getArgs(ns_uri)
>>> request.parseExtensionArgs(args)
@param args: The unqualified simple registration arguments
@type args: {str:str}
@param strict: Whether requests with fields that are not
defined in the simple registration specification should be
tolerated (and ignored)
@type strict: bool
@returns: None; updates this object
"""
for list_name in ['required', 'optional']:
required = (list_name == 'required')
items = args.get(list_name)
if items:
for field_name in items.split(','):
try:
self.requestField(field_name, required, strict)
except ValueError:
if strict:
raise
self.policy_url = args.get('policy_url')
|
python
|
def parseExtensionArgs(self, args, strict=False):
"""Parse the unqualified simple registration request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized simple
registration request fields.
If you are extracting arguments from a standard OpenID
checkid_* request, you probably want to use C{L{fromOpenIDRequest}},
which will extract the sreg namespace and arguments from the
OpenID request. This method is intended for cases where the
OpenID server needs more control over how the arguments are
parsed than that method provides.
>>> args = message.getArgs(ns_uri)
>>> request.parseExtensionArgs(args)
@param args: The unqualified simple registration arguments
@type args: {str:str}
@param strict: Whether requests with fields that are not
defined in the simple registration specification should be
tolerated (and ignored)
@type strict: bool
@returns: None; updates this object
"""
for list_name in ['required', 'optional']:
required = (list_name == 'required')
items = args.get(list_name)
if items:
for field_name in items.split(','):
try:
self.requestField(field_name, required, strict)
except ValueError:
if strict:
raise
self.policy_url = args.get('policy_url')
|
[
"def",
"parseExtensionArgs",
"(",
"self",
",",
"args",
",",
"strict",
"=",
"False",
")",
":",
"for",
"list_name",
"in",
"[",
"'required'",
",",
"'optional'",
"]",
":",
"required",
"=",
"(",
"list_name",
"==",
"'required'",
")",
"items",
"=",
"args",
".",
"get",
"(",
"list_name",
")",
"if",
"items",
":",
"for",
"field_name",
"in",
"items",
".",
"split",
"(",
"','",
")",
":",
"try",
":",
"self",
".",
"requestField",
"(",
"field_name",
",",
"required",
",",
"strict",
")",
"except",
"ValueError",
":",
"if",
"strict",
":",
"raise",
"self",
".",
"policy_url",
"=",
"args",
".",
"get",
"(",
"'policy_url'",
")"
] |
Parse the unqualified simple registration request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized simple
registration request fields.
If you are extracting arguments from a standard OpenID
checkid_* request, you probably want to use C{L{fromOpenIDRequest}},
which will extract the sreg namespace and arguments from the
OpenID request. This method is intended for cases where the
OpenID server needs more control over how the arguments are
parsed than that method provides.
>>> args = message.getArgs(ns_uri)
>>> request.parseExtensionArgs(args)
@param args: The unqualified simple registration arguments
@type args: {str:str}
@param strict: Whether requests with fields that are not
defined in the simple registration specification should be
tolerated (and ignored)
@type strict: bool
@returns: None; updates this object
|
[
"Parse",
"the",
"unqualified",
"simple",
"registration",
"request",
"parameters",
"and",
"add",
"them",
"to",
"this",
"object",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/sreg.py#L232-L271
|
16,528
|
openid/python-openid
|
openid/extensions/sreg.py
|
SRegRequest.requestField
|
def requestField(self, field_name, required=False, strict=False):
"""Request the specified field from the OpenID user
@param field_name: the unqualified simple registration field name
@type field_name: str
@param required: whether the given field should be presented
to the user as being a required to successfully complete
the request
@param strict: whether to raise an exception when a field is
added to a request more than once
@raise ValueError: when the field requested is not a simple
registration field or strict is set and the field was
requested more than once
"""
checkFieldName(field_name)
if strict:
if field_name in self.required or field_name in self.optional:
raise ValueError('That field has already been requested')
else:
if field_name in self.required:
return
if field_name in self.optional:
if required:
self.optional.remove(field_name)
else:
return
if required:
self.required.append(field_name)
else:
self.optional.append(field_name)
|
python
|
def requestField(self, field_name, required=False, strict=False):
"""Request the specified field from the OpenID user
@param field_name: the unqualified simple registration field name
@type field_name: str
@param required: whether the given field should be presented
to the user as being a required to successfully complete
the request
@param strict: whether to raise an exception when a field is
added to a request more than once
@raise ValueError: when the field requested is not a simple
registration field or strict is set and the field was
requested more than once
"""
checkFieldName(field_name)
if strict:
if field_name in self.required or field_name in self.optional:
raise ValueError('That field has already been requested')
else:
if field_name in self.required:
return
if field_name in self.optional:
if required:
self.optional.remove(field_name)
else:
return
if required:
self.required.append(field_name)
else:
self.optional.append(field_name)
|
[
"def",
"requestField",
"(",
"self",
",",
"field_name",
",",
"required",
"=",
"False",
",",
"strict",
"=",
"False",
")",
":",
"checkFieldName",
"(",
"field_name",
")",
"if",
"strict",
":",
"if",
"field_name",
"in",
"self",
".",
"required",
"or",
"field_name",
"in",
"self",
".",
"optional",
":",
"raise",
"ValueError",
"(",
"'That field has already been requested'",
")",
"else",
":",
"if",
"field_name",
"in",
"self",
".",
"required",
":",
"return",
"if",
"field_name",
"in",
"self",
".",
"optional",
":",
"if",
"required",
":",
"self",
".",
"optional",
".",
"remove",
"(",
"field_name",
")",
"else",
":",
"return",
"if",
"required",
":",
"self",
".",
"required",
".",
"append",
"(",
"field_name",
")",
"else",
":",
"self",
".",
"optional",
".",
"append",
"(",
"field_name",
")"
] |
Request the specified field from the OpenID user
@param field_name: the unqualified simple registration field name
@type field_name: str
@param required: whether the given field should be presented
to the user as being a required to successfully complete
the request
@param strict: whether to raise an exception when a field is
added to a request more than once
@raise ValueError: when the field requested is not a simple
registration field or strict is set and the field was
requested more than once
|
[
"Request",
"the",
"specified",
"field",
"from",
"the",
"OpenID",
"user"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/sreg.py#L293-L328
|
16,529
|
openid/python-openid
|
openid/extensions/sreg.py
|
SRegRequest.requestFields
|
def requestFields(self, field_names, required=False, strict=False):
"""Add the given list of fields to the request
@param field_names: The simple registration data fields to request
@type field_names: [str]
@param required: Whether these values should be presented to
the user as required
@param strict: whether to raise an exception when a field is
added to a request more than once
@raise ValueError: when a field requested is not a simple
registration field or strict is set and a field was
requested more than once
"""
if isinstance(field_names, basestring):
raise TypeError('Fields should be passed as a list of '
'strings (not %r)' % (type(field_names),))
for field_name in field_names:
self.requestField(field_name, required, strict=strict)
|
python
|
def requestFields(self, field_names, required=False, strict=False):
"""Add the given list of fields to the request
@param field_names: The simple registration data fields to request
@type field_names: [str]
@param required: Whether these values should be presented to
the user as required
@param strict: whether to raise an exception when a field is
added to a request more than once
@raise ValueError: when a field requested is not a simple
registration field or strict is set and a field was
requested more than once
"""
if isinstance(field_names, basestring):
raise TypeError('Fields should be passed as a list of '
'strings (not %r)' % (type(field_names),))
for field_name in field_names:
self.requestField(field_name, required, strict=strict)
|
[
"def",
"requestFields",
"(",
"self",
",",
"field_names",
",",
"required",
"=",
"False",
",",
"strict",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"field_names",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"'Fields should be passed as a list of '",
"'strings (not %r)'",
"%",
"(",
"type",
"(",
"field_names",
")",
",",
")",
")",
"for",
"field_name",
"in",
"field_names",
":",
"self",
".",
"requestField",
"(",
"field_name",
",",
"required",
",",
"strict",
"=",
"strict",
")"
] |
Add the given list of fields to the request
@param field_names: The simple registration data fields to request
@type field_names: [str]
@param required: Whether these values should be presented to
the user as required
@param strict: whether to raise an exception when a field is
added to a request more than once
@raise ValueError: when a field requested is not a simple
registration field or strict is set and a field was
requested more than once
|
[
"Add",
"the",
"given",
"list",
"of",
"fields",
"to",
"the",
"request"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/sreg.py#L330-L351
|
16,530
|
openid/python-openid
|
openid/extensions/sreg.py
|
SRegRequest.getExtensionArgs
|
def getExtensionArgs(self):
"""Get a dictionary of unqualified simple registration
arguments representing this request.
This method is essentially the inverse of
C{L{parseExtensionArgs}}. This method serializes the simple
registration request fields.
@rtype: {str:str}
"""
args = {}
if self.required:
args['required'] = ','.join(self.required)
if self.optional:
args['optional'] = ','.join(self.optional)
if self.policy_url:
args['policy_url'] = self.policy_url
return args
|
python
|
def getExtensionArgs(self):
"""Get a dictionary of unqualified simple registration
arguments representing this request.
This method is essentially the inverse of
C{L{parseExtensionArgs}}. This method serializes the simple
registration request fields.
@rtype: {str:str}
"""
args = {}
if self.required:
args['required'] = ','.join(self.required)
if self.optional:
args['optional'] = ','.join(self.optional)
if self.policy_url:
args['policy_url'] = self.policy_url
return args
|
[
"def",
"getExtensionArgs",
"(",
"self",
")",
":",
"args",
"=",
"{",
"}",
"if",
"self",
".",
"required",
":",
"args",
"[",
"'required'",
"]",
"=",
"','",
".",
"join",
"(",
"self",
".",
"required",
")",
"if",
"self",
".",
"optional",
":",
"args",
"[",
"'optional'",
"]",
"=",
"','",
".",
"join",
"(",
"self",
".",
"optional",
")",
"if",
"self",
".",
"policy_url",
":",
"args",
"[",
"'policy_url'",
"]",
"=",
"self",
".",
"policy_url",
"return",
"args"
] |
Get a dictionary of unqualified simple registration
arguments representing this request.
This method is essentially the inverse of
C{L{parseExtensionArgs}}. This method serializes the simple
registration request fields.
@rtype: {str:str}
|
[
"Get",
"a",
"dictionary",
"of",
"unqualified",
"simple",
"registration",
"arguments",
"representing",
"this",
"request",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/sreg.py#L353-L374
|
16,531
|
openid/python-openid
|
openid/extensions/sreg.py
|
SRegResponse.get
|
def get(self, field_name, default=None):
"""Like dict.get, except that it checks that the field name is
defined by the simple registration specification"""
checkFieldName(field_name)
return self.data.get(field_name, default)
|
python
|
def get(self, field_name, default=None):
"""Like dict.get, except that it checks that the field name is
defined by the simple registration specification"""
checkFieldName(field_name)
return self.data.get(field_name, default)
|
[
"def",
"get",
"(",
"self",
",",
"field_name",
",",
"default",
"=",
"None",
")",
":",
"checkFieldName",
"(",
"field_name",
")",
"return",
"self",
".",
"data",
".",
"get",
"(",
"field_name",
",",
"default",
")"
] |
Like dict.get, except that it checks that the field name is
defined by the simple registration specification
|
[
"Like",
"dict",
".",
"get",
"except",
"that",
"it",
"checks",
"that",
"the",
"field",
"name",
"is",
"defined",
"by",
"the",
"simple",
"registration",
"specification"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/sreg.py#L483-L487
|
16,532
|
openid/python-openid
|
openid/server/trustroot.py
|
returnToMatches
|
def returnToMatches(allowed_return_to_urls, return_to):
"""Is the return_to URL under one of the supplied allowed
return_to URLs?
@since: 2.1.0
"""
for allowed_return_to in allowed_return_to_urls:
# A return_to pattern works the same as a realm, except that
# it's not allowed to use a wildcard. We'll model this by
# parsing it as a realm, and not trying to match it if it has
# a wildcard.
return_realm = TrustRoot.parse(allowed_return_to)
if (# Parses as a trust root
return_realm is not None and
# Does not have a wildcard
not return_realm.wildcard and
# Matches the return_to that we passed in with it
return_realm.validateURL(return_to)
):
return True
# No URL in the list matched
return False
|
python
|
def returnToMatches(allowed_return_to_urls, return_to):
"""Is the return_to URL under one of the supplied allowed
return_to URLs?
@since: 2.1.0
"""
for allowed_return_to in allowed_return_to_urls:
# A return_to pattern works the same as a realm, except that
# it's not allowed to use a wildcard. We'll model this by
# parsing it as a realm, and not trying to match it if it has
# a wildcard.
return_realm = TrustRoot.parse(allowed_return_to)
if (# Parses as a trust root
return_realm is not None and
# Does not have a wildcard
not return_realm.wildcard and
# Matches the return_to that we passed in with it
return_realm.validateURL(return_to)
):
return True
# No URL in the list matched
return False
|
[
"def",
"returnToMatches",
"(",
"allowed_return_to_urls",
",",
"return_to",
")",
":",
"for",
"allowed_return_to",
"in",
"allowed_return_to_urls",
":",
"# A return_to pattern works the same as a realm, except that",
"# it's not allowed to use a wildcard. We'll model this by",
"# parsing it as a realm, and not trying to match it if it has",
"# a wildcard.",
"return_realm",
"=",
"TrustRoot",
".",
"parse",
"(",
"allowed_return_to",
")",
"if",
"(",
"# Parses as a trust root",
"return_realm",
"is",
"not",
"None",
"and",
"# Does not have a wildcard",
"not",
"return_realm",
".",
"wildcard",
"and",
"# Matches the return_to that we passed in with it",
"return_realm",
".",
"validateURL",
"(",
"return_to",
")",
")",
":",
"return",
"True",
"# No URL in the list matched",
"return",
"False"
] |
Is the return_to URL under one of the supplied allowed
return_to URLs?
@since: 2.1.0
|
[
"Is",
"the",
"return_to",
"URL",
"under",
"one",
"of",
"the",
"supplied",
"allowed",
"return_to",
"URLs?"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/trustroot.py#L381-L407
|
16,533
|
openid/python-openid
|
openid/server/trustroot.py
|
getAllowedReturnURLs
|
def getAllowedReturnURLs(relying_party_url):
"""Given a relying party discovery URL return a list of return_to URLs.
@since: 2.1.0
"""
(rp_url_after_redirects, return_to_urls) = services.getServiceEndpoints(
relying_party_url, _extractReturnURL)
if rp_url_after_redirects != relying_party_url:
# Verification caused a redirect
raise RealmVerificationRedirected(
relying_party_url, rp_url_after_redirects)
return return_to_urls
|
python
|
def getAllowedReturnURLs(relying_party_url):
"""Given a relying party discovery URL return a list of return_to URLs.
@since: 2.1.0
"""
(rp_url_after_redirects, return_to_urls) = services.getServiceEndpoints(
relying_party_url, _extractReturnURL)
if rp_url_after_redirects != relying_party_url:
# Verification caused a redirect
raise RealmVerificationRedirected(
relying_party_url, rp_url_after_redirects)
return return_to_urls
|
[
"def",
"getAllowedReturnURLs",
"(",
"relying_party_url",
")",
":",
"(",
"rp_url_after_redirects",
",",
"return_to_urls",
")",
"=",
"services",
".",
"getServiceEndpoints",
"(",
"relying_party_url",
",",
"_extractReturnURL",
")",
"if",
"rp_url_after_redirects",
"!=",
"relying_party_url",
":",
"# Verification caused a redirect",
"raise",
"RealmVerificationRedirected",
"(",
"relying_party_url",
",",
"rp_url_after_redirects",
")",
"return",
"return_to_urls"
] |
Given a relying party discovery URL return a list of return_to URLs.
@since: 2.1.0
|
[
"Given",
"a",
"relying",
"party",
"discovery",
"URL",
"return",
"a",
"list",
"of",
"return_to",
"URLs",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/trustroot.py#L409-L422
|
16,534
|
openid/python-openid
|
openid/server/trustroot.py
|
verifyReturnTo
|
def verifyReturnTo(realm_str, return_to, _vrfy=getAllowedReturnURLs):
"""Verify that a return_to URL is valid for the given realm.
This function builds a discovery URL, performs Yadis discovery on
it, makes sure that the URL does not redirect, parses out the
return_to URLs, and finally checks to see if the current return_to
URL matches the return_to.
@raises DiscoveryFailure: When Yadis discovery fails
@returns: True if the return_to URL is valid for the realm
@since: 2.1.0
"""
realm = TrustRoot.parse(realm_str)
if realm is None:
# The realm does not parse as a URL pattern
return False
try:
allowable_urls = _vrfy(realm.buildDiscoveryURL())
except RealmVerificationRedirected, err:
logging.exception(str(err))
return False
if returnToMatches(allowable_urls, return_to):
return True
else:
logging.error("Failed to validate return_to %r for realm %r, was not "
"in %s" % (return_to, realm_str, allowable_urls))
return False
|
python
|
def verifyReturnTo(realm_str, return_to, _vrfy=getAllowedReturnURLs):
"""Verify that a return_to URL is valid for the given realm.
This function builds a discovery URL, performs Yadis discovery on
it, makes sure that the URL does not redirect, parses out the
return_to URLs, and finally checks to see if the current return_to
URL matches the return_to.
@raises DiscoveryFailure: When Yadis discovery fails
@returns: True if the return_to URL is valid for the realm
@since: 2.1.0
"""
realm = TrustRoot.parse(realm_str)
if realm is None:
# The realm does not parse as a URL pattern
return False
try:
allowable_urls = _vrfy(realm.buildDiscoveryURL())
except RealmVerificationRedirected, err:
logging.exception(str(err))
return False
if returnToMatches(allowable_urls, return_to):
return True
else:
logging.error("Failed to validate return_to %r for realm %r, was not "
"in %s" % (return_to, realm_str, allowable_urls))
return False
|
[
"def",
"verifyReturnTo",
"(",
"realm_str",
",",
"return_to",
",",
"_vrfy",
"=",
"getAllowedReturnURLs",
")",
":",
"realm",
"=",
"TrustRoot",
".",
"parse",
"(",
"realm_str",
")",
"if",
"realm",
"is",
"None",
":",
"# The realm does not parse as a URL pattern",
"return",
"False",
"try",
":",
"allowable_urls",
"=",
"_vrfy",
"(",
"realm",
".",
"buildDiscoveryURL",
"(",
")",
")",
"except",
"RealmVerificationRedirected",
",",
"err",
":",
"logging",
".",
"exception",
"(",
"str",
"(",
"err",
")",
")",
"return",
"False",
"if",
"returnToMatches",
"(",
"allowable_urls",
",",
"return_to",
")",
":",
"return",
"True",
"else",
":",
"logging",
".",
"error",
"(",
"\"Failed to validate return_to %r for realm %r, was not \"",
"\"in %s\"",
"%",
"(",
"return_to",
",",
"realm_str",
",",
"allowable_urls",
")",
")",
"return",
"False"
] |
Verify that a return_to URL is valid for the given realm.
This function builds a discovery URL, performs Yadis discovery on
it, makes sure that the URL does not redirect, parses out the
return_to URLs, and finally checks to see if the current return_to
URL matches the return_to.
@raises DiscoveryFailure: When Yadis discovery fails
@returns: True if the return_to URL is valid for the realm
@since: 2.1.0
|
[
"Verify",
"that",
"a",
"return_to",
"URL",
"is",
"valid",
"for",
"the",
"given",
"realm",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/trustroot.py#L425-L454
|
16,535
|
openid/python-openid
|
openid/server/trustroot.py
|
TrustRoot.validateURL
|
def validateURL(self, url):
"""
Validates a URL against this trust root.
@param url: The URL to check
@type url: C{str}
@return: Whether the given URL is within this trust root.
@rtype: C{bool}
"""
url_parts = _parseURL(url)
if url_parts is None:
return False
proto, host, port, path = url_parts
if proto != self.proto:
return False
if port != self.port:
return False
if '*' in host:
return False
if not self.wildcard:
if host != self.host:
return False
elif ((not host.endswith(self.host)) and
('.' + host) != self.host):
return False
if path != self.path:
path_len = len(self.path)
trust_prefix = self.path[:path_len]
url_prefix = path[:path_len]
# must be equal up to the length of the path, at least
if trust_prefix != url_prefix:
return False
# These characters must be on the boundary between the end
# of the trust root's path and the start of the URL's
# path.
if '?' in self.path:
allowed = '&'
else:
allowed = '?/'
return (self.path[-1] in allowed or
path[path_len] in allowed)
return True
|
python
|
def validateURL(self, url):
"""
Validates a URL against this trust root.
@param url: The URL to check
@type url: C{str}
@return: Whether the given URL is within this trust root.
@rtype: C{bool}
"""
url_parts = _parseURL(url)
if url_parts is None:
return False
proto, host, port, path = url_parts
if proto != self.proto:
return False
if port != self.port:
return False
if '*' in host:
return False
if not self.wildcard:
if host != self.host:
return False
elif ((not host.endswith(self.host)) and
('.' + host) != self.host):
return False
if path != self.path:
path_len = len(self.path)
trust_prefix = self.path[:path_len]
url_prefix = path[:path_len]
# must be equal up to the length of the path, at least
if trust_prefix != url_prefix:
return False
# These characters must be on the boundary between the end
# of the trust root's path and the start of the URL's
# path.
if '?' in self.path:
allowed = '&'
else:
allowed = '?/'
return (self.path[-1] in allowed or
path[path_len] in allowed)
return True
|
[
"def",
"validateURL",
"(",
"self",
",",
"url",
")",
":",
"url_parts",
"=",
"_parseURL",
"(",
"url",
")",
"if",
"url_parts",
"is",
"None",
":",
"return",
"False",
"proto",
",",
"host",
",",
"port",
",",
"path",
"=",
"url_parts",
"if",
"proto",
"!=",
"self",
".",
"proto",
":",
"return",
"False",
"if",
"port",
"!=",
"self",
".",
"port",
":",
"return",
"False",
"if",
"'*'",
"in",
"host",
":",
"return",
"False",
"if",
"not",
"self",
".",
"wildcard",
":",
"if",
"host",
"!=",
"self",
".",
"host",
":",
"return",
"False",
"elif",
"(",
"(",
"not",
"host",
".",
"endswith",
"(",
"self",
".",
"host",
")",
")",
"and",
"(",
"'.'",
"+",
"host",
")",
"!=",
"self",
".",
"host",
")",
":",
"return",
"False",
"if",
"path",
"!=",
"self",
".",
"path",
":",
"path_len",
"=",
"len",
"(",
"self",
".",
"path",
")",
"trust_prefix",
"=",
"self",
".",
"path",
"[",
":",
"path_len",
"]",
"url_prefix",
"=",
"path",
"[",
":",
"path_len",
"]",
"# must be equal up to the length of the path, at least",
"if",
"trust_prefix",
"!=",
"url_prefix",
":",
"return",
"False",
"# These characters must be on the boundary between the end",
"# of the trust root's path and the start of the URL's",
"# path.",
"if",
"'?'",
"in",
"self",
".",
"path",
":",
"allowed",
"=",
"'&'",
"else",
":",
"allowed",
"=",
"'?/'",
"return",
"(",
"self",
".",
"path",
"[",
"-",
"1",
"]",
"in",
"allowed",
"or",
"path",
"[",
"path_len",
"]",
"in",
"allowed",
")",
"return",
"True"
] |
Validates a URL against this trust root.
@param url: The URL to check
@type url: C{str}
@return: Whether the given URL is within this trust root.
@rtype: C{bool}
|
[
"Validates",
"a",
"URL",
"against",
"this",
"trust",
"root",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/trustroot.py#L190-L247
|
16,536
|
openid/python-openid
|
openid/server/trustroot.py
|
TrustRoot.checkSanity
|
def checkSanity(cls, trust_root_string):
"""str -> bool
is this a sane trust root?
"""
trust_root = cls.parse(trust_root_string)
if trust_root is None:
return False
else:
return trust_root.isSane()
|
python
|
def checkSanity(cls, trust_root_string):
"""str -> bool
is this a sane trust root?
"""
trust_root = cls.parse(trust_root_string)
if trust_root is None:
return False
else:
return trust_root.isSane()
|
[
"def",
"checkSanity",
"(",
"cls",
",",
"trust_root_string",
")",
":",
"trust_root",
"=",
"cls",
".",
"parse",
"(",
"trust_root_string",
")",
"if",
"trust_root",
"is",
"None",
":",
"return",
"False",
"else",
":",
"return",
"trust_root",
".",
"isSane",
"(",
")"
] |
str -> bool
is this a sane trust root?
|
[
"str",
"-",
">",
"bool"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/trustroot.py#L303-L312
|
16,537
|
openid/python-openid
|
openid/server/trustroot.py
|
TrustRoot.checkURL
|
def checkURL(cls, trust_root, url):
"""quick func for validating a url against a trust root. See the
TrustRoot class if you need more control."""
tr = cls.parse(trust_root)
return tr is not None and tr.validateURL(url)
|
python
|
def checkURL(cls, trust_root, url):
"""quick func for validating a url against a trust root. See the
TrustRoot class if you need more control."""
tr = cls.parse(trust_root)
return tr is not None and tr.validateURL(url)
|
[
"def",
"checkURL",
"(",
"cls",
",",
"trust_root",
",",
"url",
")",
":",
"tr",
"=",
"cls",
".",
"parse",
"(",
"trust_root",
")",
"return",
"tr",
"is",
"not",
"None",
"and",
"tr",
".",
"validateURL",
"(",
"url",
")"
] |
quick func for validating a url against a trust root. See the
TrustRoot class if you need more control.
|
[
"quick",
"func",
"for",
"validating",
"a",
"url",
"against",
"a",
"trust",
"root",
".",
"See",
"the",
"TrustRoot",
"class",
"if",
"you",
"need",
"more",
"control",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/trustroot.py#L316-L320
|
16,538
|
openid/python-openid
|
openid/server/trustroot.py
|
TrustRoot.buildDiscoveryURL
|
def buildDiscoveryURL(self):
"""Return a discovery URL for this realm.
This function does not check to make sure that the realm is
valid. Its behaviour on invalid inputs is undefined.
@rtype: str
@returns: The URL upon which relying party discovery should be run
in order to verify the return_to URL
@since: 2.1.0
"""
if self.wildcard:
# Use "www." in place of the star
assert self.host.startswith('.'), self.host
www_domain = 'www' + self.host
return '%s://%s%s' % (self.proto, www_domain, self.path)
else:
return self.unparsed
|
python
|
def buildDiscoveryURL(self):
"""Return a discovery URL for this realm.
This function does not check to make sure that the realm is
valid. Its behaviour on invalid inputs is undefined.
@rtype: str
@returns: The URL upon which relying party discovery should be run
in order to verify the return_to URL
@since: 2.1.0
"""
if self.wildcard:
# Use "www." in place of the star
assert self.host.startswith('.'), self.host
www_domain = 'www' + self.host
return '%s://%s%s' % (self.proto, www_domain, self.path)
else:
return self.unparsed
|
[
"def",
"buildDiscoveryURL",
"(",
"self",
")",
":",
"if",
"self",
".",
"wildcard",
":",
"# Use \"www.\" in place of the star",
"assert",
"self",
".",
"host",
".",
"startswith",
"(",
"'.'",
")",
",",
"self",
".",
"host",
"www_domain",
"=",
"'www'",
"+",
"self",
".",
"host",
"return",
"'%s://%s%s'",
"%",
"(",
"self",
".",
"proto",
",",
"www_domain",
",",
"self",
".",
"path",
")",
"else",
":",
"return",
"self",
".",
"unparsed"
] |
Return a discovery URL for this realm.
This function does not check to make sure that the realm is
valid. Its behaviour on invalid inputs is undefined.
@rtype: str
@returns: The URL upon which relying party discovery should be run
in order to verify the return_to URL
@since: 2.1.0
|
[
"Return",
"a",
"discovery",
"URL",
"for",
"this",
"realm",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/trustroot.py#L324-L343
|
16,539
|
openid/python-openid
|
openid/yadis/manager.py
|
YadisServiceManager.next
|
def next(self):
"""Return the next service
self.current() will continue to return that service until the
next call to this method."""
try:
self._current = self.services.pop(0)
except IndexError:
raise StopIteration
else:
return self._current
|
python
|
def next(self):
"""Return the next service
self.current() will continue to return that service until the
next call to this method."""
try:
self._current = self.services.pop(0)
except IndexError:
raise StopIteration
else:
return self._current
|
[
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_current",
"=",
"self",
".",
"services",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"raise",
"StopIteration",
"else",
":",
"return",
"self",
".",
"_current"
] |
Return the next service
self.current() will continue to return that service until the
next call to this method.
|
[
"Return",
"the",
"next",
"service"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L27-L37
|
16,540
|
openid/python-openid
|
openid/yadis/manager.py
|
Discovery.getNextService
|
def getNextService(self, discover):
"""Return the next authentication service for the pair of
user_input and session. This function handles fallback.
@param discover: a callable that takes a URL and returns a
list of services
@type discover: str -> [service]
@return: the next available service
"""
manager = self.getManager()
if manager is not None and not manager:
self.destroyManager()
if not manager:
yadis_url, services = discover(self.url)
manager = self.createManager(services, yadis_url)
if manager:
service = manager.next()
manager.store(self.session)
else:
service = None
return service
|
python
|
def getNextService(self, discover):
"""Return the next authentication service for the pair of
user_input and session. This function handles fallback.
@param discover: a callable that takes a URL and returns a
list of services
@type discover: str -> [service]
@return: the next available service
"""
manager = self.getManager()
if manager is not None and not manager:
self.destroyManager()
if not manager:
yadis_url, services = discover(self.url)
manager = self.createManager(services, yadis_url)
if manager:
service = manager.next()
manager.store(self.session)
else:
service = None
return service
|
[
"def",
"getNextService",
"(",
"self",
",",
"discover",
")",
":",
"manager",
"=",
"self",
".",
"getManager",
"(",
")",
"if",
"manager",
"is",
"not",
"None",
"and",
"not",
"manager",
":",
"self",
".",
"destroyManager",
"(",
")",
"if",
"not",
"manager",
":",
"yadis_url",
",",
"services",
"=",
"discover",
"(",
"self",
".",
"url",
")",
"manager",
"=",
"self",
".",
"createManager",
"(",
"services",
",",
"yadis_url",
")",
"if",
"manager",
":",
"service",
"=",
"manager",
".",
"next",
"(",
")",
"manager",
".",
"store",
"(",
"self",
".",
"session",
")",
"else",
":",
"service",
"=",
"None",
"return",
"service"
] |
Return the next authentication service for the pair of
user_input and session. This function handles fallback.
@param discover: a callable that takes a URL and returns a
list of services
@type discover: str -> [service]
@return: the next available service
|
[
"Return",
"the",
"next",
"authentication",
"service",
"for",
"the",
"pair",
"of",
"user_input",
"and",
"session",
".",
"This",
"function",
"handles",
"fallback",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L87-L114
|
16,541
|
openid/python-openid
|
openid/yadis/manager.py
|
Discovery.cleanup
|
def cleanup(self, force=False):
"""Clean up Yadis-related services in the session and return
the most-recently-attempted service from the manager, if one
exists.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
@return: current service endpoint object or None if there is
no current service
"""
manager = self.getManager(force=force)
if manager is not None:
service = manager.current()
self.destroyManager(force=force)
else:
service = None
return service
|
python
|
def cleanup(self, force=False):
"""Clean up Yadis-related services in the session and return
the most-recently-attempted service from the manager, if one
exists.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
@return: current service endpoint object or None if there is
no current service
"""
manager = self.getManager(force=force)
if manager is not None:
service = manager.current()
self.destroyManager(force=force)
else:
service = None
return service
|
[
"def",
"cleanup",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"manager",
"=",
"self",
".",
"getManager",
"(",
"force",
"=",
"force",
")",
"if",
"manager",
"is",
"not",
"None",
":",
"service",
"=",
"manager",
".",
"current",
"(",
")",
"self",
".",
"destroyManager",
"(",
"force",
"=",
"force",
")",
"else",
":",
"service",
"=",
"None",
"return",
"service"
] |
Clean up Yadis-related services in the session and return
the most-recently-attempted service from the manager, if one
exists.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
@return: current service endpoint object or None if there is
no current service
|
[
"Clean",
"up",
"Yadis",
"-",
"related",
"services",
"in",
"the",
"session",
"and",
"return",
"the",
"most",
"-",
"recently",
"-",
"attempted",
"service",
"from",
"the",
"manager",
"if",
"one",
"exists",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L116-L134
|
16,542
|
openid/python-openid
|
openid/yadis/manager.py
|
Discovery.getManager
|
def getManager(self, force=False):
"""Extract the YadisServiceManager for this object's URL and
suffix from the session.
@param force: True if the manager should be returned
regardless of whether it's a manager for self.url.
@return: The current YadisServiceManager, if it's for this
URL, or else None
"""
manager = self.session.get(self.getSessionKey())
if (manager is not None and (manager.forURL(self.url) or force)):
return manager
else:
return None
|
python
|
def getManager(self, force=False):
"""Extract the YadisServiceManager for this object's URL and
suffix from the session.
@param force: True if the manager should be returned
regardless of whether it's a manager for self.url.
@return: The current YadisServiceManager, if it's for this
URL, or else None
"""
manager = self.session.get(self.getSessionKey())
if (manager is not None and (manager.forURL(self.url) or force)):
return manager
else:
return None
|
[
"def",
"getManager",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"manager",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"getSessionKey",
"(",
")",
")",
"if",
"(",
"manager",
"is",
"not",
"None",
"and",
"(",
"manager",
".",
"forURL",
"(",
"self",
".",
"url",
")",
"or",
"force",
")",
")",
":",
"return",
"manager",
"else",
":",
"return",
"None"
] |
Extract the YadisServiceManager for this object's URL and
suffix from the session.
@param force: True if the manager should be returned
regardless of whether it's a manager for self.url.
@return: The current YadisServiceManager, if it's for this
URL, or else None
|
[
"Extract",
"the",
"YadisServiceManager",
"for",
"this",
"object",
"s",
"URL",
"and",
"suffix",
"from",
"the",
"session",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L146-L160
|
16,543
|
openid/python-openid
|
openid/yadis/manager.py
|
Discovery.createManager
|
def createManager(self, services, yadis_url=None):
"""Create a new YadisService Manager for this starting URL and
suffix, and store it in the session.
@raises KeyError: When I already have a manager.
@return: A new YadisServiceManager or None
"""
key = self.getSessionKey()
if self.getManager():
raise KeyError('There is already a %r manager for %r' %
(key, self.url))
if not services:
return None
manager = YadisServiceManager(self.url, yadis_url, services, key)
manager.store(self.session)
return manager
|
python
|
def createManager(self, services, yadis_url=None):
"""Create a new YadisService Manager for this starting URL and
suffix, and store it in the session.
@raises KeyError: When I already have a manager.
@return: A new YadisServiceManager or None
"""
key = self.getSessionKey()
if self.getManager():
raise KeyError('There is already a %r manager for %r' %
(key, self.url))
if not services:
return None
manager = YadisServiceManager(self.url, yadis_url, services, key)
manager.store(self.session)
return manager
|
[
"def",
"createManager",
"(",
"self",
",",
"services",
",",
"yadis_url",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"getSessionKey",
"(",
")",
"if",
"self",
".",
"getManager",
"(",
")",
":",
"raise",
"KeyError",
"(",
"'There is already a %r manager for %r'",
"%",
"(",
"key",
",",
"self",
".",
"url",
")",
")",
"if",
"not",
"services",
":",
"return",
"None",
"manager",
"=",
"YadisServiceManager",
"(",
"self",
".",
"url",
",",
"yadis_url",
",",
"services",
",",
"key",
")",
"manager",
".",
"store",
"(",
"self",
".",
"session",
")",
"return",
"manager"
] |
Create a new YadisService Manager for this starting URL and
suffix, and store it in the session.
@raises KeyError: When I already have a manager.
@return: A new YadisServiceManager or None
|
[
"Create",
"a",
"new",
"YadisService",
"Manager",
"for",
"this",
"starting",
"URL",
"and",
"suffix",
"and",
"store",
"it",
"in",
"the",
"session",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L162-L180
|
16,544
|
openid/python-openid
|
openid/yadis/manager.py
|
Discovery.destroyManager
|
def destroyManager(self, force=False):
"""Delete any YadisServiceManager with this starting URL and
suffix from the session.
If there is no service manager or the service manager is for a
different URL, it silently does nothing.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
"""
if self.getManager(force=force) is not None:
key = self.getSessionKey()
del self.session[key]
|
python
|
def destroyManager(self, force=False):
"""Delete any YadisServiceManager with this starting URL and
suffix from the session.
If there is no service manager or the service manager is for a
different URL, it silently does nothing.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
"""
if self.getManager(force=force) is not None:
key = self.getSessionKey()
del self.session[key]
|
[
"def",
"destroyManager",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"getManager",
"(",
"force",
"=",
"force",
")",
"is",
"not",
"None",
":",
"key",
"=",
"self",
".",
"getSessionKey",
"(",
")",
"del",
"self",
".",
"session",
"[",
"key",
"]"
] |
Delete any YadisServiceManager with this starting URL and
suffix from the session.
If there is no service manager or the service manager is for a
different URL, it silently does nothing.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
|
[
"Delete",
"any",
"YadisServiceManager",
"with",
"this",
"starting",
"URL",
"and",
"suffix",
"from",
"the",
"session",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L182-L194
|
16,545
|
openid/python-openid
|
openid/dh.py
|
DiffieHellman._setPrivate
|
def _setPrivate(self, private):
"""This is here to make testing easier"""
self.private = private
self.public = pow(self.generator, self.private, self.modulus)
|
python
|
def _setPrivate(self, private):
"""This is here to make testing easier"""
self.private = private
self.public = pow(self.generator, self.private, self.modulus)
|
[
"def",
"_setPrivate",
"(",
"self",
",",
"private",
")",
":",
"self",
".",
"private",
"=",
"private",
"self",
".",
"public",
"=",
"pow",
"(",
"self",
".",
"generator",
",",
"self",
".",
"private",
",",
"self",
".",
"modulus",
")"
] |
This is here to make testing easier
|
[
"This",
"is",
"here",
"to",
"make",
"testing",
"easier"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/dh.py#L27-L30
|
16,546
|
openid/python-openid
|
openid/server/server.py
|
AssociateRequest.answerUnsupported
|
def answerUnsupported(self, message, preferred_association_type=None,
preferred_session_type=None):
"""Respond to this request indicating that the association
type or association session type is not supported."""
if self.message.isOpenID1():
raise ProtocolError(self.message)
response = OpenIDResponse(self)
response.fields.setArg(OPENID_NS, 'error_code', 'unsupported-type')
response.fields.setArg(OPENID_NS, 'error', message)
if preferred_association_type:
response.fields.setArg(
OPENID_NS, 'assoc_type', preferred_association_type)
if preferred_session_type:
response.fields.setArg(
OPENID_NS, 'session_type', preferred_session_type)
return response
|
python
|
def answerUnsupported(self, message, preferred_association_type=None,
preferred_session_type=None):
"""Respond to this request indicating that the association
type or association session type is not supported."""
if self.message.isOpenID1():
raise ProtocolError(self.message)
response = OpenIDResponse(self)
response.fields.setArg(OPENID_NS, 'error_code', 'unsupported-type')
response.fields.setArg(OPENID_NS, 'error', message)
if preferred_association_type:
response.fields.setArg(
OPENID_NS, 'assoc_type', preferred_association_type)
if preferred_session_type:
response.fields.setArg(
OPENID_NS, 'session_type', preferred_session_type)
return response
|
[
"def",
"answerUnsupported",
"(",
"self",
",",
"message",
",",
"preferred_association_type",
"=",
"None",
",",
"preferred_session_type",
"=",
"None",
")",
":",
"if",
"self",
".",
"message",
".",
"isOpenID1",
"(",
")",
":",
"raise",
"ProtocolError",
"(",
"self",
".",
"message",
")",
"response",
"=",
"OpenIDResponse",
"(",
"self",
")",
"response",
".",
"fields",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'error_code'",
",",
"'unsupported-type'",
")",
"response",
".",
"fields",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'error'",
",",
"message",
")",
"if",
"preferred_association_type",
":",
"response",
".",
"fields",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'assoc_type'",
",",
"preferred_association_type",
")",
"if",
"preferred_session_type",
":",
"response",
".",
"fields",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'session_type'",
",",
"preferred_session_type",
")",
"return",
"response"
] |
Respond to this request indicating that the association
type or association session type is not supported.
|
[
"Respond",
"to",
"this",
"request",
"indicating",
"that",
"the",
"association",
"type",
"or",
"association",
"session",
"type",
"is",
"not",
"supported",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L486-L505
|
16,547
|
openid/python-openid
|
openid/server/server.py
|
CheckIDRequest.fromMessage
|
def fromMessage(klass, message, op_endpoint):
"""Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When the C{return_to} URL is outside
the C{trust_root}.
@param message: An OpenID checkid_* request Message
@type message: openid.message.Message
@param op_endpoint: The endpoint URL of the server that this
message was sent to.
@type op_endpoint: str
@returntype: L{CheckIDRequest}
"""
self = klass.__new__(klass)
self.message = message
self.op_endpoint = op_endpoint
mode = message.getArg(OPENID_NS, 'mode')
if mode == "checkid_immediate":
self.immediate = True
self.mode = "checkid_immediate"
else:
self.immediate = False
self.mode = "checkid_setup"
self.return_to = message.getArg(OPENID_NS, 'return_to')
if message.isOpenID1() and not self.return_to:
fmt = "Missing required field 'return_to' from %r"
raise ProtocolError(message, text=fmt % (message,))
self.identity = message.getArg(OPENID_NS, 'identity')
self.claimed_id = message.getArg(OPENID_NS, 'claimed_id')
if message.isOpenID1():
if self.identity is None:
s = "OpenID 1 message did not contain openid.identity"
raise ProtocolError(message, text=s)
else:
if self.identity and not self.claimed_id:
s = ("OpenID 2.0 message contained openid.identity but not "
"claimed_id")
raise ProtocolError(message, text=s)
elif self.claimed_id and not self.identity:
s = ("OpenID 2.0 message contained openid.claimed_id but not "
"identity")
raise ProtocolError(message, text=s)
# There's a case for making self.trust_root be a TrustRoot
# here. But if TrustRoot isn't currently part of the "public" API,
# I'm not sure it's worth doing.
if message.isOpenID1():
trust_root_param = 'trust_root'
else:
trust_root_param = 'realm'
# Using 'or' here is slightly different than sending a default
# argument to getArg, as it will treat no value and an empty
# string as equivalent.
self.trust_root = (message.getArg(OPENID_NS, trust_root_param)
or self.return_to)
if not message.isOpenID1():
if self.return_to is self.trust_root is None:
raise ProtocolError(message, "openid.realm required when " +
"openid.return_to absent")
self.assoc_handle = message.getArg(OPENID_NS, 'assoc_handle')
# Using TrustRoot.parse here is a bit misleading, as we're not
# parsing return_to as a trust root at all. However, valid URLs
# are valid trust roots, so we can use this to get an idea if it
# is a valid URL. Not all trust roots are valid return_to URLs,
# however (particularly ones with wildcards), so this is still a
# little sketchy.
if self.return_to is not None and \
not TrustRoot.parse(self.return_to):
raise MalformedReturnURL(message, self.return_to)
# I first thought that checking to see if the return_to is within
# the trust_root is premature here, a logic-not-decoding thing. But
# it was argued that this is really part of data validation. A
# request with an invalid trust_root/return_to is broken regardless of
# application, right?
if not self.trustRootValid():
raise UntrustedReturnURL(message, self.return_to, self.trust_root)
return self
|
python
|
def fromMessage(klass, message, op_endpoint):
"""Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When the C{return_to} URL is outside
the C{trust_root}.
@param message: An OpenID checkid_* request Message
@type message: openid.message.Message
@param op_endpoint: The endpoint URL of the server that this
message was sent to.
@type op_endpoint: str
@returntype: L{CheckIDRequest}
"""
self = klass.__new__(klass)
self.message = message
self.op_endpoint = op_endpoint
mode = message.getArg(OPENID_NS, 'mode')
if mode == "checkid_immediate":
self.immediate = True
self.mode = "checkid_immediate"
else:
self.immediate = False
self.mode = "checkid_setup"
self.return_to = message.getArg(OPENID_NS, 'return_to')
if message.isOpenID1() and not self.return_to:
fmt = "Missing required field 'return_to' from %r"
raise ProtocolError(message, text=fmt % (message,))
self.identity = message.getArg(OPENID_NS, 'identity')
self.claimed_id = message.getArg(OPENID_NS, 'claimed_id')
if message.isOpenID1():
if self.identity is None:
s = "OpenID 1 message did not contain openid.identity"
raise ProtocolError(message, text=s)
else:
if self.identity and not self.claimed_id:
s = ("OpenID 2.0 message contained openid.identity but not "
"claimed_id")
raise ProtocolError(message, text=s)
elif self.claimed_id and not self.identity:
s = ("OpenID 2.0 message contained openid.claimed_id but not "
"identity")
raise ProtocolError(message, text=s)
# There's a case for making self.trust_root be a TrustRoot
# here. But if TrustRoot isn't currently part of the "public" API,
# I'm not sure it's worth doing.
if message.isOpenID1():
trust_root_param = 'trust_root'
else:
trust_root_param = 'realm'
# Using 'or' here is slightly different than sending a default
# argument to getArg, as it will treat no value and an empty
# string as equivalent.
self.trust_root = (message.getArg(OPENID_NS, trust_root_param)
or self.return_to)
if not message.isOpenID1():
if self.return_to is self.trust_root is None:
raise ProtocolError(message, "openid.realm required when " +
"openid.return_to absent")
self.assoc_handle = message.getArg(OPENID_NS, 'assoc_handle')
# Using TrustRoot.parse here is a bit misleading, as we're not
# parsing return_to as a trust root at all. However, valid URLs
# are valid trust roots, so we can use this to get an idea if it
# is a valid URL. Not all trust roots are valid return_to URLs,
# however (particularly ones with wildcards), so this is still a
# little sketchy.
if self.return_to is not None and \
not TrustRoot.parse(self.return_to):
raise MalformedReturnURL(message, self.return_to)
# I first thought that checking to see if the return_to is within
# the trust_root is premature here, a logic-not-decoding thing. But
# it was argued that this is really part of data validation. A
# request with an invalid trust_root/return_to is broken regardless of
# application, right?
if not self.trustRootValid():
raise UntrustedReturnURL(message, self.return_to, self.trust_root)
return self
|
[
"def",
"fromMessage",
"(",
"klass",
",",
"message",
",",
"op_endpoint",
")",
":",
"self",
"=",
"klass",
".",
"__new__",
"(",
"klass",
")",
"self",
".",
"message",
"=",
"message",
"self",
".",
"op_endpoint",
"=",
"op_endpoint",
"mode",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'mode'",
")",
"if",
"mode",
"==",
"\"checkid_immediate\"",
":",
"self",
".",
"immediate",
"=",
"True",
"self",
".",
"mode",
"=",
"\"checkid_immediate\"",
"else",
":",
"self",
".",
"immediate",
"=",
"False",
"self",
".",
"mode",
"=",
"\"checkid_setup\"",
"self",
".",
"return_to",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'return_to'",
")",
"if",
"message",
".",
"isOpenID1",
"(",
")",
"and",
"not",
"self",
".",
"return_to",
":",
"fmt",
"=",
"\"Missing required field 'return_to' from %r\"",
"raise",
"ProtocolError",
"(",
"message",
",",
"text",
"=",
"fmt",
"%",
"(",
"message",
",",
")",
")",
"self",
".",
"identity",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'identity'",
")",
"self",
".",
"claimed_id",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'claimed_id'",
")",
"if",
"message",
".",
"isOpenID1",
"(",
")",
":",
"if",
"self",
".",
"identity",
"is",
"None",
":",
"s",
"=",
"\"OpenID 1 message did not contain openid.identity\"",
"raise",
"ProtocolError",
"(",
"message",
",",
"text",
"=",
"s",
")",
"else",
":",
"if",
"self",
".",
"identity",
"and",
"not",
"self",
".",
"claimed_id",
":",
"s",
"=",
"(",
"\"OpenID 2.0 message contained openid.identity but not \"",
"\"claimed_id\"",
")",
"raise",
"ProtocolError",
"(",
"message",
",",
"text",
"=",
"s",
")",
"elif",
"self",
".",
"claimed_id",
"and",
"not",
"self",
".",
"identity",
":",
"s",
"=",
"(",
"\"OpenID 2.0 message contained openid.claimed_id but not \"",
"\"identity\"",
")",
"raise",
"ProtocolError",
"(",
"message",
",",
"text",
"=",
"s",
")",
"# There's a case for making self.trust_root be a TrustRoot",
"# here. But if TrustRoot isn't currently part of the \"public\" API,",
"# I'm not sure it's worth doing.",
"if",
"message",
".",
"isOpenID1",
"(",
")",
":",
"trust_root_param",
"=",
"'trust_root'",
"else",
":",
"trust_root_param",
"=",
"'realm'",
"# Using 'or' here is slightly different than sending a default",
"# argument to getArg, as it will treat no value and an empty",
"# string as equivalent.",
"self",
".",
"trust_root",
"=",
"(",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"trust_root_param",
")",
"or",
"self",
".",
"return_to",
")",
"if",
"not",
"message",
".",
"isOpenID1",
"(",
")",
":",
"if",
"self",
".",
"return_to",
"is",
"self",
".",
"trust_root",
"is",
"None",
":",
"raise",
"ProtocolError",
"(",
"message",
",",
"\"openid.realm required when \"",
"+",
"\"openid.return_to absent\"",
")",
"self",
".",
"assoc_handle",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'assoc_handle'",
")",
"# Using TrustRoot.parse here is a bit misleading, as we're not",
"# parsing return_to as a trust root at all. However, valid URLs",
"# are valid trust roots, so we can use this to get an idea if it",
"# is a valid URL. Not all trust roots are valid return_to URLs,",
"# however (particularly ones with wildcards), so this is still a",
"# little sketchy.",
"if",
"self",
".",
"return_to",
"is",
"not",
"None",
"and",
"not",
"TrustRoot",
".",
"parse",
"(",
"self",
".",
"return_to",
")",
":",
"raise",
"MalformedReturnURL",
"(",
"message",
",",
"self",
".",
"return_to",
")",
"# I first thought that checking to see if the return_to is within",
"# the trust_root is premature here, a logic-not-decoding thing. But",
"# it was argued that this is really part of data validation. A",
"# request with an invalid trust_root/return_to is broken regardless of",
"# application, right?",
"if",
"not",
"self",
".",
"trustRootValid",
"(",
")",
":",
"raise",
"UntrustedReturnURL",
"(",
"message",
",",
"self",
".",
"return_to",
",",
"self",
".",
"trust_root",
")",
"return",
"self"
] |
Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When the C{return_to} URL is outside
the C{trust_root}.
@param message: An OpenID checkid_* request Message
@type message: openid.message.Message
@param op_endpoint: The endpoint URL of the server that this
message was sent to.
@type op_endpoint: str
@returntype: L{CheckIDRequest}
|
[
"Construct",
"me",
"from",
"an",
"OpenID",
"message",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L580-L672
|
16,548
|
openid/python-openid
|
openid/server/server.py
|
CheckIDRequest.trustRootValid
|
def trustRootValid(self):
"""Is my return_to under my trust_root?
@returntype: bool
"""
if not self.trust_root:
return True
tr = TrustRoot.parse(self.trust_root)
if tr is None:
raise MalformedTrustRoot(self.message, self.trust_root)
if self.return_to is not None:
return tr.validateURL(self.return_to)
else:
return True
|
python
|
def trustRootValid(self):
"""Is my return_to under my trust_root?
@returntype: bool
"""
if not self.trust_root:
return True
tr = TrustRoot.parse(self.trust_root)
if tr is None:
raise MalformedTrustRoot(self.message, self.trust_root)
if self.return_to is not None:
return tr.validateURL(self.return_to)
else:
return True
|
[
"def",
"trustRootValid",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"trust_root",
":",
"return",
"True",
"tr",
"=",
"TrustRoot",
".",
"parse",
"(",
"self",
".",
"trust_root",
")",
"if",
"tr",
"is",
"None",
":",
"raise",
"MalformedTrustRoot",
"(",
"self",
".",
"message",
",",
"self",
".",
"trust_root",
")",
"if",
"self",
".",
"return_to",
"is",
"not",
"None",
":",
"return",
"tr",
".",
"validateURL",
"(",
"self",
".",
"return_to",
")",
"else",
":",
"return",
"True"
] |
Is my return_to under my trust_root?
@returntype: bool
|
[
"Is",
"my",
"return_to",
"under",
"my",
"trust_root?"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L684-L698
|
16,549
|
openid/python-openid
|
openid/server/server.py
|
CheckIDRequest.encodeToURL
|
def encodeToURL(self, server_url):
"""Encode this request as a URL to GET.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to.
"""
if not self.return_to:
raise NoReturnToError
# Imported from the alternate reality where these classes are used
# in both the client and server code, so Requests are Encodable too.
# That's right, code imported from alternate realities all for the
# love of you, id_res/user_setup_url.
q = {'mode': self.mode,
'identity': self.identity,
'claimed_id': self.claimed_id,
'return_to': self.return_to}
if self.trust_root:
if self.message.isOpenID1():
q['trust_root'] = self.trust_root
else:
q['realm'] = self.trust_root
if self.assoc_handle:
q['assoc_handle'] = self.assoc_handle
response = Message(self.message.getOpenIDNamespace())
response.updateArgs(OPENID_NS, q)
return response.toURL(server_url)
|
python
|
def encodeToURL(self, server_url):
"""Encode this request as a URL to GET.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to.
"""
if not self.return_to:
raise NoReturnToError
# Imported from the alternate reality where these classes are used
# in both the client and server code, so Requests are Encodable too.
# That's right, code imported from alternate realities all for the
# love of you, id_res/user_setup_url.
q = {'mode': self.mode,
'identity': self.identity,
'claimed_id': self.claimed_id,
'return_to': self.return_to}
if self.trust_root:
if self.message.isOpenID1():
q['trust_root'] = self.trust_root
else:
q['realm'] = self.trust_root
if self.assoc_handle:
q['assoc_handle'] = self.assoc_handle
response = Message(self.message.getOpenIDNamespace())
response.updateArgs(OPENID_NS, q)
return response.toURL(server_url)
|
[
"def",
"encodeToURL",
"(",
"self",
",",
"server_url",
")",
":",
"if",
"not",
"self",
".",
"return_to",
":",
"raise",
"NoReturnToError",
"# Imported from the alternate reality where these classes are used",
"# in both the client and server code, so Requests are Encodable too.",
"# That's right, code imported from alternate realities all for the",
"# love of you, id_res/user_setup_url.",
"q",
"=",
"{",
"'mode'",
":",
"self",
".",
"mode",
",",
"'identity'",
":",
"self",
".",
"identity",
",",
"'claimed_id'",
":",
"self",
".",
"claimed_id",
",",
"'return_to'",
":",
"self",
".",
"return_to",
"}",
"if",
"self",
".",
"trust_root",
":",
"if",
"self",
".",
"message",
".",
"isOpenID1",
"(",
")",
":",
"q",
"[",
"'trust_root'",
"]",
"=",
"self",
".",
"trust_root",
"else",
":",
"q",
"[",
"'realm'",
"]",
"=",
"self",
".",
"trust_root",
"if",
"self",
".",
"assoc_handle",
":",
"q",
"[",
"'assoc_handle'",
"]",
"=",
"self",
".",
"assoc_handle",
"response",
"=",
"Message",
"(",
"self",
".",
"message",
".",
"getOpenIDNamespace",
"(",
")",
")",
"response",
".",
"updateArgs",
"(",
"OPENID_NS",
",",
"q",
")",
"return",
"response",
".",
"toURL",
"(",
"server_url",
")"
] |
Encode this request as a URL to GET.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to.
|
[
"Encode",
"this",
"request",
"as",
"a",
"URL",
"to",
"GET",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L883-L914
|
16,550
|
openid/python-openid
|
openid/server/server.py
|
CheckIDRequest.getCancelURL
|
def getCancelURL(self):
"""Get the URL to cancel this request.
Useful for creating a "Cancel" button on a web form so that operation
can be carried out directly without another trip through the server.
(Except you probably want to make another trip through the server so
that it knows that the user did make a decision. Or you could simulate
this method by doing C{.answer(False).encodeToURL()})
@returntype: str
@returns: The return_to URL with openid.mode = cancel.
@raises NoReturnError: when I do not have a return_to.
"""
if not self.return_to:
raise NoReturnToError
if self.immediate:
raise ValueError("Cancel is not an appropriate response to "
"immediate mode requests.")
response = Message(self.message.getOpenIDNamespace())
response.setArg(OPENID_NS, 'mode', 'cancel')
return response.toURL(self.return_to)
|
python
|
def getCancelURL(self):
"""Get the URL to cancel this request.
Useful for creating a "Cancel" button on a web form so that operation
can be carried out directly without another trip through the server.
(Except you probably want to make another trip through the server so
that it knows that the user did make a decision. Or you could simulate
this method by doing C{.answer(False).encodeToURL()})
@returntype: str
@returns: The return_to URL with openid.mode = cancel.
@raises NoReturnError: when I do not have a return_to.
"""
if not self.return_to:
raise NoReturnToError
if self.immediate:
raise ValueError("Cancel is not an appropriate response to "
"immediate mode requests.")
response = Message(self.message.getOpenIDNamespace())
response.setArg(OPENID_NS, 'mode', 'cancel')
return response.toURL(self.return_to)
|
[
"def",
"getCancelURL",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"return_to",
":",
"raise",
"NoReturnToError",
"if",
"self",
".",
"immediate",
":",
"raise",
"ValueError",
"(",
"\"Cancel is not an appropriate response to \"",
"\"immediate mode requests.\"",
")",
"response",
"=",
"Message",
"(",
"self",
".",
"message",
".",
"getOpenIDNamespace",
"(",
")",
")",
"response",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'mode'",
",",
"'cancel'",
")",
"return",
"response",
".",
"toURL",
"(",
"self",
".",
"return_to",
")"
] |
Get the URL to cancel this request.
Useful for creating a "Cancel" button on a web form so that operation
can be carried out directly without another trip through the server.
(Except you probably want to make another trip through the server so
that it knows that the user did make a decision. Or you could simulate
this method by doing C{.answer(False).encodeToURL()})
@returntype: str
@returns: The return_to URL with openid.mode = cancel.
@raises NoReturnError: when I do not have a return_to.
|
[
"Get",
"the",
"URL",
"to",
"cancel",
"this",
"request",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L917-L941
|
16,551
|
openid/python-openid
|
openid/server/server.py
|
OpenIDResponse.toFormMarkup
|
def toFormMarkup(self, form_tag_attrs=None):
"""Returns the form markup for this response.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@returntype: str
@since: 2.1.0
"""
return self.fields.toFormMarkup(self.request.return_to,
form_tag_attrs=form_tag_attrs)
|
python
|
def toFormMarkup(self, form_tag_attrs=None):
"""Returns the form markup for this response.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@returntype: str
@since: 2.1.0
"""
return self.fields.toFormMarkup(self.request.return_to,
form_tag_attrs=form_tag_attrs)
|
[
"def",
"toFormMarkup",
"(",
"self",
",",
"form_tag_attrs",
"=",
"None",
")",
":",
"return",
"self",
".",
"fields",
".",
"toFormMarkup",
"(",
"self",
".",
"request",
".",
"return_to",
",",
"form_tag_attrs",
"=",
"form_tag_attrs",
")"
] |
Returns the form markup for this response.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@returntype: str
@since: 2.1.0
|
[
"Returns",
"the",
"form",
"markup",
"for",
"this",
"response",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L990-L1003
|
16,552
|
openid/python-openid
|
openid/server/server.py
|
Signatory.verify
|
def verify(self, assoc_handle, message):
"""Verify that the signature for some data is valid.
@param assoc_handle: The handle of the association used to sign the
data.
@type assoc_handle: str
@param message: The signed message to verify
@type message: openid.message.Message
@returns: C{True} if the signature is valid, C{False} if not.
@returntype: bool
"""
assoc = self.getAssociation(assoc_handle, dumb=True)
if not assoc:
logging.error("failed to get assoc with handle %r to verify "
"message %r"
% (assoc_handle, message))
return False
try:
valid = assoc.checkMessageSignature(message)
except ValueError, ex:
logging.exception("Error in verifying %s with %s: %s" % (message,
assoc,
ex))
return False
return valid
|
python
|
def verify(self, assoc_handle, message):
"""Verify that the signature for some data is valid.
@param assoc_handle: The handle of the association used to sign the
data.
@type assoc_handle: str
@param message: The signed message to verify
@type message: openid.message.Message
@returns: C{True} if the signature is valid, C{False} if not.
@returntype: bool
"""
assoc = self.getAssociation(assoc_handle, dumb=True)
if not assoc:
logging.error("failed to get assoc with handle %r to verify "
"message %r"
% (assoc_handle, message))
return False
try:
valid = assoc.checkMessageSignature(message)
except ValueError, ex:
logging.exception("Error in verifying %s with %s: %s" % (message,
assoc,
ex))
return False
return valid
|
[
"def",
"verify",
"(",
"self",
",",
"assoc_handle",
",",
"message",
")",
":",
"assoc",
"=",
"self",
".",
"getAssociation",
"(",
"assoc_handle",
",",
"dumb",
"=",
"True",
")",
"if",
"not",
"assoc",
":",
"logging",
".",
"error",
"(",
"\"failed to get assoc with handle %r to verify \"",
"\"message %r\"",
"%",
"(",
"assoc_handle",
",",
"message",
")",
")",
"return",
"False",
"try",
":",
"valid",
"=",
"assoc",
".",
"checkMessageSignature",
"(",
"message",
")",
"except",
"ValueError",
",",
"ex",
":",
"logging",
".",
"exception",
"(",
"\"Error in verifying %s with %s: %s\"",
"%",
"(",
"message",
",",
"assoc",
",",
"ex",
")",
")",
"return",
"False",
"return",
"valid"
] |
Verify that the signature for some data is valid.
@param assoc_handle: The handle of the association used to sign the
data.
@type assoc_handle: str
@param message: The signed message to verify
@type message: openid.message.Message
@returns: C{True} if the signature is valid, C{False} if not.
@returntype: bool
|
[
"Verify",
"that",
"the",
"signature",
"for",
"some",
"data",
"is",
"valid",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1159-L1186
|
16,553
|
openid/python-openid
|
openid/server/server.py
|
Signatory.sign
|
def sign(self, response):
"""Sign a response.
I take a L{OpenIDResponse}, create a signature for everything
in its L{signed<OpenIDResponse.signed>} list, and return a new
copy of the response object with that signature included.
@param response: A response to sign.
@type response: L{OpenIDResponse}
@returns: A signed copy of the response.
@returntype: L{OpenIDResponse}
"""
signed_response = deepcopy(response)
assoc_handle = response.request.assoc_handle
if assoc_handle:
# normal mode
# disabling expiration check because even if the association
# is expired, we still need to know some properties of the
# association so that we may preserve those properties when
# creating the fallback association.
assoc = self.getAssociation(assoc_handle, dumb=False,
checkExpiration=False)
if not assoc or assoc.expiresIn <= 0:
# fall back to dumb mode
signed_response.fields.setArg(
OPENID_NS, 'invalidate_handle', assoc_handle)
assoc_type = assoc and assoc.assoc_type or 'HMAC-SHA1'
if assoc and assoc.expiresIn <= 0:
# now do the clean-up that the disabled checkExpiration
# code didn't get to do.
self.invalidate(assoc_handle, dumb=False)
assoc = self.createAssociation(dumb=True, assoc_type=assoc_type)
else:
# dumb mode.
assoc = self.createAssociation(dumb=True)
try:
signed_response.fields = assoc.signMessage(signed_response.fields)
except kvform.KVFormError, err:
raise EncodingError(response, explanation=str(err))
return signed_response
|
python
|
def sign(self, response):
"""Sign a response.
I take a L{OpenIDResponse}, create a signature for everything
in its L{signed<OpenIDResponse.signed>} list, and return a new
copy of the response object with that signature included.
@param response: A response to sign.
@type response: L{OpenIDResponse}
@returns: A signed copy of the response.
@returntype: L{OpenIDResponse}
"""
signed_response = deepcopy(response)
assoc_handle = response.request.assoc_handle
if assoc_handle:
# normal mode
# disabling expiration check because even if the association
# is expired, we still need to know some properties of the
# association so that we may preserve those properties when
# creating the fallback association.
assoc = self.getAssociation(assoc_handle, dumb=False,
checkExpiration=False)
if not assoc or assoc.expiresIn <= 0:
# fall back to dumb mode
signed_response.fields.setArg(
OPENID_NS, 'invalidate_handle', assoc_handle)
assoc_type = assoc and assoc.assoc_type or 'HMAC-SHA1'
if assoc and assoc.expiresIn <= 0:
# now do the clean-up that the disabled checkExpiration
# code didn't get to do.
self.invalidate(assoc_handle, dumb=False)
assoc = self.createAssociation(dumb=True, assoc_type=assoc_type)
else:
# dumb mode.
assoc = self.createAssociation(dumb=True)
try:
signed_response.fields = assoc.signMessage(signed_response.fields)
except kvform.KVFormError, err:
raise EncodingError(response, explanation=str(err))
return signed_response
|
[
"def",
"sign",
"(",
"self",
",",
"response",
")",
":",
"signed_response",
"=",
"deepcopy",
"(",
"response",
")",
"assoc_handle",
"=",
"response",
".",
"request",
".",
"assoc_handle",
"if",
"assoc_handle",
":",
"# normal mode",
"# disabling expiration check because even if the association",
"# is expired, we still need to know some properties of the",
"# association so that we may preserve those properties when",
"# creating the fallback association.",
"assoc",
"=",
"self",
".",
"getAssociation",
"(",
"assoc_handle",
",",
"dumb",
"=",
"False",
",",
"checkExpiration",
"=",
"False",
")",
"if",
"not",
"assoc",
"or",
"assoc",
".",
"expiresIn",
"<=",
"0",
":",
"# fall back to dumb mode",
"signed_response",
".",
"fields",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'invalidate_handle'",
",",
"assoc_handle",
")",
"assoc_type",
"=",
"assoc",
"and",
"assoc",
".",
"assoc_type",
"or",
"'HMAC-SHA1'",
"if",
"assoc",
"and",
"assoc",
".",
"expiresIn",
"<=",
"0",
":",
"# now do the clean-up that the disabled checkExpiration",
"# code didn't get to do.",
"self",
".",
"invalidate",
"(",
"assoc_handle",
",",
"dumb",
"=",
"False",
")",
"assoc",
"=",
"self",
".",
"createAssociation",
"(",
"dumb",
"=",
"True",
",",
"assoc_type",
"=",
"assoc_type",
")",
"else",
":",
"# dumb mode.",
"assoc",
"=",
"self",
".",
"createAssociation",
"(",
"dumb",
"=",
"True",
")",
"try",
":",
"signed_response",
".",
"fields",
"=",
"assoc",
".",
"signMessage",
"(",
"signed_response",
".",
"fields",
")",
"except",
"kvform",
".",
"KVFormError",
",",
"err",
":",
"raise",
"EncodingError",
"(",
"response",
",",
"explanation",
"=",
"str",
"(",
"err",
")",
")",
"return",
"signed_response"
] |
Sign a response.
I take a L{OpenIDResponse}, create a signature for everything
in its L{signed<OpenIDResponse.signed>} list, and return a new
copy of the response object with that signature included.
@param response: A response to sign.
@type response: L{OpenIDResponse}
@returns: A signed copy of the response.
@returntype: L{OpenIDResponse}
|
[
"Sign",
"a",
"response",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1189-L1231
|
16,554
|
openid/python-openid
|
openid/server/server.py
|
Signatory.createAssociation
|
def createAssociation(self, dumb=True, assoc_type='HMAC-SHA1'):
"""Make a new association.
@param dumb: Is this association for a dumb-mode transaction?
@type dumb: bool
@param assoc_type: The type of association to create. Currently
there is only one type defined, C{HMAC-SHA1}.
@type assoc_type: str
@returns: the new association.
@returntype: L{openid.association.Association}
"""
secret = cryptutil.getBytes(getSecretSize(assoc_type))
uniq = oidutil.toBase64(cryptutil.getBytes(4))
handle = '{%s}{%x}{%s}' % (assoc_type, int(time.time()), uniq)
assoc = Association.fromExpiresIn(
self.SECRET_LIFETIME, handle, secret, assoc_type)
if dumb:
key = self._dumb_key
else:
key = self._normal_key
self.store.storeAssociation(key, assoc)
return assoc
|
python
|
def createAssociation(self, dumb=True, assoc_type='HMAC-SHA1'):
"""Make a new association.
@param dumb: Is this association for a dumb-mode transaction?
@type dumb: bool
@param assoc_type: The type of association to create. Currently
there is only one type defined, C{HMAC-SHA1}.
@type assoc_type: str
@returns: the new association.
@returntype: L{openid.association.Association}
"""
secret = cryptutil.getBytes(getSecretSize(assoc_type))
uniq = oidutil.toBase64(cryptutil.getBytes(4))
handle = '{%s}{%x}{%s}' % (assoc_type, int(time.time()), uniq)
assoc = Association.fromExpiresIn(
self.SECRET_LIFETIME, handle, secret, assoc_type)
if dumb:
key = self._dumb_key
else:
key = self._normal_key
self.store.storeAssociation(key, assoc)
return assoc
|
[
"def",
"createAssociation",
"(",
"self",
",",
"dumb",
"=",
"True",
",",
"assoc_type",
"=",
"'HMAC-SHA1'",
")",
":",
"secret",
"=",
"cryptutil",
".",
"getBytes",
"(",
"getSecretSize",
"(",
"assoc_type",
")",
")",
"uniq",
"=",
"oidutil",
".",
"toBase64",
"(",
"cryptutil",
".",
"getBytes",
"(",
"4",
")",
")",
"handle",
"=",
"'{%s}{%x}{%s}'",
"%",
"(",
"assoc_type",
",",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"uniq",
")",
"assoc",
"=",
"Association",
".",
"fromExpiresIn",
"(",
"self",
".",
"SECRET_LIFETIME",
",",
"handle",
",",
"secret",
",",
"assoc_type",
")",
"if",
"dumb",
":",
"key",
"=",
"self",
".",
"_dumb_key",
"else",
":",
"key",
"=",
"self",
".",
"_normal_key",
"self",
".",
"store",
".",
"storeAssociation",
"(",
"key",
",",
"assoc",
")",
"return",
"assoc"
] |
Make a new association.
@param dumb: Is this association for a dumb-mode transaction?
@type dumb: bool
@param assoc_type: The type of association to create. Currently
there is only one type defined, C{HMAC-SHA1}.
@type assoc_type: str
@returns: the new association.
@returntype: L{openid.association.Association}
|
[
"Make",
"a",
"new",
"association",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1234-L1259
|
16,555
|
openid/python-openid
|
openid/server/server.py
|
Signatory.getAssociation
|
def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
"""Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with that
handle was found.
@returntype: L{openid.association.Association}
"""
# Hmm. We've created an interface that deals almost entirely with
# assoc_handles. The only place outside the Signatory that uses this
# (and thus the only place that ever sees Association objects) is
# when creating a response to an association request, as it must have
# the association's secret.
if assoc_handle is None:
raise ValueError("assoc_handle must not be None")
if dumb:
key = self._dumb_key
else:
key = self._normal_key
assoc = self.store.getAssociation(key, assoc_handle)
if assoc is not None and assoc.expiresIn <= 0:
logging.info("requested %sdumb key %r is expired (by %s seconds)" %
((not dumb) and 'not-' or '',
assoc_handle, assoc.expiresIn))
if checkExpiration:
self.store.removeAssociation(key, assoc_handle)
assoc = None
return assoc
|
python
|
def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
"""Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with that
handle was found.
@returntype: L{openid.association.Association}
"""
# Hmm. We've created an interface that deals almost entirely with
# assoc_handles. The only place outside the Signatory that uses this
# (and thus the only place that ever sees Association objects) is
# when creating a response to an association request, as it must have
# the association's secret.
if assoc_handle is None:
raise ValueError("assoc_handle must not be None")
if dumb:
key = self._dumb_key
else:
key = self._normal_key
assoc = self.store.getAssociation(key, assoc_handle)
if assoc is not None and assoc.expiresIn <= 0:
logging.info("requested %sdumb key %r is expired (by %s seconds)" %
((not dumb) and 'not-' or '',
assoc_handle, assoc.expiresIn))
if checkExpiration:
self.store.removeAssociation(key, assoc_handle)
assoc = None
return assoc
|
[
"def",
"getAssociation",
"(",
"self",
",",
"assoc_handle",
",",
"dumb",
",",
"checkExpiration",
"=",
"True",
")",
":",
"# Hmm. We've created an interface that deals almost entirely with",
"# assoc_handles. The only place outside the Signatory that uses this",
"# (and thus the only place that ever sees Association objects) is",
"# when creating a response to an association request, as it must have",
"# the association's secret.",
"if",
"assoc_handle",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"assoc_handle must not be None\"",
")",
"if",
"dumb",
":",
"key",
"=",
"self",
".",
"_dumb_key",
"else",
":",
"key",
"=",
"self",
".",
"_normal_key",
"assoc",
"=",
"self",
".",
"store",
".",
"getAssociation",
"(",
"key",
",",
"assoc_handle",
")",
"if",
"assoc",
"is",
"not",
"None",
"and",
"assoc",
".",
"expiresIn",
"<=",
"0",
":",
"logging",
".",
"info",
"(",
"\"requested %sdumb key %r is expired (by %s seconds)\"",
"%",
"(",
"(",
"not",
"dumb",
")",
"and",
"'not-'",
"or",
"''",
",",
"assoc_handle",
",",
"assoc",
".",
"expiresIn",
")",
")",
"if",
"checkExpiration",
":",
"self",
".",
"store",
".",
"removeAssociation",
"(",
"key",
",",
"assoc_handle",
")",
"assoc",
"=",
"None",
"return",
"assoc"
] |
Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with that
handle was found.
@returntype: L{openid.association.Association}
|
[
"Get",
"the",
"association",
"with",
"the",
"specified",
"handle",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1262-L1295
|
16,556
|
openid/python-openid
|
openid/server/server.py
|
Signatory.invalidate
|
def invalidate(self, assoc_handle, dumb):
"""Invalidates the association with the given handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
"""
if dumb:
key = self._dumb_key
else:
key = self._normal_key
self.store.removeAssociation(key, assoc_handle)
|
python
|
def invalidate(self, assoc_handle, dumb):
"""Invalidates the association with the given handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
"""
if dumb:
key = self._dumb_key
else:
key = self._normal_key
self.store.removeAssociation(key, assoc_handle)
|
[
"def",
"invalidate",
"(",
"self",
",",
"assoc_handle",
",",
"dumb",
")",
":",
"if",
"dumb",
":",
"key",
"=",
"self",
".",
"_dumb_key",
"else",
":",
"key",
"=",
"self",
".",
"_normal_key",
"self",
".",
"store",
".",
"removeAssociation",
"(",
"key",
",",
"assoc_handle",
")"
] |
Invalidates the association with the given handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
|
[
"Invalidates",
"the",
"association",
"with",
"the",
"given",
"handle",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1298-L1310
|
16,557
|
openid/python-openid
|
openid/server/server.py
|
Decoder.defaultDecoder
|
def defaultDecoder(self, message, server):
"""Called to decode queries when no handler for that mode is found.
@raises ProtocolError: This implementation always raises
L{ProtocolError}.
"""
mode = message.getArg(OPENID_NS, 'mode')
fmt = "Unrecognized OpenID mode %r"
raise ProtocolError(message, text=fmt % (mode,))
|
python
|
def defaultDecoder(self, message, server):
"""Called to decode queries when no handler for that mode is found.
@raises ProtocolError: This implementation always raises
L{ProtocolError}.
"""
mode = message.getArg(OPENID_NS, 'mode')
fmt = "Unrecognized OpenID mode %r"
raise ProtocolError(message, text=fmt % (mode,))
|
[
"def",
"defaultDecoder",
"(",
"self",
",",
"message",
",",
"server",
")",
":",
"mode",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'mode'",
")",
"fmt",
"=",
"\"Unrecognized OpenID mode %r\"",
"raise",
"ProtocolError",
"(",
"message",
",",
"text",
"=",
"fmt",
"%",
"(",
"mode",
",",
")",
")"
] |
Called to decode queries when no handler for that mode is found.
@raises ProtocolError: This implementation always raises
L{ProtocolError}.
|
[
"Called",
"to",
"decode",
"queries",
"when",
"no",
"handler",
"for",
"that",
"mode",
"is",
"found",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1448-L1456
|
16,558
|
openid/python-openid
|
openid/server/server.py
|
ProtocolError.toMessage
|
def toMessage(self):
"""Generate a Message object for sending to the relying party,
after encoding.
"""
namespace = self.openid_message.getOpenIDNamespace()
reply = Message(namespace)
reply.setArg(OPENID_NS, 'mode', 'error')
reply.setArg(OPENID_NS, 'error', str(self))
if self.contact is not None:
reply.setArg(OPENID_NS, 'contact', str(self.contact))
if self.reference is not None:
reply.setArg(OPENID_NS, 'reference', str(self.reference))
return reply
|
python
|
def toMessage(self):
"""Generate a Message object for sending to the relying party,
after encoding.
"""
namespace = self.openid_message.getOpenIDNamespace()
reply = Message(namespace)
reply.setArg(OPENID_NS, 'mode', 'error')
reply.setArg(OPENID_NS, 'error', str(self))
if self.contact is not None:
reply.setArg(OPENID_NS, 'contact', str(self.contact))
if self.reference is not None:
reply.setArg(OPENID_NS, 'reference', str(self.reference))
return reply
|
[
"def",
"toMessage",
"(",
"self",
")",
":",
"namespace",
"=",
"self",
".",
"openid_message",
".",
"getOpenIDNamespace",
"(",
")",
"reply",
"=",
"Message",
"(",
"namespace",
")",
"reply",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'mode'",
",",
"'error'",
")",
"reply",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'error'",
",",
"str",
"(",
"self",
")",
")",
"if",
"self",
".",
"contact",
"is",
"not",
"None",
":",
"reply",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'contact'",
",",
"str",
"(",
"self",
".",
"contact",
")",
")",
"if",
"self",
".",
"reference",
"is",
"not",
"None",
":",
"reply",
".",
"setArg",
"(",
"OPENID_NS",
",",
"'reference'",
",",
"str",
"(",
"self",
".",
"reference",
")",
")",
"return",
"reply"
] |
Generate a Message object for sending to the relying party,
after encoding.
|
[
"Generate",
"a",
"Message",
"object",
"for",
"sending",
"to",
"the",
"relying",
"party",
"after",
"encoding",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1674-L1689
|
16,559
|
openid/python-openid
|
examples/djopenid/consumer/views.py
|
rpXRDS
|
def rpXRDS(request):
"""
Return a relying party verification XRDS document
"""
return util.renderXRDS(
request,
[RP_RETURN_TO_URL_TYPE],
[util.getViewURL(request, finishOpenID)])
|
python
|
def rpXRDS(request):
"""
Return a relying party verification XRDS document
"""
return util.renderXRDS(
request,
[RP_RETURN_TO_URL_TYPE],
[util.getViewURL(request, finishOpenID)])
|
[
"def",
"rpXRDS",
"(",
"request",
")",
":",
"return",
"util",
".",
"renderXRDS",
"(",
"request",
",",
"[",
"RP_RETURN_TO_URL_TYPE",
"]",
",",
"[",
"util",
".",
"getViewURL",
"(",
"request",
",",
"finishOpenID",
")",
"]",
")"
] |
Return a relying party verification XRDS document
|
[
"Return",
"a",
"relying",
"party",
"verification",
"XRDS",
"document"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/consumer/views.py#L213-L220
|
16,560
|
openid/python-openid
|
examples/consumer.py
|
OpenIDRequestHandler.getSession
|
def getSession(self):
"""Return the existing session or a new session"""
if self.session is not None:
return self.session
# Get value of cookie header that was sent
cookie_str = self.headers.get('Cookie')
if cookie_str:
cookie_obj = SimpleCookie(cookie_str)
sid_morsel = cookie_obj.get(self.SESSION_COOKIE_NAME, None)
if sid_morsel is not None:
sid = sid_morsel.value
else:
sid = None
else:
sid = None
# If a session id was not set, create a new one
if sid is None:
sid = randomString(16, '0123456789abcdef')
session = None
else:
session = self.server.sessions.get(sid)
# If no session exists for this session ID, create one
if session is None:
session = self.server.sessions[sid] = {}
session['id'] = sid
self.session = session
return session
|
python
|
def getSession(self):
"""Return the existing session or a new session"""
if self.session is not None:
return self.session
# Get value of cookie header that was sent
cookie_str = self.headers.get('Cookie')
if cookie_str:
cookie_obj = SimpleCookie(cookie_str)
sid_morsel = cookie_obj.get(self.SESSION_COOKIE_NAME, None)
if sid_morsel is not None:
sid = sid_morsel.value
else:
sid = None
else:
sid = None
# If a session id was not set, create a new one
if sid is None:
sid = randomString(16, '0123456789abcdef')
session = None
else:
session = self.server.sessions.get(sid)
# If no session exists for this session ID, create one
if session is None:
session = self.server.sessions[sid] = {}
session['id'] = sid
self.session = session
return session
|
[
"def",
"getSession",
"(",
"self",
")",
":",
"if",
"self",
".",
"session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"session",
"# Get value of cookie header that was sent",
"cookie_str",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'Cookie'",
")",
"if",
"cookie_str",
":",
"cookie_obj",
"=",
"SimpleCookie",
"(",
"cookie_str",
")",
"sid_morsel",
"=",
"cookie_obj",
".",
"get",
"(",
"self",
".",
"SESSION_COOKIE_NAME",
",",
"None",
")",
"if",
"sid_morsel",
"is",
"not",
"None",
":",
"sid",
"=",
"sid_morsel",
".",
"value",
"else",
":",
"sid",
"=",
"None",
"else",
":",
"sid",
"=",
"None",
"# If a session id was not set, create a new one",
"if",
"sid",
"is",
"None",
":",
"sid",
"=",
"randomString",
"(",
"16",
",",
"'0123456789abcdef'",
")",
"session",
"=",
"None",
"else",
":",
"session",
"=",
"self",
".",
"server",
".",
"sessions",
".",
"get",
"(",
"sid",
")",
"# If no session exists for this session ID, create one",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"self",
".",
"server",
".",
"sessions",
"[",
"sid",
"]",
"=",
"{",
"}",
"session",
"[",
"'id'",
"]",
"=",
"sid",
"self",
".",
"session",
"=",
"session",
"return",
"session"
] |
Return the existing session or a new session
|
[
"Return",
"the",
"existing",
"session",
"or",
"a",
"new",
"session"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L77-L107
|
16,561
|
openid/python-openid
|
examples/consumer.py
|
OpenIDRequestHandler.doProcess
|
def doProcess(self):
"""Handle the redirect from the OpenID server.
"""
oidconsumer = self.getConsumer()
# Ask the library to check the response that the server sent
# us. Status is a code indicating the response type. info is
# either None or a string containing more information about
# the return type.
url = 'http://'+self.headers.get('Host')+self.path
info = oidconsumer.complete(self.query, url)
sreg_resp = None
pape_resp = None
css_class = 'error'
display_identifier = info.getDisplayIdentifier()
if info.status == consumer.FAILURE and display_identifier:
# In the case of failure, if info is non-None, it is the
# URL that we were verifying. We include it in the error
# message to help the user figure out what happened.
fmt = "Verification of %s failed: %s"
message = fmt % (cgi.escape(display_identifier),
info.message)
elif info.status == consumer.SUCCESS:
# Success means that the transaction completed without
# error. If info is None, it means that the user cancelled
# the verification.
css_class = 'alert'
# This is a successful verification attempt. If this
# was a real application, we would do our login,
# comment posting, etc. here.
fmt = "You have successfully verified %s as your identity."
message = fmt % (cgi.escape(display_identifier),)
sreg_resp = sreg.SRegResponse.fromSuccessResponse(info)
pape_resp = pape.Response.fromSuccessResponse(info)
if info.endpoint.canonicalID:
# You should authorize i-name users by their canonicalID,
# rather than their more human-friendly identifiers. That
# way their account with you is not compromised if their
# i-name registration expires and is bought by someone else.
message += (" This is an i-name, and its persistent ID is %s"
% (cgi.escape(info.endpoint.canonicalID),))
elif info.status == consumer.CANCEL:
# cancelled
message = 'Verification cancelled'
elif info.status == consumer.SETUP_NEEDED:
if info.setup_url:
message = '<a href=%s>Setup needed</a>' % (
quoteattr(info.setup_url),)
else:
# This means auth didn't succeed, but you're welcome to try
# non-immediate mode.
message = 'Setup needed'
else:
# Either we don't understand the code or there is no
# openid_url included with the error. Give a generic
# failure message. The library should supply debug
# information in a log.
message = 'Verification failed.'
self.render(message, css_class, display_identifier,
sreg_data=sreg_resp, pape_data=pape_resp)
|
python
|
def doProcess(self):
"""Handle the redirect from the OpenID server.
"""
oidconsumer = self.getConsumer()
# Ask the library to check the response that the server sent
# us. Status is a code indicating the response type. info is
# either None or a string containing more information about
# the return type.
url = 'http://'+self.headers.get('Host')+self.path
info = oidconsumer.complete(self.query, url)
sreg_resp = None
pape_resp = None
css_class = 'error'
display_identifier = info.getDisplayIdentifier()
if info.status == consumer.FAILURE and display_identifier:
# In the case of failure, if info is non-None, it is the
# URL that we were verifying. We include it in the error
# message to help the user figure out what happened.
fmt = "Verification of %s failed: %s"
message = fmt % (cgi.escape(display_identifier),
info.message)
elif info.status == consumer.SUCCESS:
# Success means that the transaction completed without
# error. If info is None, it means that the user cancelled
# the verification.
css_class = 'alert'
# This is a successful verification attempt. If this
# was a real application, we would do our login,
# comment posting, etc. here.
fmt = "You have successfully verified %s as your identity."
message = fmt % (cgi.escape(display_identifier),)
sreg_resp = sreg.SRegResponse.fromSuccessResponse(info)
pape_resp = pape.Response.fromSuccessResponse(info)
if info.endpoint.canonicalID:
# You should authorize i-name users by their canonicalID,
# rather than their more human-friendly identifiers. That
# way their account with you is not compromised if their
# i-name registration expires and is bought by someone else.
message += (" This is an i-name, and its persistent ID is %s"
% (cgi.escape(info.endpoint.canonicalID),))
elif info.status == consumer.CANCEL:
# cancelled
message = 'Verification cancelled'
elif info.status == consumer.SETUP_NEEDED:
if info.setup_url:
message = '<a href=%s>Setup needed</a>' % (
quoteattr(info.setup_url),)
else:
# This means auth didn't succeed, but you're welcome to try
# non-immediate mode.
message = 'Setup needed'
else:
# Either we don't understand the code or there is no
# openid_url included with the error. Give a generic
# failure message. The library should supply debug
# information in a log.
message = 'Verification failed.'
self.render(message, css_class, display_identifier,
sreg_data=sreg_resp, pape_data=pape_resp)
|
[
"def",
"doProcess",
"(",
"self",
")",
":",
"oidconsumer",
"=",
"self",
".",
"getConsumer",
"(",
")",
"# Ask the library to check the response that the server sent",
"# us. Status is a code indicating the response type. info is",
"# either None or a string containing more information about",
"# the return type.",
"url",
"=",
"'http://'",
"+",
"self",
".",
"headers",
".",
"get",
"(",
"'Host'",
")",
"+",
"self",
".",
"path",
"info",
"=",
"oidconsumer",
".",
"complete",
"(",
"self",
".",
"query",
",",
"url",
")",
"sreg_resp",
"=",
"None",
"pape_resp",
"=",
"None",
"css_class",
"=",
"'error'",
"display_identifier",
"=",
"info",
".",
"getDisplayIdentifier",
"(",
")",
"if",
"info",
".",
"status",
"==",
"consumer",
".",
"FAILURE",
"and",
"display_identifier",
":",
"# In the case of failure, if info is non-None, it is the",
"# URL that we were verifying. We include it in the error",
"# message to help the user figure out what happened.",
"fmt",
"=",
"\"Verification of %s failed: %s\"",
"message",
"=",
"fmt",
"%",
"(",
"cgi",
".",
"escape",
"(",
"display_identifier",
")",
",",
"info",
".",
"message",
")",
"elif",
"info",
".",
"status",
"==",
"consumer",
".",
"SUCCESS",
":",
"# Success means that the transaction completed without",
"# error. If info is None, it means that the user cancelled",
"# the verification.",
"css_class",
"=",
"'alert'",
"# This is a successful verification attempt. If this",
"# was a real application, we would do our login,",
"# comment posting, etc. here.",
"fmt",
"=",
"\"You have successfully verified %s as your identity.\"",
"message",
"=",
"fmt",
"%",
"(",
"cgi",
".",
"escape",
"(",
"display_identifier",
")",
",",
")",
"sreg_resp",
"=",
"sreg",
".",
"SRegResponse",
".",
"fromSuccessResponse",
"(",
"info",
")",
"pape_resp",
"=",
"pape",
".",
"Response",
".",
"fromSuccessResponse",
"(",
"info",
")",
"if",
"info",
".",
"endpoint",
".",
"canonicalID",
":",
"# You should authorize i-name users by their canonicalID,",
"# rather than their more human-friendly identifiers. That",
"# way their account with you is not compromised if their",
"# i-name registration expires and is bought by someone else.",
"message",
"+=",
"(",
"\" This is an i-name, and its persistent ID is %s\"",
"%",
"(",
"cgi",
".",
"escape",
"(",
"info",
".",
"endpoint",
".",
"canonicalID",
")",
",",
")",
")",
"elif",
"info",
".",
"status",
"==",
"consumer",
".",
"CANCEL",
":",
"# cancelled",
"message",
"=",
"'Verification cancelled'",
"elif",
"info",
".",
"status",
"==",
"consumer",
".",
"SETUP_NEEDED",
":",
"if",
"info",
".",
"setup_url",
":",
"message",
"=",
"'<a href=%s>Setup needed</a>'",
"%",
"(",
"quoteattr",
"(",
"info",
".",
"setup_url",
")",
",",
")",
"else",
":",
"# This means auth didn't succeed, but you're welcome to try",
"# non-immediate mode.",
"message",
"=",
"'Setup needed'",
"else",
":",
"# Either we don't understand the code or there is no",
"# openid_url included with the error. Give a generic",
"# failure message. The library should supply debug",
"# information in a log.",
"message",
"=",
"'Verification failed.'",
"self",
".",
"render",
"(",
"message",
",",
"css_class",
",",
"display_identifier",
",",
"sreg_data",
"=",
"sreg_resp",
",",
"pape_data",
"=",
"pape_resp",
")"
] |
Handle the redirect from the OpenID server.
|
[
"Handle",
"the",
"redirect",
"from",
"the",
"OpenID",
"server",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L222-L285
|
16,562
|
openid/python-openid
|
examples/consumer.py
|
OpenIDRequestHandler.notFound
|
def notFound(self):
"""Render a page with a 404 return code and a message."""
fmt = 'The path <q>%s</q> was not understood by this server.'
msg = fmt % (self.path,)
openid_url = self.query.get('openid_identifier')
self.render(msg, 'error', openid_url, status=404)
|
python
|
def notFound(self):
"""Render a page with a 404 return code and a message."""
fmt = 'The path <q>%s</q> was not understood by this server.'
msg = fmt % (self.path,)
openid_url = self.query.get('openid_identifier')
self.render(msg, 'error', openid_url, status=404)
|
[
"def",
"notFound",
"(",
"self",
")",
":",
"fmt",
"=",
"'The path <q>%s</q> was not understood by this server.'",
"msg",
"=",
"fmt",
"%",
"(",
"self",
".",
"path",
",",
")",
"openid_url",
"=",
"self",
".",
"query",
".",
"get",
"(",
"'openid_identifier'",
")",
"self",
".",
"render",
"(",
"msg",
",",
"'error'",
",",
"openid_url",
",",
"status",
"=",
"404",
")"
] |
Render a page with a 404 return code and a message.
|
[
"Render",
"a",
"page",
"with",
"a",
"404",
"return",
"code",
"and",
"a",
"message",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L343-L348
|
16,563
|
openid/python-openid
|
examples/consumer.py
|
OpenIDRequestHandler.render
|
def render(self, message=None, css_class='alert', form_contents=None,
status=200, title="Python OpenID Consumer Example",
sreg_data=None, pape_data=None):
"""Render a page."""
self.send_response(status)
self.pageHeader(title)
if message:
self.wfile.write("<div class='%s'>" % (css_class,))
self.wfile.write(message)
self.wfile.write("</div>")
if sreg_data is not None:
self.renderSREG(sreg_data)
if pape_data is not None:
self.renderPAPE(pape_data)
self.pageFooter(form_contents)
|
python
|
def render(self, message=None, css_class='alert', form_contents=None,
status=200, title="Python OpenID Consumer Example",
sreg_data=None, pape_data=None):
"""Render a page."""
self.send_response(status)
self.pageHeader(title)
if message:
self.wfile.write("<div class='%s'>" % (css_class,))
self.wfile.write(message)
self.wfile.write("</div>")
if sreg_data is not None:
self.renderSREG(sreg_data)
if pape_data is not None:
self.renderPAPE(pape_data)
self.pageFooter(form_contents)
|
[
"def",
"render",
"(",
"self",
",",
"message",
"=",
"None",
",",
"css_class",
"=",
"'alert'",
",",
"form_contents",
"=",
"None",
",",
"status",
"=",
"200",
",",
"title",
"=",
"\"Python OpenID Consumer Example\"",
",",
"sreg_data",
"=",
"None",
",",
"pape_data",
"=",
"None",
")",
":",
"self",
".",
"send_response",
"(",
"status",
")",
"self",
".",
"pageHeader",
"(",
"title",
")",
"if",
"message",
":",
"self",
".",
"wfile",
".",
"write",
"(",
"\"<div class='%s'>\"",
"%",
"(",
"css_class",
",",
")",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"message",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"\"</div>\"",
")",
"if",
"sreg_data",
"is",
"not",
"None",
":",
"self",
".",
"renderSREG",
"(",
"sreg_data",
")",
"if",
"pape_data",
"is",
"not",
"None",
":",
"self",
".",
"renderPAPE",
"(",
"pape_data",
")",
"self",
".",
"pageFooter",
"(",
"form_contents",
")"
] |
Render a page.
|
[
"Render",
"a",
"page",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L350-L367
|
16,564
|
openid/python-openid
|
openid/store/sqlstore.py
|
SQLStore._callInTransaction
|
def _callInTransaction(self, func, *args, **kwargs):
"""Execute the given function inside of a transaction, with an
open cursor. If no exception is raised, the transaction is
comitted, otherwise it is rolled back."""
# No nesting of transactions
self.conn.rollback()
try:
self.cur = self.conn.cursor()
try:
ret = func(*args, **kwargs)
finally:
self.cur.close()
self.cur = None
except:
self.conn.rollback()
raise
else:
self.conn.commit()
return ret
|
python
|
def _callInTransaction(self, func, *args, **kwargs):
"""Execute the given function inside of a transaction, with an
open cursor. If no exception is raised, the transaction is
comitted, otherwise it is rolled back."""
# No nesting of transactions
self.conn.rollback()
try:
self.cur = self.conn.cursor()
try:
ret = func(*args, **kwargs)
finally:
self.cur.close()
self.cur = None
except:
self.conn.rollback()
raise
else:
self.conn.commit()
return ret
|
[
"def",
"_callInTransaction",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# No nesting of transactions",
"self",
".",
"conn",
".",
"rollback",
"(",
")",
"try",
":",
"self",
".",
"cur",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"try",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"finally",
":",
"self",
".",
"cur",
".",
"close",
"(",
")",
"self",
".",
"cur",
"=",
"None",
"except",
":",
"self",
".",
"conn",
".",
"rollback",
"(",
")",
"raise",
"else",
":",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"return",
"ret"
] |
Execute the given function inside of a transaction, with an
open cursor. If no exception is raised, the transaction is
comitted, otherwise it is rolled back.
|
[
"Execute",
"the",
"given",
"function",
"inside",
"of",
"a",
"transaction",
"with",
"an",
"open",
"cursor",
".",
"If",
"no",
"exception",
"is",
"raised",
"the",
"transaction",
"is",
"comitted",
"otherwise",
"it",
"is",
"rolled",
"back",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L162-L182
|
16,565
|
openid/python-openid
|
openid/store/sqlstore.py
|
SQLStore.txn_storeAssociation
|
def txn_storeAssociation(self, server_url, association):
"""Set the association for the server URL.
Association -> NoneType
"""
a = association
self.db_set_assoc(
server_url,
a.handle,
self.blobEncode(a.secret),
a.issued,
a.lifetime,
a.assoc_type)
|
python
|
def txn_storeAssociation(self, server_url, association):
"""Set the association for the server URL.
Association -> NoneType
"""
a = association
self.db_set_assoc(
server_url,
a.handle,
self.blobEncode(a.secret),
a.issued,
a.lifetime,
a.assoc_type)
|
[
"def",
"txn_storeAssociation",
"(",
"self",
",",
"server_url",
",",
"association",
")",
":",
"a",
"=",
"association",
"self",
".",
"db_set_assoc",
"(",
"server_url",
",",
"a",
".",
"handle",
",",
"self",
".",
"blobEncode",
"(",
"a",
".",
"secret",
")",
",",
"a",
".",
"issued",
",",
"a",
".",
"lifetime",
",",
"a",
".",
"assoc_type",
")"
] |
Set the association for the server URL.
Association -> NoneType
|
[
"Set",
"the",
"association",
"for",
"the",
"server",
"URL",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L195-L207
|
16,566
|
openid/python-openid
|
openid/store/sqlstore.py
|
SQLStore.txn_removeAssociation
|
def txn_removeAssociation(self, server_url, handle):
"""Remove the association for the given server URL and handle,
returning whether the association existed at all.
(str, str) -> bool
"""
self.db_remove_assoc(server_url, handle)
return self.cur.rowcount > 0
|
python
|
def txn_removeAssociation(self, server_url, handle):
"""Remove the association for the given server URL and handle,
returning whether the association existed at all.
(str, str) -> bool
"""
self.db_remove_assoc(server_url, handle)
return self.cur.rowcount > 0
|
[
"def",
"txn_removeAssociation",
"(",
"self",
",",
"server_url",
",",
"handle",
")",
":",
"self",
".",
"db_remove_assoc",
"(",
"server_url",
",",
"handle",
")",
"return",
"self",
".",
"cur",
".",
"rowcount",
">",
"0"
] |
Remove the association for the given server URL and handle,
returning whether the association existed at all.
(str, str) -> bool
|
[
"Remove",
"the",
"association",
"for",
"the",
"given",
"server",
"URL",
"and",
"handle",
"returning",
"whether",
"the",
"association",
"existed",
"at",
"all",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L243-L250
|
16,567
|
openid/python-openid
|
openid/store/sqlstore.py
|
SQLStore.txn_useNonce
|
def txn_useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is present, and if it is, then
remove it from the set.
str -> bool"""
if abs(timestamp - time.time()) > nonce.SKEW:
return False
try:
self.db_add_nonce(server_url, timestamp, salt)
except self.exceptions.IntegrityError:
# The key uniqueness check failed
return False
else:
# The nonce was successfully added
return True
|
python
|
def txn_useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is present, and if it is, then
remove it from the set.
str -> bool"""
if abs(timestamp - time.time()) > nonce.SKEW:
return False
try:
self.db_add_nonce(server_url, timestamp, salt)
except self.exceptions.IntegrityError:
# The key uniqueness check failed
return False
else:
# The nonce was successfully added
return True
|
[
"def",
"txn_useNonce",
"(",
"self",
",",
"server_url",
",",
"timestamp",
",",
"salt",
")",
":",
"if",
"abs",
"(",
"timestamp",
"-",
"time",
".",
"time",
"(",
")",
")",
">",
"nonce",
".",
"SKEW",
":",
"return",
"False",
"try",
":",
"self",
".",
"db_add_nonce",
"(",
"server_url",
",",
"timestamp",
",",
"salt",
")",
"except",
"self",
".",
"exceptions",
".",
"IntegrityError",
":",
"# The key uniqueness check failed",
"return",
"False",
"else",
":",
"# The nonce was successfully added",
"return",
"True"
] |
Return whether this nonce is present, and if it is, then
remove it from the set.
str -> bool
|
[
"Return",
"whether",
"this",
"nonce",
"is",
"present",
"and",
"if",
"it",
"is",
"then",
"remove",
"it",
"from",
"the",
"set",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L254-L269
|
16,568
|
openid/python-openid
|
openid/yadis/xri.py
|
_escape_xref
|
def _escape_xref(xref_match):
"""Escape things that need to be escaped if they're in a cross-reference.
"""
xref = xref_match.group()
xref = xref.replace('/', '%2F')
xref = xref.replace('?', '%3F')
xref = xref.replace('#', '%23')
return xref
|
python
|
def _escape_xref(xref_match):
"""Escape things that need to be escaped if they're in a cross-reference.
"""
xref = xref_match.group()
xref = xref.replace('/', '%2F')
xref = xref.replace('?', '%3F')
xref = xref.replace('#', '%23')
return xref
|
[
"def",
"_escape_xref",
"(",
"xref_match",
")",
":",
"xref",
"=",
"xref_match",
".",
"group",
"(",
")",
"xref",
"=",
"xref",
".",
"replace",
"(",
"'/'",
",",
"'%2F'",
")",
"xref",
"=",
"xref",
".",
"replace",
"(",
"'?'",
",",
"'%3F'",
")",
"xref",
"=",
"xref",
".",
"replace",
"(",
"'#'",
",",
"'%23'",
")",
"return",
"xref"
] |
Escape things that need to be escaped if they're in a cross-reference.
|
[
"Escape",
"things",
"that",
"need",
"to",
"be",
"escaped",
"if",
"they",
"re",
"in",
"a",
"cross",
"-",
"reference",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L79-L86
|
16,569
|
openid/python-openid
|
openid/yadis/xri.py
|
escapeForIRI
|
def escapeForIRI(xri):
"""Escape things that need to be escaped when transforming to an IRI."""
xri = xri.replace('%', '%25')
xri = _xref_re.sub(_escape_xref, xri)
return xri
|
python
|
def escapeForIRI(xri):
"""Escape things that need to be escaped when transforming to an IRI."""
xri = xri.replace('%', '%25')
xri = _xref_re.sub(_escape_xref, xri)
return xri
|
[
"def",
"escapeForIRI",
"(",
"xri",
")",
":",
"xri",
"=",
"xri",
".",
"replace",
"(",
"'%'",
",",
"'%25'",
")",
"xri",
"=",
"_xref_re",
".",
"sub",
"(",
"_escape_xref",
",",
"xri",
")",
"return",
"xri"
] |
Escape things that need to be escaped when transforming to an IRI.
|
[
"Escape",
"things",
"that",
"need",
"to",
"be",
"escaped",
"when",
"transforming",
"to",
"an",
"IRI",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L89-L93
|
16,570
|
openid/python-openid
|
openid/yadis/xri.py
|
providerIsAuthoritative
|
def providerIsAuthoritative(providerID, canonicalID):
"""Is this provider ID authoritative for this XRI?
@returntype: bool
"""
# XXX: can't use rsplit until we require python >= 2.4.
lastbang = canonicalID.rindex('!')
parent = canonicalID[:lastbang]
return parent == providerID
|
python
|
def providerIsAuthoritative(providerID, canonicalID):
"""Is this provider ID authoritative for this XRI?
@returntype: bool
"""
# XXX: can't use rsplit until we require python >= 2.4.
lastbang = canonicalID.rindex('!')
parent = canonicalID[:lastbang]
return parent == providerID
|
[
"def",
"providerIsAuthoritative",
"(",
"providerID",
",",
"canonicalID",
")",
":",
"# XXX: can't use rsplit until we require python >= 2.4.",
"lastbang",
"=",
"canonicalID",
".",
"rindex",
"(",
"'!'",
")",
"parent",
"=",
"canonicalID",
"[",
":",
"lastbang",
"]",
"return",
"parent",
"==",
"providerID"
] |
Is this provider ID authoritative for this XRI?
@returntype: bool
|
[
"Is",
"this",
"provider",
"ID",
"authoritative",
"for",
"this",
"XRI?"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L112-L120
|
16,571
|
openid/python-openid
|
openid/yadis/xri.py
|
rootAuthority
|
def rootAuthority(xri):
"""Return the root authority for an XRI.
Example::
rootAuthority("xri://@example") == "xri://@"
@type xri: unicode
@returntype: unicode
"""
if xri.startswith('xri://'):
xri = xri[6:]
authority = xri.split('/', 1)[0]
if authority[0] == '(':
# Cross-reference.
# XXX: This is incorrect if someone nests cross-references so there
# is another close-paren in there. Hopefully nobody does that
# before we have a real xriparse function. Hopefully nobody does
# that *ever*.
root = authority[:authority.index(')') + 1]
elif authority[0] in XRI_AUTHORITIES:
# Other XRI reference.
root = authority[0]
else:
# IRI reference. XXX: Can IRI authorities have segments?
segments = authority.split('!')
segments = reduce(list.__add__,
map(lambda s: s.split('*'), segments))
root = segments[0]
return XRI(root)
|
python
|
def rootAuthority(xri):
"""Return the root authority for an XRI.
Example::
rootAuthority("xri://@example") == "xri://@"
@type xri: unicode
@returntype: unicode
"""
if xri.startswith('xri://'):
xri = xri[6:]
authority = xri.split('/', 1)[0]
if authority[0] == '(':
# Cross-reference.
# XXX: This is incorrect if someone nests cross-references so there
# is another close-paren in there. Hopefully nobody does that
# before we have a real xriparse function. Hopefully nobody does
# that *ever*.
root = authority[:authority.index(')') + 1]
elif authority[0] in XRI_AUTHORITIES:
# Other XRI reference.
root = authority[0]
else:
# IRI reference. XXX: Can IRI authorities have segments?
segments = authority.split('!')
segments = reduce(list.__add__,
map(lambda s: s.split('*'), segments))
root = segments[0]
return XRI(root)
|
[
"def",
"rootAuthority",
"(",
"xri",
")",
":",
"if",
"xri",
".",
"startswith",
"(",
"'xri://'",
")",
":",
"xri",
"=",
"xri",
"[",
"6",
":",
"]",
"authority",
"=",
"xri",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"authority",
"[",
"0",
"]",
"==",
"'('",
":",
"# Cross-reference.",
"# XXX: This is incorrect if someone nests cross-references so there",
"# is another close-paren in there. Hopefully nobody does that",
"# before we have a real xriparse function. Hopefully nobody does",
"# that *ever*.",
"root",
"=",
"authority",
"[",
":",
"authority",
".",
"index",
"(",
"')'",
")",
"+",
"1",
"]",
"elif",
"authority",
"[",
"0",
"]",
"in",
"XRI_AUTHORITIES",
":",
"# Other XRI reference.",
"root",
"=",
"authority",
"[",
"0",
"]",
"else",
":",
"# IRI reference. XXX: Can IRI authorities have segments?",
"segments",
"=",
"authority",
".",
"split",
"(",
"'!'",
")",
"segments",
"=",
"reduce",
"(",
"list",
".",
"__add__",
",",
"map",
"(",
"lambda",
"s",
":",
"s",
".",
"split",
"(",
"'*'",
")",
",",
"segments",
")",
")",
"root",
"=",
"segments",
"[",
"0",
"]",
"return",
"XRI",
"(",
"root",
")"
] |
Return the root authority for an XRI.
Example::
rootAuthority("xri://@example") == "xri://@"
@type xri: unicode
@returntype: unicode
|
[
"Return",
"the",
"root",
"authority",
"for",
"an",
"XRI",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L123-L153
|
16,572
|
openid/python-openid
|
openid/extension.py
|
Extension.toMessage
|
def toMessage(self, message=None):
"""Add the arguments from this extension to the provided
message, or create a new message containing only those
arguments.
@returns: The message with the extension arguments added
"""
if message is None:
warnings.warn('Passing None to Extension.toMessage is deprecated. '
'Creating a message assuming you want OpenID 2.',
DeprecationWarning, stacklevel=2)
message = message_module.Message(message_module.OPENID2_NS)
implicit = message.isOpenID1()
try:
message.namespaces.addAlias(self.ns_uri, self.ns_alias,
implicit=implicit)
except KeyError:
if message.namespaces.getAlias(self.ns_uri) != self.ns_alias:
raise
message.updateArgs(self.ns_uri, self.getExtensionArgs())
return message
|
python
|
def toMessage(self, message=None):
"""Add the arguments from this extension to the provided
message, or create a new message containing only those
arguments.
@returns: The message with the extension arguments added
"""
if message is None:
warnings.warn('Passing None to Extension.toMessage is deprecated. '
'Creating a message assuming you want OpenID 2.',
DeprecationWarning, stacklevel=2)
message = message_module.Message(message_module.OPENID2_NS)
implicit = message.isOpenID1()
try:
message.namespaces.addAlias(self.ns_uri, self.ns_alias,
implicit=implicit)
except KeyError:
if message.namespaces.getAlias(self.ns_uri) != self.ns_alias:
raise
message.updateArgs(self.ns_uri, self.getExtensionArgs())
return message
|
[
"def",
"toMessage",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"'Passing None to Extension.toMessage is deprecated. '",
"'Creating a message assuming you want OpenID 2.'",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"message",
"=",
"message_module",
".",
"Message",
"(",
"message_module",
".",
"OPENID2_NS",
")",
"implicit",
"=",
"message",
".",
"isOpenID1",
"(",
")",
"try",
":",
"message",
".",
"namespaces",
".",
"addAlias",
"(",
"self",
".",
"ns_uri",
",",
"self",
".",
"ns_alias",
",",
"implicit",
"=",
"implicit",
")",
"except",
"KeyError",
":",
"if",
"message",
".",
"namespaces",
".",
"getAlias",
"(",
"self",
".",
"ns_uri",
")",
"!=",
"self",
".",
"ns_alias",
":",
"raise",
"message",
".",
"updateArgs",
"(",
"self",
".",
"ns_uri",
",",
"self",
".",
"getExtensionArgs",
"(",
")",
")",
"return",
"message"
] |
Add the arguments from this extension to the provided
message, or create a new message containing only those
arguments.
@returns: The message with the extension arguments added
|
[
"Add",
"the",
"arguments",
"from",
"this",
"extension",
"to",
"the",
"provided",
"message",
"or",
"create",
"a",
"new",
"message",
"containing",
"only",
"those",
"arguments",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extension.py#L23-L46
|
16,573
|
openid/python-openid
|
openid/store/filestore.py
|
_ensureDir
|
def _ensureDir(dir_name):
"""Create dir_name as a directory if it does not exist. If it
exists, make sure that it is, in fact, a directory.
Can raise OSError
str -> NoneType
"""
try:
os.makedirs(dir_name)
except OSError, why:
if why.errno != EEXIST or not os.path.isdir(dir_name):
raise
|
python
|
def _ensureDir(dir_name):
"""Create dir_name as a directory if it does not exist. If it
exists, make sure that it is, in fact, a directory.
Can raise OSError
str -> NoneType
"""
try:
os.makedirs(dir_name)
except OSError, why:
if why.errno != EEXIST or not os.path.isdir(dir_name):
raise
|
[
"def",
"_ensureDir",
"(",
"dir_name",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"dir_name",
")",
"except",
"OSError",
",",
"why",
":",
"if",
"why",
".",
"errno",
"!=",
"EEXIST",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dir_name",
")",
":",
"raise"
] |
Create dir_name as a directory if it does not exist. If it
exists, make sure that it is, in fact, a directory.
Can raise OSError
str -> NoneType
|
[
"Create",
"dir_name",
"as",
"a",
"directory",
"if",
"it",
"does",
"not",
"exist",
".",
"If",
"it",
"exists",
"make",
"sure",
"that",
"it",
"is",
"in",
"fact",
"a",
"directory",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L96-L108
|
16,574
|
openid/python-openid
|
openid/store/filestore.py
|
FileOpenIDStore._setup
|
def _setup(self):
"""Make sure that the directories in which we store our data
exist.
() -> NoneType
"""
_ensureDir(self.nonce_dir)
_ensureDir(self.association_dir)
_ensureDir(self.temp_dir)
|
python
|
def _setup(self):
"""Make sure that the directories in which we store our data
exist.
() -> NoneType
"""
_ensureDir(self.nonce_dir)
_ensureDir(self.association_dir)
_ensureDir(self.temp_dir)
|
[
"def",
"_setup",
"(",
"self",
")",
":",
"_ensureDir",
"(",
"self",
".",
"nonce_dir",
")",
"_ensureDir",
"(",
"self",
".",
"association_dir",
")",
"_ensureDir",
"(",
"self",
".",
"temp_dir",
")"
] |
Make sure that the directories in which we store our data
exist.
() -> NoneType
|
[
"Make",
"sure",
"that",
"the",
"directories",
"in",
"which",
"we",
"store",
"our",
"data",
"exist",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L153-L161
|
16,575
|
openid/python-openid
|
openid/store/filestore.py
|
FileOpenIDStore._mktemp
|
def _mktemp(self):
"""Create a temporary file on the same filesystem as
self.association_dir.
The temporary directory should not be cleaned if there are any
processes using the store. If there is no active process using
the store, it is safe to remove all of the files in the
temporary directory.
() -> (file, str)
"""
fd, name = mkstemp(dir=self.temp_dir)
try:
file_obj = os.fdopen(fd, 'wb')
return file_obj, name
except:
_removeIfPresent(name)
raise
|
python
|
def _mktemp(self):
"""Create a temporary file on the same filesystem as
self.association_dir.
The temporary directory should not be cleaned if there are any
processes using the store. If there is no active process using
the store, it is safe to remove all of the files in the
temporary directory.
() -> (file, str)
"""
fd, name = mkstemp(dir=self.temp_dir)
try:
file_obj = os.fdopen(fd, 'wb')
return file_obj, name
except:
_removeIfPresent(name)
raise
|
[
"def",
"_mktemp",
"(",
"self",
")",
":",
"fd",
",",
"name",
"=",
"mkstemp",
"(",
"dir",
"=",
"self",
".",
"temp_dir",
")",
"try",
":",
"file_obj",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'wb'",
")",
"return",
"file_obj",
",",
"name",
"except",
":",
"_removeIfPresent",
"(",
"name",
")",
"raise"
] |
Create a temporary file on the same filesystem as
self.association_dir.
The temporary directory should not be cleaned if there are any
processes using the store. If there is no active process using
the store, it is safe to remove all of the files in the
temporary directory.
() -> (file, str)
|
[
"Create",
"a",
"temporary",
"file",
"on",
"the",
"same",
"filesystem",
"as",
"self",
".",
"association_dir",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L163-L180
|
16,576
|
openid/python-openid
|
openid/store/filestore.py
|
FileOpenIDStore.getAssociationFilename
|
def getAssociationFilename(self, server_url, handle):
"""Create a unique filename for a given server url and
handle. This implementation does not assume anything about the
format of the handle. The filename that is returned will
contain the domain name from the server URL for ease of human
inspection of the data directory.
(str, str) -> str
"""
if server_url.find('://') == -1:
raise ValueError('Bad server URL: %r' % server_url)
proto, rest = server_url.split('://', 1)
domain = _filenameEscape(rest.split('/', 1)[0])
url_hash = _safe64(server_url)
if handle:
handle_hash = _safe64(handle)
else:
handle_hash = ''
filename = '%s-%s-%s-%s' % (proto, domain, url_hash, handle_hash)
return os.path.join(self.association_dir, filename)
|
python
|
def getAssociationFilename(self, server_url, handle):
"""Create a unique filename for a given server url and
handle. This implementation does not assume anything about the
format of the handle. The filename that is returned will
contain the domain name from the server URL for ease of human
inspection of the data directory.
(str, str) -> str
"""
if server_url.find('://') == -1:
raise ValueError('Bad server URL: %r' % server_url)
proto, rest = server_url.split('://', 1)
domain = _filenameEscape(rest.split('/', 1)[0])
url_hash = _safe64(server_url)
if handle:
handle_hash = _safe64(handle)
else:
handle_hash = ''
filename = '%s-%s-%s-%s' % (proto, domain, url_hash, handle_hash)
return os.path.join(self.association_dir, filename)
|
[
"def",
"getAssociationFilename",
"(",
"self",
",",
"server_url",
",",
"handle",
")",
":",
"if",
"server_url",
".",
"find",
"(",
"'://'",
")",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'Bad server URL: %r'",
"%",
"server_url",
")",
"proto",
",",
"rest",
"=",
"server_url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"domain",
"=",
"_filenameEscape",
"(",
"rest",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]",
")",
"url_hash",
"=",
"_safe64",
"(",
"server_url",
")",
"if",
"handle",
":",
"handle_hash",
"=",
"_safe64",
"(",
"handle",
")",
"else",
":",
"handle_hash",
"=",
"''",
"filename",
"=",
"'%s-%s-%s-%s'",
"%",
"(",
"proto",
",",
"domain",
",",
"url_hash",
",",
"handle_hash",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"association_dir",
",",
"filename",
")"
] |
Create a unique filename for a given server url and
handle. This implementation does not assume anything about the
format of the handle. The filename that is returned will
contain the domain name from the server URL for ease of human
inspection of the data directory.
(str, str) -> str
|
[
"Create",
"a",
"unique",
"filename",
"for",
"a",
"given",
"server",
"url",
"and",
"handle",
".",
"This",
"implementation",
"does",
"not",
"assume",
"anything",
"about",
"the",
"format",
"of",
"the",
"handle",
".",
"The",
"filename",
"that",
"is",
"returned",
"will",
"contain",
"the",
"domain",
"name",
"from",
"the",
"server",
"URL",
"for",
"ease",
"of",
"human",
"inspection",
"of",
"the",
"data",
"directory",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L182-L204
|
16,577
|
openid/python-openid
|
openid/store/filestore.py
|
FileOpenIDStore.getAssociation
|
def getAssociation(self, server_url, handle=None):
"""Retrieve an association. If no handle is specified, return
the association with the latest expiration.
(str, str or NoneType) -> Association or NoneType
"""
if handle is None:
handle = ''
# The filename with the empty handle is a prefix of all other
# associations for the given server URL.
filename = self.getAssociationFilename(server_url, handle)
if handle:
return self._getAssociation(filename)
else:
association_files = os.listdir(self.association_dir)
matching_files = []
# strip off the path to do the comparison
name = os.path.basename(filename)
for association_file in association_files:
if association_file.startswith(name):
matching_files.append(association_file)
matching_associations = []
# read the matching files and sort by time issued
for name in matching_files:
full_name = os.path.join(self.association_dir, name)
association = self._getAssociation(full_name)
if association is not None:
matching_associations.append(
(association.issued, association))
matching_associations.sort()
# return the most recently issued one.
if matching_associations:
(_, assoc) = matching_associations[-1]
return assoc
else:
return None
|
python
|
def getAssociation(self, server_url, handle=None):
"""Retrieve an association. If no handle is specified, return
the association with the latest expiration.
(str, str or NoneType) -> Association or NoneType
"""
if handle is None:
handle = ''
# The filename with the empty handle is a prefix of all other
# associations for the given server URL.
filename = self.getAssociationFilename(server_url, handle)
if handle:
return self._getAssociation(filename)
else:
association_files = os.listdir(self.association_dir)
matching_files = []
# strip off the path to do the comparison
name = os.path.basename(filename)
for association_file in association_files:
if association_file.startswith(name):
matching_files.append(association_file)
matching_associations = []
# read the matching files and sort by time issued
for name in matching_files:
full_name = os.path.join(self.association_dir, name)
association = self._getAssociation(full_name)
if association is not None:
matching_associations.append(
(association.issued, association))
matching_associations.sort()
# return the most recently issued one.
if matching_associations:
(_, assoc) = matching_associations[-1]
return assoc
else:
return None
|
[
"def",
"getAssociation",
"(",
"self",
",",
"server_url",
",",
"handle",
"=",
"None",
")",
":",
"if",
"handle",
"is",
"None",
":",
"handle",
"=",
"''",
"# The filename with the empty handle is a prefix of all other",
"# associations for the given server URL.",
"filename",
"=",
"self",
".",
"getAssociationFilename",
"(",
"server_url",
",",
"handle",
")",
"if",
"handle",
":",
"return",
"self",
".",
"_getAssociation",
"(",
"filename",
")",
"else",
":",
"association_files",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"association_dir",
")",
"matching_files",
"=",
"[",
"]",
"# strip off the path to do the comparison",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"for",
"association_file",
"in",
"association_files",
":",
"if",
"association_file",
".",
"startswith",
"(",
"name",
")",
":",
"matching_files",
".",
"append",
"(",
"association_file",
")",
"matching_associations",
"=",
"[",
"]",
"# read the matching files and sort by time issued",
"for",
"name",
"in",
"matching_files",
":",
"full_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"association_dir",
",",
"name",
")",
"association",
"=",
"self",
".",
"_getAssociation",
"(",
"full_name",
")",
"if",
"association",
"is",
"not",
"None",
":",
"matching_associations",
".",
"append",
"(",
"(",
"association",
".",
"issued",
",",
"association",
")",
")",
"matching_associations",
".",
"sort",
"(",
")",
"# return the most recently issued one.",
"if",
"matching_associations",
":",
"(",
"_",
",",
"assoc",
")",
"=",
"matching_associations",
"[",
"-",
"1",
"]",
"return",
"assoc",
"else",
":",
"return",
"None"
] |
Retrieve an association. If no handle is specified, return
the association with the latest expiration.
(str, str or NoneType) -> Association or NoneType
|
[
"Retrieve",
"an",
"association",
".",
"If",
"no",
"handle",
"is",
"specified",
"return",
"the",
"association",
"with",
"the",
"latest",
"expiration",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L248-L288
|
16,578
|
openid/python-openid
|
openid/store/filestore.py
|
FileOpenIDStore.removeAssociation
|
def removeAssociation(self, server_url, handle):
"""Remove an association if it exists. Do nothing if it does not.
(str, str) -> bool
"""
assoc = self.getAssociation(server_url, handle)
if assoc is None:
return 0
else:
filename = self.getAssociationFilename(server_url, handle)
return _removeIfPresent(filename)
|
python
|
def removeAssociation(self, server_url, handle):
"""Remove an association if it exists. Do nothing if it does not.
(str, str) -> bool
"""
assoc = self.getAssociation(server_url, handle)
if assoc is None:
return 0
else:
filename = self.getAssociationFilename(server_url, handle)
return _removeIfPresent(filename)
|
[
"def",
"removeAssociation",
"(",
"self",
",",
"server_url",
",",
"handle",
")",
":",
"assoc",
"=",
"self",
".",
"getAssociation",
"(",
"server_url",
",",
"handle",
")",
"if",
"assoc",
"is",
"None",
":",
"return",
"0",
"else",
":",
"filename",
"=",
"self",
".",
"getAssociationFilename",
"(",
"server_url",
",",
"handle",
")",
"return",
"_removeIfPresent",
"(",
"filename",
")"
] |
Remove an association if it exists. Do nothing if it does not.
(str, str) -> bool
|
[
"Remove",
"an",
"association",
"if",
"it",
"exists",
".",
"Do",
"nothing",
"if",
"it",
"does",
"not",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L318-L328
|
16,579
|
openid/python-openid
|
openid/store/filestore.py
|
FileOpenIDStore.useNonce
|
def useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is valid.
str -> bool
"""
if abs(timestamp - time.time()) > nonce.SKEW:
return False
if server_url:
proto, rest = server_url.split('://', 1)
else:
# Create empty proto / rest values for empty server_url,
# which is part of a consumer-generated nonce.
proto, rest = '', ''
domain = _filenameEscape(rest.split('/', 1)[0])
url_hash = _safe64(server_url)
salt_hash = _safe64(salt)
filename = '%08x-%s-%s-%s-%s' % (timestamp, proto, domain,
url_hash, salt_hash)
filename = os.path.join(self.nonce_dir, filename)
try:
fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0200)
except OSError, why:
if why.errno == EEXIST:
return False
else:
raise
else:
os.close(fd)
return True
|
python
|
def useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is valid.
str -> bool
"""
if abs(timestamp - time.time()) > nonce.SKEW:
return False
if server_url:
proto, rest = server_url.split('://', 1)
else:
# Create empty proto / rest values for empty server_url,
# which is part of a consumer-generated nonce.
proto, rest = '', ''
domain = _filenameEscape(rest.split('/', 1)[0])
url_hash = _safe64(server_url)
salt_hash = _safe64(salt)
filename = '%08x-%s-%s-%s-%s' % (timestamp, proto, domain,
url_hash, salt_hash)
filename = os.path.join(self.nonce_dir, filename)
try:
fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0200)
except OSError, why:
if why.errno == EEXIST:
return False
else:
raise
else:
os.close(fd)
return True
|
[
"def",
"useNonce",
"(",
"self",
",",
"server_url",
",",
"timestamp",
",",
"salt",
")",
":",
"if",
"abs",
"(",
"timestamp",
"-",
"time",
".",
"time",
"(",
")",
")",
">",
"nonce",
".",
"SKEW",
":",
"return",
"False",
"if",
"server_url",
":",
"proto",
",",
"rest",
"=",
"server_url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"else",
":",
"# Create empty proto / rest values for empty server_url,",
"# which is part of a consumer-generated nonce.",
"proto",
",",
"rest",
"=",
"''",
",",
"''",
"domain",
"=",
"_filenameEscape",
"(",
"rest",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]",
")",
"url_hash",
"=",
"_safe64",
"(",
"server_url",
")",
"salt_hash",
"=",
"_safe64",
"(",
"salt",
")",
"filename",
"=",
"'%08x-%s-%s-%s-%s'",
"%",
"(",
"timestamp",
",",
"proto",
",",
"domain",
",",
"url_hash",
",",
"salt_hash",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"nonce_dir",
",",
"filename",
")",
"try",
":",
"fd",
"=",
"os",
".",
"open",
"(",
"filename",
",",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_EXCL",
"|",
"os",
".",
"O_WRONLY",
",",
"0200",
")",
"except",
"OSError",
",",
"why",
":",
"if",
"why",
".",
"errno",
"==",
"EEXIST",
":",
"return",
"False",
"else",
":",
"raise",
"else",
":",
"os",
".",
"close",
"(",
"fd",
")",
"return",
"True"
] |
Return whether this nonce is valid.
str -> bool
|
[
"Return",
"whether",
"this",
"nonce",
"is",
"valid",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L330-L362
|
16,580
|
openid/python-openid
|
openid/consumer/discover.py
|
arrangeByType
|
def arrangeByType(service_list, preferred_types):
"""Rearrange service_list in a new list so services are ordered by
types listed in preferred_types. Return the new list."""
def enumerate(elts):
"""Return an iterable that pairs the index of an element with
that element.
For Python 2.2 compatibility"""
return zip(range(len(elts)), elts)
def bestMatchingService(service):
"""Return the index of the first matching type, or something
higher if no type matches.
This provides an ordering in which service elements that
contain a type that comes earlier in the preferred types list
come before service elements that come later. If a service
element has more than one type, the most preferred one wins.
"""
for i, t in enumerate(preferred_types):
if preferred_types[i] in service.type_uris:
return i
return len(preferred_types)
# Build a list with the service elements in tuples whose
# comparison will prefer the one with the best matching service
prio_services = [(bestMatchingService(s), orig_index, s)
for (orig_index, s) in enumerate(service_list)]
prio_services.sort()
# Now that the services are sorted by priority, remove the sort
# keys from the list.
for i in range(len(prio_services)):
prio_services[i] = prio_services[i][2]
return prio_services
|
python
|
def arrangeByType(service_list, preferred_types):
"""Rearrange service_list in a new list so services are ordered by
types listed in preferred_types. Return the new list."""
def enumerate(elts):
"""Return an iterable that pairs the index of an element with
that element.
For Python 2.2 compatibility"""
return zip(range(len(elts)), elts)
def bestMatchingService(service):
"""Return the index of the first matching type, or something
higher if no type matches.
This provides an ordering in which service elements that
contain a type that comes earlier in the preferred types list
come before service elements that come later. If a service
element has more than one type, the most preferred one wins.
"""
for i, t in enumerate(preferred_types):
if preferred_types[i] in service.type_uris:
return i
return len(preferred_types)
# Build a list with the service elements in tuples whose
# comparison will prefer the one with the best matching service
prio_services = [(bestMatchingService(s), orig_index, s)
for (orig_index, s) in enumerate(service_list)]
prio_services.sort()
# Now that the services are sorted by priority, remove the sort
# keys from the list.
for i in range(len(prio_services)):
prio_services[i] = prio_services[i][2]
return prio_services
|
[
"def",
"arrangeByType",
"(",
"service_list",
",",
"preferred_types",
")",
":",
"def",
"enumerate",
"(",
"elts",
")",
":",
"\"\"\"Return an iterable that pairs the index of an element with\n that element.\n\n For Python 2.2 compatibility\"\"\"",
"return",
"zip",
"(",
"range",
"(",
"len",
"(",
"elts",
")",
")",
",",
"elts",
")",
"def",
"bestMatchingService",
"(",
"service",
")",
":",
"\"\"\"Return the index of the first matching type, or something\n higher if no type matches.\n\n This provides an ordering in which service elements that\n contain a type that comes earlier in the preferred types list\n come before service elements that come later. If a service\n element has more than one type, the most preferred one wins.\n \"\"\"",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"preferred_types",
")",
":",
"if",
"preferred_types",
"[",
"i",
"]",
"in",
"service",
".",
"type_uris",
":",
"return",
"i",
"return",
"len",
"(",
"preferred_types",
")",
"# Build a list with the service elements in tuples whose",
"# comparison will prefer the one with the best matching service",
"prio_services",
"=",
"[",
"(",
"bestMatchingService",
"(",
"s",
")",
",",
"orig_index",
",",
"s",
")",
"for",
"(",
"orig_index",
",",
"s",
")",
"in",
"enumerate",
"(",
"service_list",
")",
"]",
"prio_services",
".",
"sort",
"(",
")",
"# Now that the services are sorted by priority, remove the sort",
"# keys from the list.",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"prio_services",
")",
")",
":",
"prio_services",
"[",
"i",
"]",
"=",
"prio_services",
"[",
"i",
"]",
"[",
"2",
"]",
"return",
"prio_services"
] |
Rearrange service_list in a new list so services are ordered by
types listed in preferred_types. Return the new list.
|
[
"Rearrange",
"service_list",
"in",
"a",
"new",
"list",
"so",
"services",
"are",
"ordered",
"by",
"types",
"listed",
"in",
"preferred_types",
".",
"Return",
"the",
"new",
"list",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L319-L356
|
16,581
|
openid/python-openid
|
openid/consumer/discover.py
|
getOPOrUserServices
|
def getOPOrUserServices(openid_services):
"""Extract OP Identifier services. If none found, return the
rest, sorted with most preferred first according to
OpenIDServiceEndpoint.openid_type_uris.
openid_services is a list of OpenIDServiceEndpoint objects.
Returns a list of OpenIDServiceEndpoint objects."""
op_services = arrangeByType(openid_services, [OPENID_IDP_2_0_TYPE])
openid_services = arrangeByType(openid_services,
OpenIDServiceEndpoint.openid_type_uris)
return op_services or openid_services
|
python
|
def getOPOrUserServices(openid_services):
"""Extract OP Identifier services. If none found, return the
rest, sorted with most preferred first according to
OpenIDServiceEndpoint.openid_type_uris.
openid_services is a list of OpenIDServiceEndpoint objects.
Returns a list of OpenIDServiceEndpoint objects."""
op_services = arrangeByType(openid_services, [OPENID_IDP_2_0_TYPE])
openid_services = arrangeByType(openid_services,
OpenIDServiceEndpoint.openid_type_uris)
return op_services or openid_services
|
[
"def",
"getOPOrUserServices",
"(",
"openid_services",
")",
":",
"op_services",
"=",
"arrangeByType",
"(",
"openid_services",
",",
"[",
"OPENID_IDP_2_0_TYPE",
"]",
")",
"openid_services",
"=",
"arrangeByType",
"(",
"openid_services",
",",
"OpenIDServiceEndpoint",
".",
"openid_type_uris",
")",
"return",
"op_services",
"or",
"openid_services"
] |
Extract OP Identifier services. If none found, return the
rest, sorted with most preferred first according to
OpenIDServiceEndpoint.openid_type_uris.
openid_services is a list of OpenIDServiceEndpoint objects.
Returns a list of OpenIDServiceEndpoint objects.
|
[
"Extract",
"OP",
"Identifier",
"services",
".",
"If",
"none",
"found",
"return",
"the",
"rest",
"sorted",
"with",
"most",
"preferred",
"first",
"according",
"to",
"OpenIDServiceEndpoint",
".",
"openid_type_uris",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L358-L372
|
16,582
|
openid/python-openid
|
openid/consumer/discover.py
|
OpenIDServiceEndpoint.supportsType
|
def supportsType(self, type_uri):
"""Does this endpoint support this type?
I consider C{/server} endpoints to implicitly support C{/signon}.
"""
return (
(type_uri in self.type_uris) or
(type_uri == OPENID_2_0_TYPE and self.isOPIdentifier())
)
|
python
|
def supportsType(self, type_uri):
"""Does this endpoint support this type?
I consider C{/server} endpoints to implicitly support C{/signon}.
"""
return (
(type_uri in self.type_uris) or
(type_uri == OPENID_2_0_TYPE and self.isOPIdentifier())
)
|
[
"def",
"supportsType",
"(",
"self",
",",
"type_uri",
")",
":",
"return",
"(",
"(",
"type_uri",
"in",
"self",
".",
"type_uris",
")",
"or",
"(",
"type_uri",
"==",
"OPENID_2_0_TYPE",
"and",
"self",
".",
"isOPIdentifier",
"(",
")",
")",
")"
] |
Does this endpoint support this type?
I consider C{/server} endpoints to implicitly support C{/signon}.
|
[
"Does",
"this",
"endpoint",
"support",
"this",
"type?"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L76-L84
|
16,583
|
openid/python-openid
|
openid/consumer/discover.py
|
OpenIDServiceEndpoint.parseService
|
def parseService(self, yadis_url, uri, type_uris, service_element):
"""Set the state of this object based on the contents of the
service element."""
self.type_uris = type_uris
self.server_url = uri
self.used_yadis = True
if not self.isOPIdentifier():
# XXX: This has crappy implications for Service elements
# that contain both 'server' and 'signon' Types. But
# that's a pathological configuration anyway, so I don't
# think I care.
self.local_id = findOPLocalIdentifier(service_element,
self.type_uris)
self.claimed_id = yadis_url
|
python
|
def parseService(self, yadis_url, uri, type_uris, service_element):
"""Set the state of this object based on the contents of the
service element."""
self.type_uris = type_uris
self.server_url = uri
self.used_yadis = True
if not self.isOPIdentifier():
# XXX: This has crappy implications for Service elements
# that contain both 'server' and 'signon' Types. But
# that's a pathological configuration anyway, so I don't
# think I care.
self.local_id = findOPLocalIdentifier(service_element,
self.type_uris)
self.claimed_id = yadis_url
|
[
"def",
"parseService",
"(",
"self",
",",
"yadis_url",
",",
"uri",
",",
"type_uris",
",",
"service_element",
")",
":",
"self",
".",
"type_uris",
"=",
"type_uris",
"self",
".",
"server_url",
"=",
"uri",
"self",
".",
"used_yadis",
"=",
"True",
"if",
"not",
"self",
".",
"isOPIdentifier",
"(",
")",
":",
"# XXX: This has crappy implications for Service elements",
"# that contain both 'server' and 'signon' Types. But",
"# that's a pathological configuration anyway, so I don't",
"# think I care.",
"self",
".",
"local_id",
"=",
"findOPLocalIdentifier",
"(",
"service_element",
",",
"self",
".",
"type_uris",
")",
"self",
".",
"claimed_id",
"=",
"yadis_url"
] |
Set the state of this object based on the contents of the
service element.
|
[
"Set",
"the",
"state",
"of",
"this",
"object",
"based",
"on",
"the",
"contents",
"of",
"the",
"service",
"element",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L102-L116
|
16,584
|
openid/python-openid
|
openid/consumer/discover.py
|
OpenIDServiceEndpoint.getLocalID
|
def getLocalID(self):
"""Return the identifier that should be sent as the
openid.identity parameter to the server."""
# I looked at this conditional and thought "ah-hah! there's the bug!"
# but Python actually makes that one big expression somehow, i.e.
# "x is x is x" is not the same thing as "(x is x) is x".
# That's pretty weird, dude. -- kmt, 1/07
if (self.local_id is self.canonicalID is None):
return self.claimed_id
else:
return self.local_id or self.canonicalID
|
python
|
def getLocalID(self):
"""Return the identifier that should be sent as the
openid.identity parameter to the server."""
# I looked at this conditional and thought "ah-hah! there's the bug!"
# but Python actually makes that one big expression somehow, i.e.
# "x is x is x" is not the same thing as "(x is x) is x".
# That's pretty weird, dude. -- kmt, 1/07
if (self.local_id is self.canonicalID is None):
return self.claimed_id
else:
return self.local_id or self.canonicalID
|
[
"def",
"getLocalID",
"(",
"self",
")",
":",
"# I looked at this conditional and thought \"ah-hah! there's the bug!\"",
"# but Python actually makes that one big expression somehow, i.e.",
"# \"x is x is x\" is not the same thing as \"(x is x) is x\".",
"# That's pretty weird, dude. -- kmt, 1/07",
"if",
"(",
"self",
".",
"local_id",
"is",
"self",
".",
"canonicalID",
"is",
"None",
")",
":",
"return",
"self",
".",
"claimed_id",
"else",
":",
"return",
"self",
".",
"local_id",
"or",
"self",
".",
"canonicalID"
] |
Return the identifier that should be sent as the
openid.identity parameter to the server.
|
[
"Return",
"the",
"identifier",
"that",
"should",
"be",
"sent",
"as",
"the",
"openid",
".",
"identity",
"parameter",
"to",
"the",
"server",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L118-L128
|
16,585
|
openid/python-openid
|
openid/consumer/discover.py
|
OpenIDServiceEndpoint.fromBasicServiceEndpoint
|
def fromBasicServiceEndpoint(cls, endpoint):
"""Create a new instance of this class from the endpoint
object passed in.
@return: None or OpenIDServiceEndpoint for this endpoint object"""
type_uris = endpoint.matchTypes(cls.openid_type_uris)
# If any Type URIs match and there is an endpoint URI
# specified, then this is an OpenID endpoint
if type_uris and endpoint.uri is not None:
openid_endpoint = cls()
openid_endpoint.parseService(
endpoint.yadis_url,
endpoint.uri,
endpoint.type_uris,
endpoint.service_element)
else:
openid_endpoint = None
return openid_endpoint
|
python
|
def fromBasicServiceEndpoint(cls, endpoint):
"""Create a new instance of this class from the endpoint
object passed in.
@return: None or OpenIDServiceEndpoint for this endpoint object"""
type_uris = endpoint.matchTypes(cls.openid_type_uris)
# If any Type URIs match and there is an endpoint URI
# specified, then this is an OpenID endpoint
if type_uris and endpoint.uri is not None:
openid_endpoint = cls()
openid_endpoint.parseService(
endpoint.yadis_url,
endpoint.uri,
endpoint.type_uris,
endpoint.service_element)
else:
openid_endpoint = None
return openid_endpoint
|
[
"def",
"fromBasicServiceEndpoint",
"(",
"cls",
",",
"endpoint",
")",
":",
"type_uris",
"=",
"endpoint",
".",
"matchTypes",
"(",
"cls",
".",
"openid_type_uris",
")",
"# If any Type URIs match and there is an endpoint URI",
"# specified, then this is an OpenID endpoint",
"if",
"type_uris",
"and",
"endpoint",
".",
"uri",
"is",
"not",
"None",
":",
"openid_endpoint",
"=",
"cls",
"(",
")",
"openid_endpoint",
".",
"parseService",
"(",
"endpoint",
".",
"yadis_url",
",",
"endpoint",
".",
"uri",
",",
"endpoint",
".",
"type_uris",
",",
"endpoint",
".",
"service_element",
")",
"else",
":",
"openid_endpoint",
"=",
"None",
"return",
"openid_endpoint"
] |
Create a new instance of this class from the endpoint
object passed in.
@return: None or OpenIDServiceEndpoint for this endpoint object
|
[
"Create",
"a",
"new",
"instance",
"of",
"this",
"class",
"from",
"the",
"endpoint",
"object",
"passed",
"in",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L130-L149
|
16,586
|
openid/python-openid
|
openid/consumer/discover.py
|
OpenIDServiceEndpoint.fromDiscoveryResult
|
def fromDiscoveryResult(cls, discoveryResult):
"""Create endpoints from a DiscoveryResult.
@type discoveryResult: L{DiscoveryResult}
@rtype: list of L{OpenIDServiceEndpoint}
@raises XRDSError: When the XRDS does not parse.
@since: 2.1.0
"""
if discoveryResult.isXRDS():
method = cls.fromXRDS
else:
method = cls.fromHTML
return method(discoveryResult.normalized_uri,
discoveryResult.response_text)
|
python
|
def fromDiscoveryResult(cls, discoveryResult):
"""Create endpoints from a DiscoveryResult.
@type discoveryResult: L{DiscoveryResult}
@rtype: list of L{OpenIDServiceEndpoint}
@raises XRDSError: When the XRDS does not parse.
@since: 2.1.0
"""
if discoveryResult.isXRDS():
method = cls.fromXRDS
else:
method = cls.fromHTML
return method(discoveryResult.normalized_uri,
discoveryResult.response_text)
|
[
"def",
"fromDiscoveryResult",
"(",
"cls",
",",
"discoveryResult",
")",
":",
"if",
"discoveryResult",
".",
"isXRDS",
"(",
")",
":",
"method",
"=",
"cls",
".",
"fromXRDS",
"else",
":",
"method",
"=",
"cls",
".",
"fromHTML",
"return",
"method",
"(",
"discoveryResult",
".",
"normalized_uri",
",",
"discoveryResult",
".",
"response_text",
")"
] |
Create endpoints from a DiscoveryResult.
@type discoveryResult: L{DiscoveryResult}
@rtype: list of L{OpenIDServiceEndpoint}
@raises XRDSError: When the XRDS does not parse.
@since: 2.1.0
|
[
"Create",
"endpoints",
"from",
"a",
"DiscoveryResult",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L200-L216
|
16,587
|
openid/python-openid
|
openid/consumer/discover.py
|
OpenIDServiceEndpoint.fromOPEndpointURL
|
def fromOPEndpointURL(cls, op_endpoint_url):
"""Construct an OP-Identifier OpenIDServiceEndpoint object for
a given OP Endpoint URL
@param op_endpoint_url: The URL of the endpoint
@rtype: OpenIDServiceEndpoint
"""
service = cls()
service.server_url = op_endpoint_url
service.type_uris = [OPENID_IDP_2_0_TYPE]
return service
|
python
|
def fromOPEndpointURL(cls, op_endpoint_url):
"""Construct an OP-Identifier OpenIDServiceEndpoint object for
a given OP Endpoint URL
@param op_endpoint_url: The URL of the endpoint
@rtype: OpenIDServiceEndpoint
"""
service = cls()
service.server_url = op_endpoint_url
service.type_uris = [OPENID_IDP_2_0_TYPE]
return service
|
[
"def",
"fromOPEndpointURL",
"(",
"cls",
",",
"op_endpoint_url",
")",
":",
"service",
"=",
"cls",
"(",
")",
"service",
".",
"server_url",
"=",
"op_endpoint_url",
"service",
".",
"type_uris",
"=",
"[",
"OPENID_IDP_2_0_TYPE",
"]",
"return",
"service"
] |
Construct an OP-Identifier OpenIDServiceEndpoint object for
a given OP Endpoint URL
@param op_endpoint_url: The URL of the endpoint
@rtype: OpenIDServiceEndpoint
|
[
"Construct",
"an",
"OP",
"-",
"Identifier",
"OpenIDServiceEndpoint",
"object",
"for",
"a",
"given",
"OP",
"Endpoint",
"URL"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L221-L231
|
16,588
|
openid/python-openid
|
openid/association.py
|
SessionNegotiator.setAllowedTypes
|
def setAllowedTypes(self, allowed_types):
"""Set the allowed association types, checking to make sure
each combination is valid."""
for (assoc_type, session_type) in allowed_types:
checkSessionType(assoc_type, session_type)
self.allowed_types = allowed_types
|
python
|
def setAllowedTypes(self, allowed_types):
"""Set the allowed association types, checking to make sure
each combination is valid."""
for (assoc_type, session_type) in allowed_types:
checkSessionType(assoc_type, session_type)
self.allowed_types = allowed_types
|
[
"def",
"setAllowedTypes",
"(",
"self",
",",
"allowed_types",
")",
":",
"for",
"(",
"assoc_type",
",",
"session_type",
")",
"in",
"allowed_types",
":",
"checkSessionType",
"(",
"assoc_type",
",",
"session_type",
")",
"self",
".",
"allowed_types",
"=",
"allowed_types"
] |
Set the allowed association types, checking to make sure
each combination is valid.
|
[
"Set",
"the",
"allowed",
"association",
"types",
"checking",
"to",
"make",
"sure",
"each",
"combination",
"is",
"valid",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L143-L149
|
16,589
|
openid/python-openid
|
openid/association.py
|
SessionNegotiator.isAllowed
|
def isAllowed(self, assoc_type, session_type):
"""Is this combination of association type and session type allowed?"""
assoc_good = (assoc_type, session_type) in self.allowed_types
matches = session_type in getSessionTypes(assoc_type)
return assoc_good and matches
|
python
|
def isAllowed(self, assoc_type, session_type):
"""Is this combination of association type and session type allowed?"""
assoc_good = (assoc_type, session_type) in self.allowed_types
matches = session_type in getSessionTypes(assoc_type)
return assoc_good and matches
|
[
"def",
"isAllowed",
"(",
"self",
",",
"assoc_type",
",",
"session_type",
")",
":",
"assoc_good",
"=",
"(",
"assoc_type",
",",
"session_type",
")",
"in",
"self",
".",
"allowed_types",
"matches",
"=",
"session_type",
"in",
"getSessionTypes",
"(",
"assoc_type",
")",
"return",
"assoc_good",
"and",
"matches"
] |
Is this combination of association type and session type allowed?
|
[
"Is",
"this",
"combination",
"of",
"association",
"type",
"and",
"session",
"type",
"allowed?"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L172-L176
|
16,590
|
openid/python-openid
|
openid/association.py
|
Association.serialize
|
def serialize(self):
"""
Convert an association to KV form.
@return: String in KV form suitable for deserialization by
deserialize.
@rtype: str
"""
data = {
'version':'2',
'handle':self.handle,
'secret':oidutil.toBase64(self.secret),
'issued':str(int(self.issued)),
'lifetime':str(int(self.lifetime)),
'assoc_type':self.assoc_type
}
assert len(data) == len(self.assoc_keys)
pairs = []
for field_name in self.assoc_keys:
pairs.append((field_name, data[field_name]))
return kvform.seqToKV(pairs, strict=True)
|
python
|
def serialize(self):
"""
Convert an association to KV form.
@return: String in KV form suitable for deserialization by
deserialize.
@rtype: str
"""
data = {
'version':'2',
'handle':self.handle,
'secret':oidutil.toBase64(self.secret),
'issued':str(int(self.issued)),
'lifetime':str(int(self.lifetime)),
'assoc_type':self.assoc_type
}
assert len(data) == len(self.assoc_keys)
pairs = []
for field_name in self.assoc_keys:
pairs.append((field_name, data[field_name]))
return kvform.seqToKV(pairs, strict=True)
|
[
"def",
"serialize",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'version'",
":",
"'2'",
",",
"'handle'",
":",
"self",
".",
"handle",
",",
"'secret'",
":",
"oidutil",
".",
"toBase64",
"(",
"self",
".",
"secret",
")",
",",
"'issued'",
":",
"str",
"(",
"int",
"(",
"self",
".",
"issued",
")",
")",
",",
"'lifetime'",
":",
"str",
"(",
"int",
"(",
"self",
".",
"lifetime",
")",
")",
",",
"'assoc_type'",
":",
"self",
".",
"assoc_type",
"}",
"assert",
"len",
"(",
"data",
")",
"==",
"len",
"(",
"self",
".",
"assoc_keys",
")",
"pairs",
"=",
"[",
"]",
"for",
"field_name",
"in",
"self",
".",
"assoc_keys",
":",
"pairs",
".",
"append",
"(",
"(",
"field_name",
",",
"data",
"[",
"field_name",
"]",
")",
")",
"return",
"kvform",
".",
"seqToKV",
"(",
"pairs",
",",
"strict",
"=",
"True",
")"
] |
Convert an association to KV form.
@return: String in KV form suitable for deserialization by
deserialize.
@rtype: str
|
[
"Convert",
"an",
"association",
"to",
"KV",
"form",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L398-L421
|
16,591
|
openid/python-openid
|
openid/association.py
|
Association.getMessageSignature
|
def getMessageSignature(self, message):
"""Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association.
"""
pairs = self._makePairs(message)
return oidutil.toBase64(self.sign(pairs))
|
python
|
def getMessageSignature(self, message):
"""Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association.
"""
pairs = self._makePairs(message)
return oidutil.toBase64(self.sign(pairs))
|
[
"def",
"getMessageSignature",
"(",
"self",
",",
"message",
")",
":",
"pairs",
"=",
"self",
".",
"_makePairs",
"(",
"message",
")",
"return",
"oidutil",
".",
"toBase64",
"(",
"self",
".",
"sign",
"(",
"pairs",
")",
")"
] |
Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association.
|
[
"Return",
"the",
"signature",
"of",
"a",
"message",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L482-L496
|
16,592
|
openid/python-openid
|
openid/association.py
|
Association.checkMessageSignature
|
def checkMessageSignature(self, message):
"""Given a message with a signature, calculate a new signature
and return whether it matches the signature in the message.
@raises ValueError: if the message has no signature or no signature
can be calculated for it.
"""
message_sig = message.getArg(OPENID_NS, 'sig')
if not message_sig:
raise ValueError("%s has no sig." % (message,))
calculated_sig = self.getMessageSignature(message)
return cryptutil.const_eq(calculated_sig, message_sig)
|
python
|
def checkMessageSignature(self, message):
"""Given a message with a signature, calculate a new signature
and return whether it matches the signature in the message.
@raises ValueError: if the message has no signature or no signature
can be calculated for it.
"""
message_sig = message.getArg(OPENID_NS, 'sig')
if not message_sig:
raise ValueError("%s has no sig." % (message,))
calculated_sig = self.getMessageSignature(message)
return cryptutil.const_eq(calculated_sig, message_sig)
|
[
"def",
"checkMessageSignature",
"(",
"self",
",",
"message",
")",
":",
"message_sig",
"=",
"message",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'sig'",
")",
"if",
"not",
"message_sig",
":",
"raise",
"ValueError",
"(",
"\"%s has no sig.\"",
"%",
"(",
"message",
",",
")",
")",
"calculated_sig",
"=",
"self",
".",
"getMessageSignature",
"(",
"message",
")",
"return",
"cryptutil",
".",
"const_eq",
"(",
"calculated_sig",
",",
"message_sig",
")"
] |
Given a message with a signature, calculate a new signature
and return whether it matches the signature in the message.
@raises ValueError: if the message has no signature or no signature
can be calculated for it.
|
[
"Given",
"a",
"message",
"with",
"a",
"signature",
"calculate",
"a",
"new",
"signature",
"and",
"return",
"whether",
"it",
"matches",
"the",
"signature",
"in",
"the",
"message",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L524-L535
|
16,593
|
openid/python-openid
|
openid/extensions/draft/pape2.py
|
Request.addPolicyURI
|
def addPolicyURI(self, policy_uri):
"""Add an acceptable authentication policy URI to this request
This method is intended to be used by the relying party to add
acceptable authentication types to the request.
@param policy_uri: The identifier for the preferred type of
authentication.
@see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies
"""
if policy_uri not in self.preferred_auth_policies:
self.preferred_auth_policies.append(policy_uri)
|
python
|
def addPolicyURI(self, policy_uri):
"""Add an acceptable authentication policy URI to this request
This method is intended to be used by the relying party to add
acceptable authentication types to the request.
@param policy_uri: The identifier for the preferred type of
authentication.
@see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies
"""
if policy_uri not in self.preferred_auth_policies:
self.preferred_auth_policies.append(policy_uri)
|
[
"def",
"addPolicyURI",
"(",
"self",
",",
"policy_uri",
")",
":",
"if",
"policy_uri",
"not",
"in",
"self",
".",
"preferred_auth_policies",
":",
"self",
".",
"preferred_auth_policies",
".",
"append",
"(",
"policy_uri",
")"
] |
Add an acceptable authentication policy URI to this request
This method is intended to be used by the relying party to add
acceptable authentication types to the request.
@param policy_uri: The identifier for the preferred type of
authentication.
@see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies
|
[
"Add",
"an",
"acceptable",
"authentication",
"policy",
"URI",
"to",
"this",
"request"
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape2.py#L60-L71
|
16,594
|
openid/python-openid
|
openid/extensions/draft/pape5.py
|
PAPEExtension._addAuthLevelAlias
|
def _addAuthLevelAlias(self, auth_level_uri, alias=None):
"""Add an auth level URI alias to this request.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the alias is not
important.
"""
if alias is None:
try:
alias = self._getAlias(auth_level_uri)
except KeyError:
alias = self._generateAlias()
else:
existing_uri = self.auth_level_aliases.get(alias)
if existing_uri is not None and existing_uri != auth_level_uri:
raise KeyError('Attempting to redefine alias %r from %r to %r',
alias, existing_uri, auth_level_uri)
self.auth_level_aliases[alias] = auth_level_uri
|
python
|
def _addAuthLevelAlias(self, auth_level_uri, alias=None):
"""Add an auth level URI alias to this request.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the alias is not
important.
"""
if alias is None:
try:
alias = self._getAlias(auth_level_uri)
except KeyError:
alias = self._generateAlias()
else:
existing_uri = self.auth_level_aliases.get(alias)
if existing_uri is not None and existing_uri != auth_level_uri:
raise KeyError('Attempting to redefine alias %r from %r to %r',
alias, existing_uri, auth_level_uri)
self.auth_level_aliases[alias] = auth_level_uri
|
[
"def",
"_addAuthLevelAlias",
"(",
"self",
",",
"auth_level_uri",
",",
"alias",
"=",
"None",
")",
":",
"if",
"alias",
"is",
"None",
":",
"try",
":",
"alias",
"=",
"self",
".",
"_getAlias",
"(",
"auth_level_uri",
")",
"except",
"KeyError",
":",
"alias",
"=",
"self",
".",
"_generateAlias",
"(",
")",
"else",
":",
"existing_uri",
"=",
"self",
".",
"auth_level_aliases",
".",
"get",
"(",
"alias",
")",
"if",
"existing_uri",
"is",
"not",
"None",
"and",
"existing_uri",
"!=",
"auth_level_uri",
":",
"raise",
"KeyError",
"(",
"'Attempting to redefine alias %r from %r to %r'",
",",
"alias",
",",
"existing_uri",
",",
"auth_level_uri",
")",
"self",
".",
"auth_level_aliases",
"[",
"alias",
"]",
"=",
"auth_level_uri"
] |
Add an auth level URI alias to this request.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the alias is not
important.
|
[
"Add",
"an",
"auth",
"level",
"URI",
"alias",
"to",
"this",
"request",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape5.py#L49-L70
|
16,595
|
openid/python-openid
|
openid/extensions/draft/pape5.py
|
Response.setAuthLevel
|
def setAuthLevel(self, level_uri, level, alias=None):
"""Set the value for the given auth level type.
@param level: string representation of an authentication level
valid for level_uri
@param alias: An optional namespace alias for the given auth
level URI. May be omitted if the alias is not
significant. The library will use a reasonable default for
widely-used auth level types.
"""
self._addAuthLevelAlias(level_uri, alias)
self.auth_levels[level_uri] = level
|
python
|
def setAuthLevel(self, level_uri, level, alias=None):
"""Set the value for the given auth level type.
@param level: string representation of an authentication level
valid for level_uri
@param alias: An optional namespace alias for the given auth
level URI. May be omitted if the alias is not
significant. The library will use a reasonable default for
widely-used auth level types.
"""
self._addAuthLevelAlias(level_uri, alias)
self.auth_levels[level_uri] = level
|
[
"def",
"setAuthLevel",
"(",
"self",
",",
"level_uri",
",",
"level",
",",
"alias",
"=",
"None",
")",
":",
"self",
".",
"_addAuthLevelAlias",
"(",
"level_uri",
",",
"alias",
")",
"self",
".",
"auth_levels",
"[",
"level_uri",
"]",
"=",
"level"
] |
Set the value for the given auth level type.
@param level: string representation of an authentication level
valid for level_uri
@param alias: An optional namespace alias for the given auth
level URI. May be omitted if the alias is not
significant. The library will use a reasonable default for
widely-used auth level types.
|
[
"Set",
"the",
"value",
"for",
"the",
"given",
"auth",
"level",
"type",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape5.py#L298-L310
|
16,596
|
openid/python-openid
|
openid/yadis/discover.py
|
discover
|
def discover(uri):
"""Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult object
@raises Exception: Any exception that can be raised by fetching a URL with
the given fetcher.
@raises DiscoveryFailure: When the HTTP response does not have a 200 code.
"""
result = DiscoveryResult(uri)
resp = fetchers.fetch(uri, headers={'Accept': YADIS_ACCEPT_HEADER})
if resp.status not in (200, 206):
raise DiscoveryFailure(
'HTTP Response status from identity URL host is not 200. '
'Got status %r' % (resp.status,), resp)
# Note the URL after following redirects
result.normalized_uri = resp.final_url
# Attempt to find out where to go to discover the document
# or if we already have it
result.content_type = resp.headers.get('content-type')
result.xrds_uri = whereIsYadis(resp)
if result.xrds_uri and result.usedYadisLocation():
resp = fetchers.fetch(result.xrds_uri)
if resp.status not in (200, 206):
exc = DiscoveryFailure(
'HTTP Response status from Yadis host is not 200. '
'Got status %r' % (resp.status,), resp)
exc.identity_url = result.normalized_uri
raise exc
result.content_type = resp.headers.get('content-type')
result.response_text = resp.body
return result
|
python
|
def discover(uri):
"""Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult object
@raises Exception: Any exception that can be raised by fetching a URL with
the given fetcher.
@raises DiscoveryFailure: When the HTTP response does not have a 200 code.
"""
result = DiscoveryResult(uri)
resp = fetchers.fetch(uri, headers={'Accept': YADIS_ACCEPT_HEADER})
if resp.status not in (200, 206):
raise DiscoveryFailure(
'HTTP Response status from identity URL host is not 200. '
'Got status %r' % (resp.status,), resp)
# Note the URL after following redirects
result.normalized_uri = resp.final_url
# Attempt to find out where to go to discover the document
# or if we already have it
result.content_type = resp.headers.get('content-type')
result.xrds_uri = whereIsYadis(resp)
if result.xrds_uri and result.usedYadisLocation():
resp = fetchers.fetch(result.xrds_uri)
if resp.status not in (200, 206):
exc = DiscoveryFailure(
'HTTP Response status from Yadis host is not 200. '
'Got status %r' % (resp.status,), resp)
exc.identity_url = result.normalized_uri
raise exc
result.content_type = resp.headers.get('content-type')
result.response_text = resp.body
return result
|
[
"def",
"discover",
"(",
"uri",
")",
":",
"result",
"=",
"DiscoveryResult",
"(",
"uri",
")",
"resp",
"=",
"fetchers",
".",
"fetch",
"(",
"uri",
",",
"headers",
"=",
"{",
"'Accept'",
":",
"YADIS_ACCEPT_HEADER",
"}",
")",
"if",
"resp",
".",
"status",
"not",
"in",
"(",
"200",
",",
"206",
")",
":",
"raise",
"DiscoveryFailure",
"(",
"'HTTP Response status from identity URL host is not 200. '",
"'Got status %r'",
"%",
"(",
"resp",
".",
"status",
",",
")",
",",
"resp",
")",
"# Note the URL after following redirects",
"result",
".",
"normalized_uri",
"=",
"resp",
".",
"final_url",
"# Attempt to find out where to go to discover the document",
"# or if we already have it",
"result",
".",
"content_type",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"result",
".",
"xrds_uri",
"=",
"whereIsYadis",
"(",
"resp",
")",
"if",
"result",
".",
"xrds_uri",
"and",
"result",
".",
"usedYadisLocation",
"(",
")",
":",
"resp",
"=",
"fetchers",
".",
"fetch",
"(",
"result",
".",
"xrds_uri",
")",
"if",
"resp",
".",
"status",
"not",
"in",
"(",
"200",
",",
"206",
")",
":",
"exc",
"=",
"DiscoveryFailure",
"(",
"'HTTP Response status from Yadis host is not 200. '",
"'Got status %r'",
"%",
"(",
"resp",
".",
"status",
",",
")",
",",
"resp",
")",
"exc",
".",
"identity_url",
"=",
"result",
".",
"normalized_uri",
"raise",
"exc",
"result",
".",
"content_type",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"result",
".",
"response_text",
"=",
"resp",
".",
"body",
"return",
"result"
] |
Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult object
@raises Exception: Any exception that can be raised by fetching a URL with
the given fetcher.
@raises DiscoveryFailure: When the HTTP response does not have a 200 code.
|
[
"Discover",
"services",
"for",
"a",
"given",
"URI",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/discover.py#L57-L98
|
16,597
|
openid/python-openid
|
openid/yadis/discover.py
|
whereIsYadis
|
def whereIsYadis(resp):
"""Given a HTTPResponse, return the location of the Yadis document.
May be the URL just retrieved, another URL, or None, if I can't
find any.
[non-blocking]
@returns: str or None
"""
# Attempt to find out where to go to discover the document
# or if we already have it
content_type = resp.headers.get('content-type')
# According to the spec, the content-type header must be an exact
# match, or else we have to look for an indirection.
if (content_type and
content_type.split(';', 1)[0].lower() == YADIS_CONTENT_TYPE):
return resp.final_url
else:
# Try the header
yadis_loc = resp.headers.get(YADIS_HEADER_NAME.lower())
if not yadis_loc:
# Parse as HTML if the header is missing.
#
# XXX: do we want to do something with content-type, like
# have a whitelist or a blacklist (for detecting that it's
# HTML)?
# Decode body by encoding of file
content_type = content_type or ''
encoding = content_type.rsplit(';', 1)
if len(encoding) == 2 and encoding[1].strip().startswith('charset='):
encoding = encoding[1].split('=', 1)[1].strip()
else:
encoding = 'UTF-8'
try:
content = resp.body.decode(encoding)
except UnicodeError:
# Keep encoded version in case yadis location can be found before encoding shut this up.
# Possible errors will be caught lower.
content = resp.body
try:
yadis_loc = findHTMLMeta(StringIO(content))
except (MetaNotFound, UnicodeError):
# UnicodeError: Response body could not be encoded and xrds location
# could not be found before troubles occurs.
pass
return yadis_loc
|
python
|
def whereIsYadis(resp):
"""Given a HTTPResponse, return the location of the Yadis document.
May be the URL just retrieved, another URL, or None, if I can't
find any.
[non-blocking]
@returns: str or None
"""
# Attempt to find out where to go to discover the document
# or if we already have it
content_type = resp.headers.get('content-type')
# According to the spec, the content-type header must be an exact
# match, or else we have to look for an indirection.
if (content_type and
content_type.split(';', 1)[0].lower() == YADIS_CONTENT_TYPE):
return resp.final_url
else:
# Try the header
yadis_loc = resp.headers.get(YADIS_HEADER_NAME.lower())
if not yadis_loc:
# Parse as HTML if the header is missing.
#
# XXX: do we want to do something with content-type, like
# have a whitelist or a blacklist (for detecting that it's
# HTML)?
# Decode body by encoding of file
content_type = content_type or ''
encoding = content_type.rsplit(';', 1)
if len(encoding) == 2 and encoding[1].strip().startswith('charset='):
encoding = encoding[1].split('=', 1)[1].strip()
else:
encoding = 'UTF-8'
try:
content = resp.body.decode(encoding)
except UnicodeError:
# Keep encoded version in case yadis location can be found before encoding shut this up.
# Possible errors will be caught lower.
content = resp.body
try:
yadis_loc = findHTMLMeta(StringIO(content))
except (MetaNotFound, UnicodeError):
# UnicodeError: Response body could not be encoded and xrds location
# could not be found before troubles occurs.
pass
return yadis_loc
|
[
"def",
"whereIsYadis",
"(",
"resp",
")",
":",
"# Attempt to find out where to go to discover the document",
"# or if we already have it",
"content_type",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"# According to the spec, the content-type header must be an exact",
"# match, or else we have to look for an indirection.",
"if",
"(",
"content_type",
"and",
"content_type",
".",
"split",
"(",
"';'",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"YADIS_CONTENT_TYPE",
")",
":",
"return",
"resp",
".",
"final_url",
"else",
":",
"# Try the header",
"yadis_loc",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"YADIS_HEADER_NAME",
".",
"lower",
"(",
")",
")",
"if",
"not",
"yadis_loc",
":",
"# Parse as HTML if the header is missing.",
"#",
"# XXX: do we want to do something with content-type, like",
"# have a whitelist or a blacklist (for detecting that it's",
"# HTML)?",
"# Decode body by encoding of file",
"content_type",
"=",
"content_type",
"or",
"''",
"encoding",
"=",
"content_type",
".",
"rsplit",
"(",
"';'",
",",
"1",
")",
"if",
"len",
"(",
"encoding",
")",
"==",
"2",
"and",
"encoding",
"[",
"1",
"]",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'charset='",
")",
":",
"encoding",
"=",
"encoding",
"[",
"1",
"]",
".",
"split",
"(",
"'='",
",",
"1",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"else",
":",
"encoding",
"=",
"'UTF-8'",
"try",
":",
"content",
"=",
"resp",
".",
"body",
".",
"decode",
"(",
"encoding",
")",
"except",
"UnicodeError",
":",
"# Keep encoded version in case yadis location can be found before encoding shut this up.",
"# Possible errors will be caught lower.",
"content",
"=",
"resp",
".",
"body",
"try",
":",
"yadis_loc",
"=",
"findHTMLMeta",
"(",
"StringIO",
"(",
"content",
")",
")",
"except",
"(",
"MetaNotFound",
",",
"UnicodeError",
")",
":",
"# UnicodeError: Response body could not be encoded and xrds location",
"# could not be found before troubles occurs.",
"pass",
"return",
"yadis_loc"
] |
Given a HTTPResponse, return the location of the Yadis document.
May be the URL just retrieved, another URL, or None, if I can't
find any.
[non-blocking]
@returns: str or None
|
[
"Given",
"a",
"HTTPResponse",
"return",
"the",
"location",
"of",
"the",
"Yadis",
"document",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/discover.py#L102-L154
|
16,598
|
openid/python-openid
|
examples/djopenid/server/views.py
|
endpoint
|
def endpoint(request):
"""
Respond to low-level OpenID protocol messages.
"""
s = getServer(request)
query = util.normalDict(request.GET or request.POST)
# First, decode the incoming request into something the OpenID
# library can use.
try:
openid_request = s.decodeRequest(query)
except ProtocolError, why:
# This means the incoming request was invalid.
return direct_to_template(
request,
'server/endpoint.html',
{'error': str(why)})
# If we did not get a request, display text indicating that this
# is an endpoint.
if openid_request is None:
return direct_to_template(
request,
'server/endpoint.html',
{})
# We got a request; if the mode is checkid_*, we will handle it by
# getting feedback from the user or by checking the session.
if openid_request.mode in ["checkid_immediate", "checkid_setup"]:
return handleCheckIDRequest(request, openid_request)
else:
# We got some other kind of OpenID request, so we let the
# server handle this.
openid_response = s.handleRequest(openid_request)
return displayResponse(request, openid_response)
|
python
|
def endpoint(request):
"""
Respond to low-level OpenID protocol messages.
"""
s = getServer(request)
query = util.normalDict(request.GET or request.POST)
# First, decode the incoming request into something the OpenID
# library can use.
try:
openid_request = s.decodeRequest(query)
except ProtocolError, why:
# This means the incoming request was invalid.
return direct_to_template(
request,
'server/endpoint.html',
{'error': str(why)})
# If we did not get a request, display text indicating that this
# is an endpoint.
if openid_request is None:
return direct_to_template(
request,
'server/endpoint.html',
{})
# We got a request; if the mode is checkid_*, we will handle it by
# getting feedback from the user or by checking the session.
if openid_request.mode in ["checkid_immediate", "checkid_setup"]:
return handleCheckIDRequest(request, openid_request)
else:
# We got some other kind of OpenID request, so we let the
# server handle this.
openid_response = s.handleRequest(openid_request)
return displayResponse(request, openid_response)
|
[
"def",
"endpoint",
"(",
"request",
")",
":",
"s",
"=",
"getServer",
"(",
"request",
")",
"query",
"=",
"util",
".",
"normalDict",
"(",
"request",
".",
"GET",
"or",
"request",
".",
"POST",
")",
"# First, decode the incoming request into something the OpenID",
"# library can use.",
"try",
":",
"openid_request",
"=",
"s",
".",
"decodeRequest",
"(",
"query",
")",
"except",
"ProtocolError",
",",
"why",
":",
"# This means the incoming request was invalid.",
"return",
"direct_to_template",
"(",
"request",
",",
"'server/endpoint.html'",
",",
"{",
"'error'",
":",
"str",
"(",
"why",
")",
"}",
")",
"# If we did not get a request, display text indicating that this",
"# is an endpoint.",
"if",
"openid_request",
"is",
"None",
":",
"return",
"direct_to_template",
"(",
"request",
",",
"'server/endpoint.html'",
",",
"{",
"}",
")",
"# We got a request; if the mode is checkid_*, we will handle it by",
"# getting feedback from the user or by checking the session.",
"if",
"openid_request",
".",
"mode",
"in",
"[",
"\"checkid_immediate\"",
",",
"\"checkid_setup\"",
"]",
":",
"return",
"handleCheckIDRequest",
"(",
"request",
",",
"openid_request",
")",
"else",
":",
"# We got some other kind of OpenID request, so we let the",
"# server handle this.",
"openid_response",
"=",
"s",
".",
"handleRequest",
"(",
"openid_request",
")",
"return",
"displayResponse",
"(",
"request",
",",
"openid_response",
")"
] |
Respond to low-level OpenID protocol messages.
|
[
"Respond",
"to",
"low",
"-",
"level",
"OpenID",
"protocol",
"messages",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/server/views.py#L101-L136
|
16,599
|
openid/python-openid
|
examples/djopenid/server/views.py
|
showDecidePage
|
def showDecidePage(request, openid_request):
"""
Render a page to the user so a trust decision can be made.
@type openid_request: openid.server.server.CheckIDRequest
"""
trust_root = openid_request.trust_root
return_to = openid_request.return_to
try:
# Stringify because template's ifequal can only compare to strings.
trust_root_valid = verifyReturnTo(trust_root, return_to) \
and "Valid" or "Invalid"
except DiscoveryFailure, err:
trust_root_valid = "DISCOVERY_FAILED"
except HTTPFetchingError, err:
trust_root_valid = "Unreachable"
pape_request = pape.Request.fromOpenIDRequest(openid_request)
return direct_to_template(
request,
'server/trust.html',
{'trust_root': trust_root,
'trust_handler_url':getViewURL(request, processTrustResult),
'trust_root_valid': trust_root_valid,
'pape_request': pape_request,
})
|
python
|
def showDecidePage(request, openid_request):
"""
Render a page to the user so a trust decision can be made.
@type openid_request: openid.server.server.CheckIDRequest
"""
trust_root = openid_request.trust_root
return_to = openid_request.return_to
try:
# Stringify because template's ifequal can only compare to strings.
trust_root_valid = verifyReturnTo(trust_root, return_to) \
and "Valid" or "Invalid"
except DiscoveryFailure, err:
trust_root_valid = "DISCOVERY_FAILED"
except HTTPFetchingError, err:
trust_root_valid = "Unreachable"
pape_request = pape.Request.fromOpenIDRequest(openid_request)
return direct_to_template(
request,
'server/trust.html',
{'trust_root': trust_root,
'trust_handler_url':getViewURL(request, processTrustResult),
'trust_root_valid': trust_root_valid,
'pape_request': pape_request,
})
|
[
"def",
"showDecidePage",
"(",
"request",
",",
"openid_request",
")",
":",
"trust_root",
"=",
"openid_request",
".",
"trust_root",
"return_to",
"=",
"openid_request",
".",
"return_to",
"try",
":",
"# Stringify because template's ifequal can only compare to strings.",
"trust_root_valid",
"=",
"verifyReturnTo",
"(",
"trust_root",
",",
"return_to",
")",
"and",
"\"Valid\"",
"or",
"\"Invalid\"",
"except",
"DiscoveryFailure",
",",
"err",
":",
"trust_root_valid",
"=",
"\"DISCOVERY_FAILED\"",
"except",
"HTTPFetchingError",
",",
"err",
":",
"trust_root_valid",
"=",
"\"Unreachable\"",
"pape_request",
"=",
"pape",
".",
"Request",
".",
"fromOpenIDRequest",
"(",
"openid_request",
")",
"return",
"direct_to_template",
"(",
"request",
",",
"'server/trust.html'",
",",
"{",
"'trust_root'",
":",
"trust_root",
",",
"'trust_handler_url'",
":",
"getViewURL",
"(",
"request",
",",
"processTrustResult",
")",
",",
"'trust_root_valid'",
":",
"trust_root_valid",
",",
"'pape_request'",
":",
"pape_request",
",",
"}",
")"
] |
Render a page to the user so a trust decision can be made.
@type openid_request: openid.server.server.CheckIDRequest
|
[
"Render",
"a",
"page",
"to",
"the",
"user",
"so",
"a",
"trust",
"decision",
"can",
"be",
"made",
"."
] |
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
|
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/server/views.py#L179-L206
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.