repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
aewallin/allantools | allantools/allantools.py | phase2radians | def phase2radians(phasedata, v0):
""" Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data in radians
"""
fi = [2*np.pi*v0*xx for xx in phasedata]
return fi | python | def phase2radians(phasedata, v0):
""" Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data in radians
"""
fi = [2*np.pi*v0*xx for xx in phasedata]
return fi | [
"def",
"phase2radians",
"(",
"phasedata",
",",
"v0",
")",
":",
"fi",
"=",
"[",
"2",
"*",
"np",
".",
"pi",
"*",
"v0",
"*",
"xx",
"for",
"xx",
"in",
"phasedata",
"]",
"return",
"fi"
] | Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data in radians | [
"Convert",
"phase",
"in",
"seconds",
"to",
"phase",
"in",
"radians"
] | b5c695a5af4379fcea4d4ce93a066cb902e7ee0a | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/allantools.py#L1621-L1637 | train | 231,800 |
aewallin/allantools | allantools/allantools.py | frequency2fractional | def frequency2fractional(frequency, mean_frequency=-1):
""" Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to mean frequency=np.mean(frequency)
Returns
-------
y:
Data array of fractional frequency
"""
if mean_frequency == -1:
mu = np.mean(frequency)
else:
mu = mean_frequency
y = [(x-mu)/mu for x in frequency]
return y | python | def frequency2fractional(frequency, mean_frequency=-1):
""" Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to mean frequency=np.mean(frequency)
Returns
-------
y:
Data array of fractional frequency
"""
if mean_frequency == -1:
mu = np.mean(frequency)
else:
mu = mean_frequency
y = [(x-mu)/mu for x in frequency]
return y | [
"def",
"frequency2fractional",
"(",
"frequency",
",",
"mean_frequency",
"=",
"-",
"1",
")",
":",
"if",
"mean_frequency",
"==",
"-",
"1",
":",
"mu",
"=",
"np",
".",
"mean",
"(",
"frequency",
")",
"else",
":",
"mu",
"=",
"mean_frequency",
"y",
"=",
"[",
"(",
"x",
"-",
"mu",
")",
"/",
"mu",
"for",
"x",
"in",
"frequency",
"]",
"return",
"y"
] | Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to mean frequency=np.mean(frequency)
Returns
-------
y:
Data array of fractional frequency | [
"Convert",
"frequency",
"in",
"Hz",
"to",
"fractional",
"frequency"
] | b5c695a5af4379fcea4d4ce93a066cb902e7ee0a | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/allantools.py#L1657-L1678 | train | 231,801 |
aewallin/allantools | allantools/dataset.py | Dataset.set_input | def set_input(self, data,
rate=1.0, data_type="phase", taus=None):
""" Optionnal method if you chose not to set inputs on init
Parameters
----------
data: np.array
Input data. Provide either phase or frequency (fractional,
adimensional)
rate: float
The sampling rate for data, in Hz. Defaults to 1.0
data_type: {'phase', 'freq'}
Data type, i.e. phase or frequency. Defaults to "phase".
taus: np.array
Array of tau values, in seconds, for which to compute statistic.
Optionally set taus=["all"|"octave"|"decade"] for automatic
"""
self.inp["data"] = data
self.inp["rate"] = rate
self.inp["data_type"] = data_type
self.inp["taus"] = taus | python | def set_input(self, data,
rate=1.0, data_type="phase", taus=None):
""" Optionnal method if you chose not to set inputs on init
Parameters
----------
data: np.array
Input data. Provide either phase or frequency (fractional,
adimensional)
rate: float
The sampling rate for data, in Hz. Defaults to 1.0
data_type: {'phase', 'freq'}
Data type, i.e. phase or frequency. Defaults to "phase".
taus: np.array
Array of tau values, in seconds, for which to compute statistic.
Optionally set taus=["all"|"octave"|"decade"] for automatic
"""
self.inp["data"] = data
self.inp["rate"] = rate
self.inp["data_type"] = data_type
self.inp["taus"] = taus | [
"def",
"set_input",
"(",
"self",
",",
"data",
",",
"rate",
"=",
"1.0",
",",
"data_type",
"=",
"\"phase\"",
",",
"taus",
"=",
"None",
")",
":",
"self",
".",
"inp",
"[",
"\"data\"",
"]",
"=",
"data",
"self",
".",
"inp",
"[",
"\"rate\"",
"]",
"=",
"rate",
"self",
".",
"inp",
"[",
"\"data_type\"",
"]",
"=",
"data_type",
"self",
".",
"inp",
"[",
"\"taus\"",
"]",
"=",
"taus"
] | Optionnal method if you chose not to set inputs on init
Parameters
----------
data: np.array
Input data. Provide either phase or frequency (fractional,
adimensional)
rate: float
The sampling rate for data, in Hz. Defaults to 1.0
data_type: {'phase', 'freq'}
Data type, i.e. phase or frequency. Defaults to "phase".
taus: np.array
Array of tau values, in seconds, for which to compute statistic.
Optionally set taus=["all"|"octave"|"decade"] for automatic | [
"Optionnal",
"method",
"if",
"you",
"chose",
"not",
"to",
"set",
"inputs",
"on",
"init"
] | b5c695a5af4379fcea4d4ce93a066cb902e7ee0a | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/dataset.py#L93-L113 | train | 231,802 |
aewallin/allantools | allantools/dataset.py | Dataset.compute | def compute(self, function):
"""Evaluate the passed function with the supplied data.
Stores result in self.out.
Parameters
----------
function: str
Name of the :mod:`allantools` function to evaluate
Returns
-------
result: dict
The results of the calculation.
"""
try:
func = getattr(allantools, function)
except AttributeError:
raise AttributeError("function must be defined in allantools")
whitelisted = ["theo1", "mtie", "tierms"]
if function[-3:] != "dev" and function not in whitelisted:
# this should probably raise a custom exception type so
# it's easier to distinguish from other bad things
raise RuntimeError("function must be one of the 'dev' functions")
result = func(self.inp["data"], rate=self.inp["rate"],
data_type=self.inp["data_type"], taus=self.inp["taus"])
keys = ["taus", "stat", "stat_err", "stat_n"]
result = {key: result[i] for i, key in enumerate(keys)}
self.out = result.copy()
self.out["stat_id"] = function
return result | python | def compute(self, function):
"""Evaluate the passed function with the supplied data.
Stores result in self.out.
Parameters
----------
function: str
Name of the :mod:`allantools` function to evaluate
Returns
-------
result: dict
The results of the calculation.
"""
try:
func = getattr(allantools, function)
except AttributeError:
raise AttributeError("function must be defined in allantools")
whitelisted = ["theo1", "mtie", "tierms"]
if function[-3:] != "dev" and function not in whitelisted:
# this should probably raise a custom exception type so
# it's easier to distinguish from other bad things
raise RuntimeError("function must be one of the 'dev' functions")
result = func(self.inp["data"], rate=self.inp["rate"],
data_type=self.inp["data_type"], taus=self.inp["taus"])
keys = ["taus", "stat", "stat_err", "stat_n"]
result = {key: result[i] for i, key in enumerate(keys)}
self.out = result.copy()
self.out["stat_id"] = function
return result | [
"def",
"compute",
"(",
"self",
",",
"function",
")",
":",
"try",
":",
"func",
"=",
"getattr",
"(",
"allantools",
",",
"function",
")",
"except",
"AttributeError",
":",
"raise",
"AttributeError",
"(",
"\"function must be defined in allantools\"",
")",
"whitelisted",
"=",
"[",
"\"theo1\"",
",",
"\"mtie\"",
",",
"\"tierms\"",
"]",
"if",
"function",
"[",
"-",
"3",
":",
"]",
"!=",
"\"dev\"",
"and",
"function",
"not",
"in",
"whitelisted",
":",
"# this should probably raise a custom exception type so",
"# it's easier to distinguish from other bad things",
"raise",
"RuntimeError",
"(",
"\"function must be one of the 'dev' functions\"",
")",
"result",
"=",
"func",
"(",
"self",
".",
"inp",
"[",
"\"data\"",
"]",
",",
"rate",
"=",
"self",
".",
"inp",
"[",
"\"rate\"",
"]",
",",
"data_type",
"=",
"self",
".",
"inp",
"[",
"\"data_type\"",
"]",
",",
"taus",
"=",
"self",
".",
"inp",
"[",
"\"taus\"",
"]",
")",
"keys",
"=",
"[",
"\"taus\"",
",",
"\"stat\"",
",",
"\"stat_err\"",
",",
"\"stat_n\"",
"]",
"result",
"=",
"{",
"key",
":",
"result",
"[",
"i",
"]",
"for",
"i",
",",
"key",
"in",
"enumerate",
"(",
"keys",
")",
"}",
"self",
".",
"out",
"=",
"result",
".",
"copy",
"(",
")",
"self",
".",
"out",
"[",
"\"stat_id\"",
"]",
"=",
"function",
"return",
"result"
] | Evaluate the passed function with the supplied data.
Stores result in self.out.
Parameters
----------
function: str
Name of the :mod:`allantools` function to evaluate
Returns
-------
result: dict
The results of the calculation. | [
"Evaluate",
"the",
"passed",
"function",
"with",
"the",
"supplied",
"data",
"."
] | b5c695a5af4379fcea4d4ce93a066cb902e7ee0a | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/dataset.py#L115-L148 | train | 231,803 |
aewallin/allantools | examples/noise-color_and_PSD.py | many_psds | def many_psds(k=2,fs=1.0, b0=1.0, N=1024):
""" compute average of many PSDs """
psd=[]
for j in range(k):
print j
x = noise.white(N=2*4096,b0=b0,fs=fs)
f, tmp = noise.numpy_psd(x,fs)
if j==0:
psd = tmp
else:
psd = psd + tmp
return f, psd/k | python | def many_psds(k=2,fs=1.0, b0=1.0, N=1024):
""" compute average of many PSDs """
psd=[]
for j in range(k):
print j
x = noise.white(N=2*4096,b0=b0,fs=fs)
f, tmp = noise.numpy_psd(x,fs)
if j==0:
psd = tmp
else:
psd = psd + tmp
return f, psd/k | [
"def",
"many_psds",
"(",
"k",
"=",
"2",
",",
"fs",
"=",
"1.0",
",",
"b0",
"=",
"1.0",
",",
"N",
"=",
"1024",
")",
":",
"psd",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"k",
")",
":",
"print",
"j",
"x",
"=",
"noise",
".",
"white",
"(",
"N",
"=",
"2",
"*",
"4096",
",",
"b0",
"=",
"b0",
",",
"fs",
"=",
"fs",
")",
"f",
",",
"tmp",
"=",
"noise",
".",
"numpy_psd",
"(",
"x",
",",
"fs",
")",
"if",
"j",
"==",
"0",
":",
"psd",
"=",
"tmp",
"else",
":",
"psd",
"=",
"psd",
"+",
"tmp",
"return",
"f",
",",
"psd",
"/",
"k"
] | compute average of many PSDs | [
"compute",
"average",
"of",
"many",
"PSDs"
] | b5c695a5af4379fcea4d4ce93a066cb902e7ee0a | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/examples/noise-color_and_PSD.py#L7-L18 | train | 231,804 |
singnet/snet-cli | snet_cli/commands.py | OrganizationCommand.list_my | def list_my(self):
""" Find organization that has the current identity as the owner or as the member """
org_list = self.call_contract_command("Registry", "listOrganizations", [])
rez_owner = []
rez_member = []
for idx, org_id in enumerate(org_list):
(found, org_id, org_name, owner, members, serviceNames, repositoryNames) = self.call_contract_command("Registry", "getOrganizationById", [org_id])
if (not found):
raise Exception("Organization was removed during this call. Please retry.");
if self.ident.address == owner:
rez_owner.append((org_name, bytes32_to_str(org_id)))
if self.ident.address in members:
rez_member.append((org_name, bytes32_to_str(org_id)))
if (rez_owner):
self._printout("# Organizations you are the owner of")
self._printout("# OrgName OrgId")
for n,i in rez_owner:
self._printout("%s %s"%(n,i))
if (rez_member):
self._printout("# Organizations you are the member of")
self._printout("# OrgName OrgId")
for n,i in rez_member:
self._printout("%s %s"%(n,i)) | python | def list_my(self):
""" Find organization that has the current identity as the owner or as the member """
org_list = self.call_contract_command("Registry", "listOrganizations", [])
rez_owner = []
rez_member = []
for idx, org_id in enumerate(org_list):
(found, org_id, org_name, owner, members, serviceNames, repositoryNames) = self.call_contract_command("Registry", "getOrganizationById", [org_id])
if (not found):
raise Exception("Organization was removed during this call. Please retry.");
if self.ident.address == owner:
rez_owner.append((org_name, bytes32_to_str(org_id)))
if self.ident.address in members:
rez_member.append((org_name, bytes32_to_str(org_id)))
if (rez_owner):
self._printout("# Organizations you are the owner of")
self._printout("# OrgName OrgId")
for n,i in rez_owner:
self._printout("%s %s"%(n,i))
if (rez_member):
self._printout("# Organizations you are the member of")
self._printout("# OrgName OrgId")
for n,i in rez_member:
self._printout("%s %s"%(n,i)) | [
"def",
"list_my",
"(",
"self",
")",
":",
"org_list",
"=",
"self",
".",
"call_contract_command",
"(",
"\"Registry\"",
",",
"\"listOrganizations\"",
",",
"[",
"]",
")",
"rez_owner",
"=",
"[",
"]",
"rez_member",
"=",
"[",
"]",
"for",
"idx",
",",
"org_id",
"in",
"enumerate",
"(",
"org_list",
")",
":",
"(",
"found",
",",
"org_id",
",",
"org_name",
",",
"owner",
",",
"members",
",",
"serviceNames",
",",
"repositoryNames",
")",
"=",
"self",
".",
"call_contract_command",
"(",
"\"Registry\"",
",",
"\"getOrganizationById\"",
",",
"[",
"org_id",
"]",
")",
"if",
"(",
"not",
"found",
")",
":",
"raise",
"Exception",
"(",
"\"Organization was removed during this call. Please retry.\"",
")",
"if",
"self",
".",
"ident",
".",
"address",
"==",
"owner",
":",
"rez_owner",
".",
"append",
"(",
"(",
"org_name",
",",
"bytes32_to_str",
"(",
"org_id",
")",
")",
")",
"if",
"self",
".",
"ident",
".",
"address",
"in",
"members",
":",
"rez_member",
".",
"append",
"(",
"(",
"org_name",
",",
"bytes32_to_str",
"(",
"org_id",
")",
")",
")",
"if",
"(",
"rez_owner",
")",
":",
"self",
".",
"_printout",
"(",
"\"# Organizations you are the owner of\"",
")",
"self",
".",
"_printout",
"(",
"\"# OrgName OrgId\"",
")",
"for",
"n",
",",
"i",
"in",
"rez_owner",
":",
"self",
".",
"_printout",
"(",
"\"%s %s\"",
"%",
"(",
"n",
",",
"i",
")",
")",
"if",
"(",
"rez_member",
")",
":",
"self",
".",
"_printout",
"(",
"\"# Organizations you are the member of\"",
")",
"self",
".",
"_printout",
"(",
"\"# OrgName OrgId\"",
")",
"for",
"n",
",",
"i",
"in",
"rez_member",
":",
"self",
".",
"_printout",
"(",
"\"%s %s\"",
"%",
"(",
"n",
",",
"i",
")",
")"
] | Find organization that has the current identity as the owner or as the member | [
"Find",
"organization",
"that",
"has",
"the",
"current",
"identity",
"as",
"the",
"owner",
"or",
"as",
"the",
"member"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/commands.py#L541-L567 | train | 231,805 |
singnet/snet-cli | snet_cli/mpe_service_metadata.py | MPEServiceMetadata.add_group | def add_group(self, group_name, payment_address):
""" Return new group_id in base64 """
if (self.is_group_name_exists(group_name)):
raise Exception("the group \"%s\" is already present"%str(group_name))
group_id_base64 = base64.b64encode(secrets.token_bytes(32))
self.m["groups"] += [{"group_name" : group_name ,
"group_id" : group_id_base64.decode("ascii"),
"payment_address" : payment_address}]
return group_id_base64 | python | def add_group(self, group_name, payment_address):
""" Return new group_id in base64 """
if (self.is_group_name_exists(group_name)):
raise Exception("the group \"%s\" is already present"%str(group_name))
group_id_base64 = base64.b64encode(secrets.token_bytes(32))
self.m["groups"] += [{"group_name" : group_name ,
"group_id" : group_id_base64.decode("ascii"),
"payment_address" : payment_address}]
return group_id_base64 | [
"def",
"add_group",
"(",
"self",
",",
"group_name",
",",
"payment_address",
")",
":",
"if",
"(",
"self",
".",
"is_group_name_exists",
"(",
"group_name",
")",
")",
":",
"raise",
"Exception",
"(",
"\"the group \\\"%s\\\" is already present\"",
"%",
"str",
"(",
"group_name",
")",
")",
"group_id_base64",
"=",
"base64",
".",
"b64encode",
"(",
"secrets",
".",
"token_bytes",
"(",
"32",
")",
")",
"self",
".",
"m",
"[",
"\"groups\"",
"]",
"+=",
"[",
"{",
"\"group_name\"",
":",
"group_name",
",",
"\"group_id\"",
":",
"group_id_base64",
".",
"decode",
"(",
"\"ascii\"",
")",
",",
"\"payment_address\"",
":",
"payment_address",
"}",
"]",
"return",
"group_id_base64"
] | Return new group_id in base64 | [
"Return",
"new",
"group_id",
"in",
"base64"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_metadata.py#L75-L83 | train | 231,806 |
singnet/snet-cli | snet_cli/mpe_service_metadata.py | MPEServiceMetadata.is_group_name_exists | def is_group_name_exists(self, group_name):
""" check if group with given name is already exists """
groups = self.m["groups"]
for g in groups:
if (g["group_name"] == group_name):
return True
return False | python | def is_group_name_exists(self, group_name):
""" check if group with given name is already exists """
groups = self.m["groups"]
for g in groups:
if (g["group_name"] == group_name):
return True
return False | [
"def",
"is_group_name_exists",
"(",
"self",
",",
"group_name",
")",
":",
"groups",
"=",
"self",
".",
"m",
"[",
"\"groups\"",
"]",
"for",
"g",
"in",
"groups",
":",
"if",
"(",
"g",
"[",
"\"group_name\"",
"]",
"==",
"group_name",
")",
":",
"return",
"True",
"return",
"False"
] | check if group with given name is already exists | [
"check",
"if",
"group",
"with",
"given",
"name",
"is",
"already",
"exists"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_metadata.py#L103-L109 | train | 231,807 |
singnet/snet-cli | snet_cli/mpe_service_metadata.py | MPEServiceMetadata.get_group_name_nonetrick | def get_group_name_nonetrick(self, group_name = None):
""" In all getter function in case of single payment group, group_name can be None """
groups = self.m["groups"]
if (len(groups) == 0):
raise Exception("Cannot find any groups in metadata")
if (not group_name):
if (len(groups) > 1):
raise Exception("We have more than one payment group in metadata, so group_name should be specified")
return groups[0]["group_name"]
return group_name | python | def get_group_name_nonetrick(self, group_name = None):
""" In all getter function in case of single payment group, group_name can be None """
groups = self.m["groups"]
if (len(groups) == 0):
raise Exception("Cannot find any groups in metadata")
if (not group_name):
if (len(groups) > 1):
raise Exception("We have more than one payment group in metadata, so group_name should be specified")
return groups[0]["group_name"]
return group_name | [
"def",
"get_group_name_nonetrick",
"(",
"self",
",",
"group_name",
"=",
"None",
")",
":",
"groups",
"=",
"self",
".",
"m",
"[",
"\"groups\"",
"]",
"if",
"(",
"len",
"(",
"groups",
")",
"==",
"0",
")",
":",
"raise",
"Exception",
"(",
"\"Cannot find any groups in metadata\"",
")",
"if",
"(",
"not",
"group_name",
")",
":",
"if",
"(",
"len",
"(",
"groups",
")",
">",
"1",
")",
":",
"raise",
"Exception",
"(",
"\"We have more than one payment group in metadata, so group_name should be specified\"",
")",
"return",
"groups",
"[",
"0",
"]",
"[",
"\"group_name\"",
"]",
"return",
"group_name"
] | In all getter function in case of single payment group, group_name can be None | [
"In",
"all",
"getter",
"function",
"in",
"case",
"of",
"single",
"payment",
"group",
"group_name",
"can",
"be",
"None"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_metadata.py#L145-L154 | train | 231,808 |
singnet/snet-cli | snet_cli/utils_ipfs.py | get_from_ipfs_and_checkhash | def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True):
"""
Get file from ipfs
We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise
"""
if validate:
from snet_cli.resources.proto.unixfs_pb2 import Data
from snet_cli.resources.proto.merckledag_pb2 import MerkleNode
# No nice Python library to parse ipfs blocks, so do it ourselves.
block_data = ipfs_client.block_get(ipfs_hash_base58)
mn = MerkleNode()
mn.ParseFromString(block_data)
unixfs_data = Data()
unixfs_data.ParseFromString(mn.Data)
assert unixfs_data.Type == unixfs_data.DataType.Value('File'), "IPFS hash must be a file"
data = unixfs_data.Data
# multihash has a badly registered base58 codec, overwrite it...
multihash.CodecReg.register('base58', base58.b58encode, base58.b58decode)
# create a multihash object from our ipfs hash
mh = multihash.decode(ipfs_hash_base58.encode('ascii'), 'base58')
# Convenience method lets us directly use a multihash to verify data
if not mh.verify(block_data):
raise Exception("IPFS hash mismatch with data")
else:
data = ipfs_client.cat(ipfs_hash_base58)
return data | python | def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True):
"""
Get file from ipfs
We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise
"""
if validate:
from snet_cli.resources.proto.unixfs_pb2 import Data
from snet_cli.resources.proto.merckledag_pb2 import MerkleNode
# No nice Python library to parse ipfs blocks, so do it ourselves.
block_data = ipfs_client.block_get(ipfs_hash_base58)
mn = MerkleNode()
mn.ParseFromString(block_data)
unixfs_data = Data()
unixfs_data.ParseFromString(mn.Data)
assert unixfs_data.Type == unixfs_data.DataType.Value('File'), "IPFS hash must be a file"
data = unixfs_data.Data
# multihash has a badly registered base58 codec, overwrite it...
multihash.CodecReg.register('base58', base58.b58encode, base58.b58decode)
# create a multihash object from our ipfs hash
mh = multihash.decode(ipfs_hash_base58.encode('ascii'), 'base58')
# Convenience method lets us directly use a multihash to verify data
if not mh.verify(block_data):
raise Exception("IPFS hash mismatch with data")
else:
data = ipfs_client.cat(ipfs_hash_base58)
return data | [
"def",
"get_from_ipfs_and_checkhash",
"(",
"ipfs_client",
",",
"ipfs_hash_base58",
",",
"validate",
"=",
"True",
")",
":",
"if",
"validate",
":",
"from",
"snet_cli",
".",
"resources",
".",
"proto",
".",
"unixfs_pb2",
"import",
"Data",
"from",
"snet_cli",
".",
"resources",
".",
"proto",
".",
"merckledag_pb2",
"import",
"MerkleNode",
"# No nice Python library to parse ipfs blocks, so do it ourselves.",
"block_data",
"=",
"ipfs_client",
".",
"block_get",
"(",
"ipfs_hash_base58",
")",
"mn",
"=",
"MerkleNode",
"(",
")",
"mn",
".",
"ParseFromString",
"(",
"block_data",
")",
"unixfs_data",
"=",
"Data",
"(",
")",
"unixfs_data",
".",
"ParseFromString",
"(",
"mn",
".",
"Data",
")",
"assert",
"unixfs_data",
".",
"Type",
"==",
"unixfs_data",
".",
"DataType",
".",
"Value",
"(",
"'File'",
")",
",",
"\"IPFS hash must be a file\"",
"data",
"=",
"unixfs_data",
".",
"Data",
"# multihash has a badly registered base58 codec, overwrite it...",
"multihash",
".",
"CodecReg",
".",
"register",
"(",
"'base58'",
",",
"base58",
".",
"b58encode",
",",
"base58",
".",
"b58decode",
")",
"# create a multihash object from our ipfs hash",
"mh",
"=",
"multihash",
".",
"decode",
"(",
"ipfs_hash_base58",
".",
"encode",
"(",
"'ascii'",
")",
",",
"'base58'",
")",
"# Convenience method lets us directly use a multihash to verify data",
"if",
"not",
"mh",
".",
"verify",
"(",
"block_data",
")",
":",
"raise",
"Exception",
"(",
"\"IPFS hash mismatch with data\"",
")",
"else",
":",
"data",
"=",
"ipfs_client",
".",
"cat",
"(",
"ipfs_hash_base58",
")",
"return",
"data"
] | Get file from ipfs
We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise | [
"Get",
"file",
"from",
"ipfs",
"We",
"must",
"check",
"the",
"hash",
"becasue",
"we",
"cannot",
"believe",
"that",
"ipfs_client",
"wasn",
"t",
"been",
"compromise"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/utils_ipfs.py#L35-L63 | train | 231,809 |
singnet/snet-cli | snet_cli/utils_ipfs.py | hash_to_bytesuri | def hash_to_bytesuri(s):
"""
Convert in and from bytes uri format used in Registry contract
"""
# TODO: we should pad string with zeros till closest 32 bytes word because of a bug in processReceipt (in snet_cli.contract.process_receipt)
s = "ipfs://" + s
return s.encode("ascii").ljust(32 * (len(s)//32 + 1), b"\0") | python | def hash_to_bytesuri(s):
"""
Convert in and from bytes uri format used in Registry contract
"""
# TODO: we should pad string with zeros till closest 32 bytes word because of a bug in processReceipt (in snet_cli.contract.process_receipt)
s = "ipfs://" + s
return s.encode("ascii").ljust(32 * (len(s)//32 + 1), b"\0") | [
"def",
"hash_to_bytesuri",
"(",
"s",
")",
":",
"# TODO: we should pad string with zeros till closest 32 bytes word because of a bug in processReceipt (in snet_cli.contract.process_receipt)",
"s",
"=",
"\"ipfs://\"",
"+",
"s",
"return",
"s",
".",
"encode",
"(",
"\"ascii\"",
")",
".",
"ljust",
"(",
"32",
"*",
"(",
"len",
"(",
"s",
")",
"//",
"32",
"+",
"1",
")",
",",
"b\"\\0\"",
")"
] | Convert in and from bytes uri format used in Registry contract | [
"Convert",
"in",
"and",
"from",
"bytes",
"uri",
"format",
"used",
"in",
"Registry",
"contract"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/utils_ipfs.py#L65-L71 | train | 231,810 |
singnet/snet-cli | snet_cli/mpe_treasurer_command.py | MPETreasurerCommand._get_stub_and_request_classes | def _get_stub_and_request_classes(self, service_name):
""" import protobuf and return stub and request class """
# Compile protobuf if needed
codegen_dir = Path.home().joinpath(".snet", "mpe_client", "control_service")
proto_dir = Path(__file__).absolute().parent.joinpath("resources", "proto")
if (not codegen_dir.joinpath("control_service_pb2.py").is_file()):
compile_proto(proto_dir, codegen_dir, proto_file = "control_service.proto")
stub_class, request_class, _ = import_protobuf_from_dir(codegen_dir, service_name)
return stub_class, request_class | python | def _get_stub_and_request_classes(self, service_name):
""" import protobuf and return stub and request class """
# Compile protobuf if needed
codegen_dir = Path.home().joinpath(".snet", "mpe_client", "control_service")
proto_dir = Path(__file__).absolute().parent.joinpath("resources", "proto")
if (not codegen_dir.joinpath("control_service_pb2.py").is_file()):
compile_proto(proto_dir, codegen_dir, proto_file = "control_service.proto")
stub_class, request_class, _ = import_protobuf_from_dir(codegen_dir, service_name)
return stub_class, request_class | [
"def",
"_get_stub_and_request_classes",
"(",
"self",
",",
"service_name",
")",
":",
"# Compile protobuf if needed",
"codegen_dir",
"=",
"Path",
".",
"home",
"(",
")",
".",
"joinpath",
"(",
"\".snet\"",
",",
"\"mpe_client\"",
",",
"\"control_service\"",
")",
"proto_dir",
"=",
"Path",
"(",
"__file__",
")",
".",
"absolute",
"(",
")",
".",
"parent",
".",
"joinpath",
"(",
"\"resources\"",
",",
"\"proto\"",
")",
"if",
"(",
"not",
"codegen_dir",
".",
"joinpath",
"(",
"\"control_service_pb2.py\"",
")",
".",
"is_file",
"(",
")",
")",
":",
"compile_proto",
"(",
"proto_dir",
",",
"codegen_dir",
",",
"proto_file",
"=",
"\"control_service.proto\"",
")",
"stub_class",
",",
"request_class",
",",
"_",
"=",
"import_protobuf_from_dir",
"(",
"codegen_dir",
",",
"service_name",
")",
"return",
"stub_class",
",",
"request_class"
] | import protobuf and return stub and request class | [
"import",
"protobuf",
"and",
"return",
"stub",
"and",
"request",
"class"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_treasurer_command.py#L31-L40 | train | 231,811 |
singnet/snet-cli | snet_cli/mpe_treasurer_command.py | MPETreasurerCommand._start_claim_channels | def _start_claim_channels(self, grpc_channel, channels_ids):
""" Safely run StartClaim for given channels """
unclaimed_payments = self._call_GetListUnclaimed(grpc_channel)
unclaimed_payments_dict = {p["channel_id"] : p for p in unclaimed_payments}
to_claim = []
for channel_id in channels_ids:
if (channel_id not in unclaimed_payments_dict or unclaimed_payments_dict[channel_id]["amount"] == 0):
self._printout("There is nothing to claim for channel %i, we skip it"%channel_id)
continue
blockchain = self._get_channel_state_from_blockchain(channel_id)
if (unclaimed_payments_dict[channel_id]["nonce"] != blockchain["nonce"]):
self._printout("Old payment for channel %i is still in progress. Please run claim for this channel later."%channel_id)
continue
to_claim.append((channel_id, blockchain["nonce"]))
payments = [self._call_StartClaim(grpc_channel, channel_id, nonce) for channel_id, nonce in to_claim]
return payments | python | def _start_claim_channels(self, grpc_channel, channels_ids):
""" Safely run StartClaim for given channels """
unclaimed_payments = self._call_GetListUnclaimed(grpc_channel)
unclaimed_payments_dict = {p["channel_id"] : p for p in unclaimed_payments}
to_claim = []
for channel_id in channels_ids:
if (channel_id not in unclaimed_payments_dict or unclaimed_payments_dict[channel_id]["amount"] == 0):
self._printout("There is nothing to claim for channel %i, we skip it"%channel_id)
continue
blockchain = self._get_channel_state_from_blockchain(channel_id)
if (unclaimed_payments_dict[channel_id]["nonce"] != blockchain["nonce"]):
self._printout("Old payment for channel %i is still in progress. Please run claim for this channel later."%channel_id)
continue
to_claim.append((channel_id, blockchain["nonce"]))
payments = [self._call_StartClaim(grpc_channel, channel_id, nonce) for channel_id, nonce in to_claim]
return payments | [
"def",
"_start_claim_channels",
"(",
"self",
",",
"grpc_channel",
",",
"channels_ids",
")",
":",
"unclaimed_payments",
"=",
"self",
".",
"_call_GetListUnclaimed",
"(",
"grpc_channel",
")",
"unclaimed_payments_dict",
"=",
"{",
"p",
"[",
"\"channel_id\"",
"]",
":",
"p",
"for",
"p",
"in",
"unclaimed_payments",
"}",
"to_claim",
"=",
"[",
"]",
"for",
"channel_id",
"in",
"channels_ids",
":",
"if",
"(",
"channel_id",
"not",
"in",
"unclaimed_payments_dict",
"or",
"unclaimed_payments_dict",
"[",
"channel_id",
"]",
"[",
"\"amount\"",
"]",
"==",
"0",
")",
":",
"self",
".",
"_printout",
"(",
"\"There is nothing to claim for channel %i, we skip it\"",
"%",
"channel_id",
")",
"continue",
"blockchain",
"=",
"self",
".",
"_get_channel_state_from_blockchain",
"(",
"channel_id",
")",
"if",
"(",
"unclaimed_payments_dict",
"[",
"channel_id",
"]",
"[",
"\"nonce\"",
"]",
"!=",
"blockchain",
"[",
"\"nonce\"",
"]",
")",
":",
"self",
".",
"_printout",
"(",
"\"Old payment for channel %i is still in progress. Please run claim for this channel later.\"",
"%",
"channel_id",
")",
"continue",
"to_claim",
".",
"append",
"(",
"(",
"channel_id",
",",
"blockchain",
"[",
"\"nonce\"",
"]",
")",
")",
"payments",
"=",
"[",
"self",
".",
"_call_StartClaim",
"(",
"grpc_channel",
",",
"channel_id",
",",
"nonce",
")",
"for",
"channel_id",
",",
"nonce",
"in",
"to_claim",
"]",
"return",
"payments"
] | Safely run StartClaim for given channels | [
"Safely",
"run",
"StartClaim",
"for",
"given",
"channels"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_treasurer_command.py#L103-L120 | train | 231,812 |
singnet/snet-cli | snet_cli/mpe_treasurer_command.py | MPETreasurerCommand._claim_in_progress_and_claim_channels | def _claim_in_progress_and_claim_channels(self, grpc_channel, channels):
""" Claim all 'pending' payments in progress and after we claim given channels """
# first we get the list of all 'payments in progress' in case we 'lost' some payments.
payments = self._call_GetListInProgress(grpc_channel)
if (len(payments) > 0):
self._printout("There are %i payments in 'progress' (they haven't been claimed in blockchain). We will claim them."%len(payments))
self._blockchain_claim(payments)
payments = self._start_claim_channels(grpc_channel, channels)
self._blockchain_claim(payments) | python | def _claim_in_progress_and_claim_channels(self, grpc_channel, channels):
""" Claim all 'pending' payments in progress and after we claim given channels """
# first we get the list of all 'payments in progress' in case we 'lost' some payments.
payments = self._call_GetListInProgress(grpc_channel)
if (len(payments) > 0):
self._printout("There are %i payments in 'progress' (they haven't been claimed in blockchain). We will claim them."%len(payments))
self._blockchain_claim(payments)
payments = self._start_claim_channels(grpc_channel, channels)
self._blockchain_claim(payments) | [
"def",
"_claim_in_progress_and_claim_channels",
"(",
"self",
",",
"grpc_channel",
",",
"channels",
")",
":",
"# first we get the list of all 'payments in progress' in case we 'lost' some payments.",
"payments",
"=",
"self",
".",
"_call_GetListInProgress",
"(",
"grpc_channel",
")",
"if",
"(",
"len",
"(",
"payments",
")",
">",
"0",
")",
":",
"self",
".",
"_printout",
"(",
"\"There are %i payments in 'progress' (they haven't been claimed in blockchain). We will claim them.\"",
"%",
"len",
"(",
"payments",
")",
")",
"self",
".",
"_blockchain_claim",
"(",
"payments",
")",
"payments",
"=",
"self",
".",
"_start_claim_channels",
"(",
"grpc_channel",
",",
"channels",
")",
"self",
".",
"_blockchain_claim",
"(",
"payments",
")"
] | Claim all 'pending' payments in progress and after we claim given channels | [
"Claim",
"all",
"pending",
"payments",
"in",
"progress",
"and",
"after",
"we",
"claim",
"given",
"channels"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_treasurer_command.py#L122-L130 | train | 231,813 |
singnet/snet-cli | snet_cli/config.py | Config.create_default_config | def create_default_config(self):
""" Create default configuration if config file does not exist """
# make config directory with the minimal possible permission
self._config_file.parent.mkdir(mode=0o700, exist_ok=True)
self["network.kovan"] = {"default_eth_rpc_endpoint": "https://kovan.infura.io", "default_gas_price" : "medium"}
self["network.mainnet"] = {"default_eth_rpc_endpoint": "https://mainnet.infura.io", "default_gas_price" : "medium"}
self["network.ropsten"] = {"default_eth_rpc_endpoint": "https://ropsten.infura.io", "default_gas_price" : "medium"}
self["network.rinkeby"] = {"default_eth_rpc_endpoint": "https://rinkeby.infura.io", "default_gas_price" : "medium"}
self["ipfs"] = {"default_ipfs_endpoint": "http://ipfs.singularitynet.io:80"}
self["session"] = {
"network": "kovan" }
self._persist()
print("We've created configuration file with default values in: %s\n"%str(self._config_file)) | python | def create_default_config(self):
""" Create default configuration if config file does not exist """
# make config directory with the minimal possible permission
self._config_file.parent.mkdir(mode=0o700, exist_ok=True)
self["network.kovan"] = {"default_eth_rpc_endpoint": "https://kovan.infura.io", "default_gas_price" : "medium"}
self["network.mainnet"] = {"default_eth_rpc_endpoint": "https://mainnet.infura.io", "default_gas_price" : "medium"}
self["network.ropsten"] = {"default_eth_rpc_endpoint": "https://ropsten.infura.io", "default_gas_price" : "medium"}
self["network.rinkeby"] = {"default_eth_rpc_endpoint": "https://rinkeby.infura.io", "default_gas_price" : "medium"}
self["ipfs"] = {"default_ipfs_endpoint": "http://ipfs.singularitynet.io:80"}
self["session"] = {
"network": "kovan" }
self._persist()
print("We've created configuration file with default values in: %s\n"%str(self._config_file)) | [
"def",
"create_default_config",
"(",
"self",
")",
":",
"# make config directory with the minimal possible permission",
"self",
".",
"_config_file",
".",
"parent",
".",
"mkdir",
"(",
"mode",
"=",
"0o700",
",",
"exist_ok",
"=",
"True",
")",
"self",
"[",
"\"network.kovan\"",
"]",
"=",
"{",
"\"default_eth_rpc_endpoint\"",
":",
"\"https://kovan.infura.io\"",
",",
"\"default_gas_price\"",
":",
"\"medium\"",
"}",
"self",
"[",
"\"network.mainnet\"",
"]",
"=",
"{",
"\"default_eth_rpc_endpoint\"",
":",
"\"https://mainnet.infura.io\"",
",",
"\"default_gas_price\"",
":",
"\"medium\"",
"}",
"self",
"[",
"\"network.ropsten\"",
"]",
"=",
"{",
"\"default_eth_rpc_endpoint\"",
":",
"\"https://ropsten.infura.io\"",
",",
"\"default_gas_price\"",
":",
"\"medium\"",
"}",
"self",
"[",
"\"network.rinkeby\"",
"]",
"=",
"{",
"\"default_eth_rpc_endpoint\"",
":",
"\"https://rinkeby.infura.io\"",
",",
"\"default_gas_price\"",
":",
"\"medium\"",
"}",
"self",
"[",
"\"ipfs\"",
"]",
"=",
"{",
"\"default_ipfs_endpoint\"",
":",
"\"http://ipfs.singularitynet.io:80\"",
"}",
"self",
"[",
"\"session\"",
"]",
"=",
"{",
"\"network\"",
":",
"\"kovan\"",
"}",
"self",
".",
"_persist",
"(",
")",
"print",
"(",
"\"We've created configuration file with default values in: %s\\n\"",
"%",
"str",
"(",
"self",
".",
"_config_file",
")",
")"
] | Create default configuration if config file does not exist | [
"Create",
"default",
"configuration",
"if",
"config",
"file",
"does",
"not",
"exist"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/config.py#L175-L187 | train | 231,814 |
singnet/snet-cli | snet_cli/utils_proto.py | switch_to_json_payload_encoding | def switch_to_json_payload_encoding(call_fn, response_class):
""" Switch payload encoding to JSON for GRPC call """
def json_serializer(*args, **kwargs):
return bytes(json_format.MessageToJson(args[0], True, preserving_proto_field_name=True), "utf-8")
def json_deserializer(*args, **kwargs):
resp = response_class()
json_format.Parse(args[0], resp, True)
return resp
call_fn._request_serializer = json_serializer
call_fn._response_deserializer = json_deserializer | python | def switch_to_json_payload_encoding(call_fn, response_class):
""" Switch payload encoding to JSON for GRPC call """
def json_serializer(*args, **kwargs):
return bytes(json_format.MessageToJson(args[0], True, preserving_proto_field_name=True), "utf-8")
def json_deserializer(*args, **kwargs):
resp = response_class()
json_format.Parse(args[0], resp, True)
return resp
call_fn._request_serializer = json_serializer
call_fn._response_deserializer = json_deserializer | [
"def",
"switch_to_json_payload_encoding",
"(",
"call_fn",
",",
"response_class",
")",
":",
"def",
"json_serializer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"bytes",
"(",
"json_format",
".",
"MessageToJson",
"(",
"args",
"[",
"0",
"]",
",",
"True",
",",
"preserving_proto_field_name",
"=",
"True",
")",
",",
"\"utf-8\"",
")",
"def",
"json_deserializer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"response_class",
"(",
")",
"json_format",
".",
"Parse",
"(",
"args",
"[",
"0",
"]",
",",
"resp",
",",
"True",
")",
"return",
"resp",
"call_fn",
".",
"_request_serializer",
"=",
"json_serializer",
"call_fn",
".",
"_response_deserializer",
"=",
"json_deserializer"
] | Switch payload encoding to JSON for GRPC call | [
"Switch",
"payload",
"encoding",
"to",
"JSON",
"for",
"GRPC",
"call"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/utils_proto.py#L72-L81 | train | 231,815 |
singnet/snet-cli | snet_cli/mpe_account_command.py | MPEAccountCommand.print_agi_and_mpe_balances | def print_agi_and_mpe_balances(self):
""" Print balance of ETH, AGI, and MPE wallet """
if (self.args.account):
account = self.args.account
else:
account = self.ident.address
eth_wei = self.w3.eth.getBalance(account)
agi_cogs = self.call_contract_command("SingularityNetToken", "balanceOf", [account])
mpe_cogs = self.call_contract_command("MultiPartyEscrow", "balances", [account])
# we cannot use _pprint here because it doesn't conserve order yet
self._printout(" account: %s"%account)
self._printout(" ETH: %s"%self.w3.fromWei(eth_wei, 'ether'))
self._printout(" AGI: %s"%cogs2stragi(agi_cogs))
self._printout(" MPE: %s"%cogs2stragi(mpe_cogs)) | python | def print_agi_and_mpe_balances(self):
""" Print balance of ETH, AGI, and MPE wallet """
if (self.args.account):
account = self.args.account
else:
account = self.ident.address
eth_wei = self.w3.eth.getBalance(account)
agi_cogs = self.call_contract_command("SingularityNetToken", "balanceOf", [account])
mpe_cogs = self.call_contract_command("MultiPartyEscrow", "balances", [account])
# we cannot use _pprint here because it doesn't conserve order yet
self._printout(" account: %s"%account)
self._printout(" ETH: %s"%self.w3.fromWei(eth_wei, 'ether'))
self._printout(" AGI: %s"%cogs2stragi(agi_cogs))
self._printout(" MPE: %s"%cogs2stragi(mpe_cogs)) | [
"def",
"print_agi_and_mpe_balances",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"args",
".",
"account",
")",
":",
"account",
"=",
"self",
".",
"args",
".",
"account",
"else",
":",
"account",
"=",
"self",
".",
"ident",
".",
"address",
"eth_wei",
"=",
"self",
".",
"w3",
".",
"eth",
".",
"getBalance",
"(",
"account",
")",
"agi_cogs",
"=",
"self",
".",
"call_contract_command",
"(",
"\"SingularityNetToken\"",
",",
"\"balanceOf\"",
",",
"[",
"account",
"]",
")",
"mpe_cogs",
"=",
"self",
".",
"call_contract_command",
"(",
"\"MultiPartyEscrow\"",
",",
"\"balances\"",
",",
"[",
"account",
"]",
")",
"# we cannot use _pprint here because it doesn't conserve order yet",
"self",
".",
"_printout",
"(",
"\" account: %s\"",
"%",
"account",
")",
"self",
".",
"_printout",
"(",
"\" ETH: %s\"",
"%",
"self",
".",
"w3",
".",
"fromWei",
"(",
"eth_wei",
",",
"'ether'",
")",
")",
"self",
".",
"_printout",
"(",
"\" AGI: %s\"",
"%",
"cogs2stragi",
"(",
"agi_cogs",
")",
")",
"self",
".",
"_printout",
"(",
"\" MPE: %s\"",
"%",
"cogs2stragi",
"(",
"mpe_cogs",
")",
")"
] | Print balance of ETH, AGI, and MPE wallet | [
"Print",
"balance",
"of",
"ETH",
"AGI",
"and",
"MPE",
"wallet"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_account_command.py#L10-L24 | train | 231,816 |
singnet/snet-cli | snet_cli/mpe_service_command.py | MPEServiceCommand.publish_proto_in_ipfs | def publish_proto_in_ipfs(self):
""" Publish proto files in ipfs and print hash """
ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs(self._get_ipfs_client(), self.args.protodir)
self._printout(ipfs_hash_base58) | python | def publish_proto_in_ipfs(self):
""" Publish proto files in ipfs and print hash """
ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs(self._get_ipfs_client(), self.args.protodir)
self._printout(ipfs_hash_base58) | [
"def",
"publish_proto_in_ipfs",
"(",
"self",
")",
":",
"ipfs_hash_base58",
"=",
"utils_ipfs",
".",
"publish_proto_in_ipfs",
"(",
"self",
".",
"_get_ipfs_client",
"(",
")",
",",
"self",
".",
"args",
".",
"protodir",
")",
"self",
".",
"_printout",
"(",
"ipfs_hash_base58",
")"
] | Publish proto files in ipfs and print hash | [
"Publish",
"proto",
"files",
"in",
"ipfs",
"and",
"print",
"hash"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_command.py#L15-L18 | train | 231,817 |
singnet/snet-cli | snet_cli/mpe_service_command.py | MPEServiceCommand.publish_proto_metadata_update | def publish_proto_metadata_update(self):
""" Publish protobuf model in ipfs and update existing metadata file """
metadata = load_mpe_service_metadata(self.args.metadata_file)
ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs(self._get_ipfs_client(), self.args.protodir)
metadata.set_simple_field("model_ipfs_hash", ipfs_hash_base58)
metadata.save_pretty(self.args.metadata_file) | python | def publish_proto_metadata_update(self):
""" Publish protobuf model in ipfs and update existing metadata file """
metadata = load_mpe_service_metadata(self.args.metadata_file)
ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs(self._get_ipfs_client(), self.args.protodir)
metadata.set_simple_field("model_ipfs_hash", ipfs_hash_base58)
metadata.save_pretty(self.args.metadata_file) | [
"def",
"publish_proto_metadata_update",
"(",
"self",
")",
":",
"metadata",
"=",
"load_mpe_service_metadata",
"(",
"self",
".",
"args",
".",
"metadata_file",
")",
"ipfs_hash_base58",
"=",
"utils_ipfs",
".",
"publish_proto_in_ipfs",
"(",
"self",
".",
"_get_ipfs_client",
"(",
")",
",",
"self",
".",
"args",
".",
"protodir",
")",
"metadata",
".",
"set_simple_field",
"(",
"\"model_ipfs_hash\"",
",",
"ipfs_hash_base58",
")",
"metadata",
".",
"save_pretty",
"(",
"self",
".",
"args",
".",
"metadata_file",
")"
] | Publish protobuf model in ipfs and update existing metadata file | [
"Publish",
"protobuf",
"model",
"in",
"ipfs",
"and",
"update",
"existing",
"metadata",
"file"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_service_command.py#L37-L42 | train | 231,818 |
singnet/snet-cli | snet_cli/mpe_channel_command.py | MPEChannelCommand._get_persistent_mpe_dir | def _get_persistent_mpe_dir(self):
""" get persistent storage for mpe """
mpe_address = self.get_mpe_address().lower()
registry_address = self.get_registry_address().lower()
return Path.home().joinpath(".snet", "mpe_client", "%s_%s"%(mpe_address, registry_address)) | python | def _get_persistent_mpe_dir(self):
""" get persistent storage for mpe """
mpe_address = self.get_mpe_address().lower()
registry_address = self.get_registry_address().lower()
return Path.home().joinpath(".snet", "mpe_client", "%s_%s"%(mpe_address, registry_address)) | [
"def",
"_get_persistent_mpe_dir",
"(",
"self",
")",
":",
"mpe_address",
"=",
"self",
".",
"get_mpe_address",
"(",
")",
".",
"lower",
"(",
")",
"registry_address",
"=",
"self",
".",
"get_registry_address",
"(",
")",
".",
"lower",
"(",
")",
"return",
"Path",
".",
"home",
"(",
")",
".",
"joinpath",
"(",
"\".snet\"",
",",
"\"mpe_client\"",
",",
"\"%s_%s\"",
"%",
"(",
"mpe_address",
",",
"registry_address",
")",
")"
] | get persistent storage for mpe | [
"get",
"persistent",
"storage",
"for",
"mpe"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_channel_command.py#L21-L25 | train | 231,819 |
singnet/snet-cli | snet_cli/mpe_channel_command.py | MPEChannelCommand._check_mpe_address_metadata | def _check_mpe_address_metadata(self, metadata):
""" we make sure that MultiPartyEscrow address from metadata is correct """
mpe_address = self.get_mpe_address()
if (str(mpe_address).lower() != str(metadata["mpe_address"]).lower()):
raise Exception("MultiPartyEscrow contract address from metadata %s do not correspond to current MultiPartyEscrow address %s"%(metadata["mpe_address"], mpe_address)) | python | def _check_mpe_address_metadata(self, metadata):
""" we make sure that MultiPartyEscrow address from metadata is correct """
mpe_address = self.get_mpe_address()
if (str(mpe_address).lower() != str(metadata["mpe_address"]).lower()):
raise Exception("MultiPartyEscrow contract address from metadata %s do not correspond to current MultiPartyEscrow address %s"%(metadata["mpe_address"], mpe_address)) | [
"def",
"_check_mpe_address_metadata",
"(",
"self",
",",
"metadata",
")",
":",
"mpe_address",
"=",
"self",
".",
"get_mpe_address",
"(",
")",
"if",
"(",
"str",
"(",
"mpe_address",
")",
".",
"lower",
"(",
")",
"!=",
"str",
"(",
"metadata",
"[",
"\"mpe_address\"",
"]",
")",
".",
"lower",
"(",
")",
")",
":",
"raise",
"Exception",
"(",
"\"MultiPartyEscrow contract address from metadata %s do not correspond to current MultiPartyEscrow address %s\"",
"%",
"(",
"metadata",
"[",
"\"mpe_address\"",
"]",
",",
"mpe_address",
")",
")"
] | we make sure that MultiPartyEscrow address from metadata is correct | [
"we",
"make",
"sure",
"that",
"MultiPartyEscrow",
"address",
"from",
"metadata",
"is",
"correct"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_channel_command.py#L74-L78 | train | 231,820 |
singnet/snet-cli | snet_cli/mpe_channel_command.py | MPEChannelCommand._init_or_update_registered_service_if_needed | def _init_or_update_registered_service_if_needed(self):
'''
similar to _init_or_update_service_if_needed but we get service_registraion from registry,
so we can update only registered services
'''
if (self.is_service_initialized()):
old_reg = self._read_service_info(self.args.org_id, self.args.service_id)
# metadataURI will be in old_reg only for service which was initilized from registry (not from metadata)
# we do nothing for services which were initilized from metadata
if ("metadataURI" not in old_reg):
return
service_registration = self._get_service_registration()
# if metadataURI hasn't been changed we do nothing
if (not self.is_metadataURI_has_changed(service_registration)):
return
else:
service_registration = self._get_service_registration()
service_metadata = self._get_service_metadata_from_registry()
self._init_or_update_service_if_needed(service_metadata, service_registration) | python | def _init_or_update_registered_service_if_needed(self):
'''
similar to _init_or_update_service_if_needed but we get service_registraion from registry,
so we can update only registered services
'''
if (self.is_service_initialized()):
old_reg = self._read_service_info(self.args.org_id, self.args.service_id)
# metadataURI will be in old_reg only for service which was initilized from registry (not from metadata)
# we do nothing for services which were initilized from metadata
if ("metadataURI" not in old_reg):
return
service_registration = self._get_service_registration()
# if metadataURI hasn't been changed we do nothing
if (not self.is_metadataURI_has_changed(service_registration)):
return
else:
service_registration = self._get_service_registration()
service_metadata = self._get_service_metadata_from_registry()
self._init_or_update_service_if_needed(service_metadata, service_registration) | [
"def",
"_init_or_update_registered_service_if_needed",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"is_service_initialized",
"(",
")",
")",
":",
"old_reg",
"=",
"self",
".",
"_read_service_info",
"(",
"self",
".",
"args",
".",
"org_id",
",",
"self",
".",
"args",
".",
"service_id",
")",
"# metadataURI will be in old_reg only for service which was initilized from registry (not from metadata)",
"# we do nothing for services which were initilized from metadata",
"if",
"(",
"\"metadataURI\"",
"not",
"in",
"old_reg",
")",
":",
"return",
"service_registration",
"=",
"self",
".",
"_get_service_registration",
"(",
")",
"# if metadataURI hasn't been changed we do nothing",
"if",
"(",
"not",
"self",
".",
"is_metadataURI_has_changed",
"(",
"service_registration",
")",
")",
":",
"return",
"else",
":",
"service_registration",
"=",
"self",
".",
"_get_service_registration",
"(",
")",
"service_metadata",
"=",
"self",
".",
"_get_service_metadata_from_registry",
"(",
")",
"self",
".",
"_init_or_update_service_if_needed",
"(",
"service_metadata",
",",
"service_registration",
")"
] | similar to _init_or_update_service_if_needed but we get service_registraion from registry,
so we can update only registered services | [
"similar",
"to",
"_init_or_update_service_if_needed",
"but",
"we",
"get",
"service_registraion",
"from",
"registry",
"so",
"we",
"can",
"update",
"only",
"registered",
"services"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_channel_command.py#L115-L136 | train | 231,821 |
singnet/snet-cli | snet_cli/mpe_channel_command.py | MPEChannelCommand._smart_get_initialized_channel_for_service | def _smart_get_initialized_channel_for_service(self, metadata, filter_by, is_try_initailize = True):
'''
- filter_by can be sender or signer
'''
channels = self._get_initialized_channels_for_service(self.args.org_id, self.args.service_id)
group_id = metadata.get_group_id(self.args.group_name)
channels = [c for c in channels if c[filter_by].lower() == self.ident.address.lower() and c["groupId"] == group_id]
if (len(channels) == 0 and is_try_initailize):
# this will work only in simple case where signer == sender
self._initialize_already_opened_channel(metadata, self.ident.address, self.ident.address)
return self._smart_get_initialized_channel_for_service(metadata, filter_by, is_try_initailize = False)
if (len(channels) == 0):
raise Exception("Cannot find initialized channel for service with org_id=%s service_id=%s and signer=%s"%(self.args.org_id, self.args.service_id, self.ident.address))
if (self.args.channel_id is None):
if (len(channels) > 1):
channel_ids = [channel["channelId"] for channel in channels]
raise Exception("We have several initialized channel: %s. You should use --channel-id to select one"%str(channel_ids))
return channels[0]
for channel in channels:
if (channel["channelId"] == self.args.channel_id):
return channel
raise Exception("Channel %i has not been initialized or your are not the sender/signer of it"%self.args.channel_id) | python | def _smart_get_initialized_channel_for_service(self, metadata, filter_by, is_try_initailize = True):
'''
- filter_by can be sender or signer
'''
channels = self._get_initialized_channels_for_service(self.args.org_id, self.args.service_id)
group_id = metadata.get_group_id(self.args.group_name)
channels = [c for c in channels if c[filter_by].lower() == self.ident.address.lower() and c["groupId"] == group_id]
if (len(channels) == 0 and is_try_initailize):
# this will work only in simple case where signer == sender
self._initialize_already_opened_channel(metadata, self.ident.address, self.ident.address)
return self._smart_get_initialized_channel_for_service(metadata, filter_by, is_try_initailize = False)
if (len(channels) == 0):
raise Exception("Cannot find initialized channel for service with org_id=%s service_id=%s and signer=%s"%(self.args.org_id, self.args.service_id, self.ident.address))
if (self.args.channel_id is None):
if (len(channels) > 1):
channel_ids = [channel["channelId"] for channel in channels]
raise Exception("We have several initialized channel: %s. You should use --channel-id to select one"%str(channel_ids))
return channels[0]
for channel in channels:
if (channel["channelId"] == self.args.channel_id):
return channel
raise Exception("Channel %i has not been initialized or your are not the sender/signer of it"%self.args.channel_id) | [
"def",
"_smart_get_initialized_channel_for_service",
"(",
"self",
",",
"metadata",
",",
"filter_by",
",",
"is_try_initailize",
"=",
"True",
")",
":",
"channels",
"=",
"self",
".",
"_get_initialized_channels_for_service",
"(",
"self",
".",
"args",
".",
"org_id",
",",
"self",
".",
"args",
".",
"service_id",
")",
"group_id",
"=",
"metadata",
".",
"get_group_id",
"(",
"self",
".",
"args",
".",
"group_name",
")",
"channels",
"=",
"[",
"c",
"for",
"c",
"in",
"channels",
"if",
"c",
"[",
"filter_by",
"]",
".",
"lower",
"(",
")",
"==",
"self",
".",
"ident",
".",
"address",
".",
"lower",
"(",
")",
"and",
"c",
"[",
"\"groupId\"",
"]",
"==",
"group_id",
"]",
"if",
"(",
"len",
"(",
"channels",
")",
"==",
"0",
"and",
"is_try_initailize",
")",
":",
"# this will work only in simple case where signer == sender",
"self",
".",
"_initialize_already_opened_channel",
"(",
"metadata",
",",
"self",
".",
"ident",
".",
"address",
",",
"self",
".",
"ident",
".",
"address",
")",
"return",
"self",
".",
"_smart_get_initialized_channel_for_service",
"(",
"metadata",
",",
"filter_by",
",",
"is_try_initailize",
"=",
"False",
")",
"if",
"(",
"len",
"(",
"channels",
")",
"==",
"0",
")",
":",
"raise",
"Exception",
"(",
"\"Cannot find initialized channel for service with org_id=%s service_id=%s and signer=%s\"",
"%",
"(",
"self",
".",
"args",
".",
"org_id",
",",
"self",
".",
"args",
".",
"service_id",
",",
"self",
".",
"ident",
".",
"address",
")",
")",
"if",
"(",
"self",
".",
"args",
".",
"channel_id",
"is",
"None",
")",
":",
"if",
"(",
"len",
"(",
"channels",
")",
">",
"1",
")",
":",
"channel_ids",
"=",
"[",
"channel",
"[",
"\"channelId\"",
"]",
"for",
"channel",
"in",
"channels",
"]",
"raise",
"Exception",
"(",
"\"We have several initialized channel: %s. You should use --channel-id to select one\"",
"%",
"str",
"(",
"channel_ids",
")",
")",
"return",
"channels",
"[",
"0",
"]",
"for",
"channel",
"in",
"channels",
":",
"if",
"(",
"channel",
"[",
"\"channelId\"",
"]",
"==",
"self",
".",
"args",
".",
"channel_id",
")",
":",
"return",
"channel",
"raise",
"Exception",
"(",
"\"Channel %i has not been initialized or your are not the sender/signer of it\"",
"%",
"self",
".",
"args",
".",
"channel_id",
")"
] | - filter_by can be sender or signer | [
"-",
"filter_by",
"can",
"be",
"sender",
"or",
"signer"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_channel_command.py#L297-L320 | train | 231,822 |
singnet/snet-cli | snet_cli/mpe_channel_command.py | MPEChannelCommand._get_all_filtered_channels | def _get_all_filtered_channels(self, topics_without_signature):
""" get all filtered chanels from blockchain logs """
mpe_address = self.get_mpe_address()
event_signature = self.ident.w3.sha3(text="ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)").hex()
topics = [event_signature] + topics_without_signature
logs = self.ident.w3.eth.getLogs({"fromBlock" : self.args.from_block, "address" : mpe_address, "topics" : topics})
abi = get_contract_def("MultiPartyEscrow")
event_abi = abi_get_element_by_name(abi, "ChannelOpen")
channels_ids = [get_event_data(event_abi, l)["args"]["channelId"] for l in logs]
return channels_ids | python | def _get_all_filtered_channels(self, topics_without_signature):
""" get all filtered chanels from blockchain logs """
mpe_address = self.get_mpe_address()
event_signature = self.ident.w3.sha3(text="ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)").hex()
topics = [event_signature] + topics_without_signature
logs = self.ident.w3.eth.getLogs({"fromBlock" : self.args.from_block, "address" : mpe_address, "topics" : topics})
abi = get_contract_def("MultiPartyEscrow")
event_abi = abi_get_element_by_name(abi, "ChannelOpen")
channels_ids = [get_event_data(event_abi, l)["args"]["channelId"] for l in logs]
return channels_ids | [
"def",
"_get_all_filtered_channels",
"(",
"self",
",",
"topics_without_signature",
")",
":",
"mpe_address",
"=",
"self",
".",
"get_mpe_address",
"(",
")",
"event_signature",
"=",
"self",
".",
"ident",
".",
"w3",
".",
"sha3",
"(",
"text",
"=",
"\"ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)\"",
")",
".",
"hex",
"(",
")",
"topics",
"=",
"[",
"event_signature",
"]",
"+",
"topics_without_signature",
"logs",
"=",
"self",
".",
"ident",
".",
"w3",
".",
"eth",
".",
"getLogs",
"(",
"{",
"\"fromBlock\"",
":",
"self",
".",
"args",
".",
"from_block",
",",
"\"address\"",
":",
"mpe_address",
",",
"\"topics\"",
":",
"topics",
"}",
")",
"abi",
"=",
"get_contract_def",
"(",
"\"MultiPartyEscrow\"",
")",
"event_abi",
"=",
"abi_get_element_by_name",
"(",
"abi",
",",
"\"ChannelOpen\"",
")",
"channels_ids",
"=",
"[",
"get_event_data",
"(",
"event_abi",
",",
"l",
")",
"[",
"\"args\"",
"]",
"[",
"\"channelId\"",
"]",
"for",
"l",
"in",
"logs",
"]",
"return",
"channels_ids"
] | get all filtered chanels from blockchain logs | [
"get",
"all",
"filtered",
"chanels",
"from",
"blockchain",
"logs"
] | 1b5ac98cb9a64211c861ead9fcfe6208f2749032 | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/mpe_channel_command.py#L415-L424 | train | 231,823 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.list_repo | def list_repo(self):
"""
Returns info about all Repos.
"""
req = proto.ListRepoRequest()
res = self.stub.ListRepo(req, metadata=self.metadata)
if hasattr(res, 'repo_info'):
return res.repo_info
return [] | python | def list_repo(self):
"""
Returns info about all Repos.
"""
req = proto.ListRepoRequest()
res = self.stub.ListRepo(req, metadata=self.metadata)
if hasattr(res, 'repo_info'):
return res.repo_info
return [] | [
"def",
"list_repo",
"(",
"self",
")",
":",
"req",
"=",
"proto",
".",
"ListRepoRequest",
"(",
")",
"res",
"=",
"self",
".",
"stub",
".",
"ListRepo",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"if",
"hasattr",
"(",
"res",
",",
"'repo_info'",
")",
":",
"return",
"res",
".",
"repo_info",
"return",
"[",
"]"
] | Returns info about all Repos. | [
"Returns",
"info",
"about",
"all",
"Repos",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L71-L79 | train | 231,824 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.delete_repo | def delete_repo(self, repo_name=None, force=False, all=False):
"""
Deletes a repo and reclaims the storage space it was using.
Params:
* repo_name: The name of the repo.
* force: If set to true, the repo will be removed regardless of
errors. This argument should be used with care.
* all: Delete all repos.
"""
if not all:
if repo_name:
req = proto.DeleteRepoRequest(repo=proto.Repo(name=repo_name), force=force)
self.stub.DeleteRepo(req, metadata=self.metadata)
else:
raise ValueError("Either a repo_name or all=True needs to be provided")
else:
if not repo_name:
req = proto.DeleteRepoRequest(force=force, all=all)
self.stub.DeleteRepo(req, metadata=self.metadata)
else:
raise ValueError("Cannot specify a repo_name if all=True") | python | def delete_repo(self, repo_name=None, force=False, all=False):
"""
Deletes a repo and reclaims the storage space it was using.
Params:
* repo_name: The name of the repo.
* force: If set to true, the repo will be removed regardless of
errors. This argument should be used with care.
* all: Delete all repos.
"""
if not all:
if repo_name:
req = proto.DeleteRepoRequest(repo=proto.Repo(name=repo_name), force=force)
self.stub.DeleteRepo(req, metadata=self.metadata)
else:
raise ValueError("Either a repo_name or all=True needs to be provided")
else:
if not repo_name:
req = proto.DeleteRepoRequest(force=force, all=all)
self.stub.DeleteRepo(req, metadata=self.metadata)
else:
raise ValueError("Cannot specify a repo_name if all=True") | [
"def",
"delete_repo",
"(",
"self",
",",
"repo_name",
"=",
"None",
",",
"force",
"=",
"False",
",",
"all",
"=",
"False",
")",
":",
"if",
"not",
"all",
":",
"if",
"repo_name",
":",
"req",
"=",
"proto",
".",
"DeleteRepoRequest",
"(",
"repo",
"=",
"proto",
".",
"Repo",
"(",
"name",
"=",
"repo_name",
")",
",",
"force",
"=",
"force",
")",
"self",
".",
"stub",
".",
"DeleteRepo",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Either a repo_name or all=True needs to be provided\"",
")",
"else",
":",
"if",
"not",
"repo_name",
":",
"req",
"=",
"proto",
".",
"DeleteRepoRequest",
"(",
"force",
"=",
"force",
",",
"all",
"=",
"all",
")",
"self",
".",
"stub",
".",
"DeleteRepo",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Cannot specify a repo_name if all=True\"",
")"
] | Deletes a repo and reclaims the storage space it was using.
Params:
* repo_name: The name of the repo.
* force: If set to true, the repo will be removed regardless of
errors. This argument should be used with care.
* all: Delete all repos. | [
"Deletes",
"a",
"repo",
"and",
"reclaims",
"the",
"storage",
"space",
"it",
"was",
"using",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L81-L102 | train | 231,825 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.start_commit | def start_commit(self, repo_name, branch=None, parent=None, description=None):
"""
Begins the process of committing data to a Repo. Once started you can
write to the Commit with PutFile and when all the data has been
written you must finish the Commit with FinishCommit. NOTE, data is
not persisted until FinishCommit is called. A Commit object is
returned.
Params:
* repo_name: The name of the repo.
* branch: A more convenient way to build linear chains of commits.
When a commit is started with a non-empty branch the value of branch
becomes an alias for the created Commit. This enables a more intuitive
access pattern. When the commit is started on a branch the previous
head of the branch is used as the parent of the commit.
* parent: Specifies the parent Commit, upon creation the new Commit
will appear identical to the parent Commit, data can safely be added
to the new commit without affecting the contents of the parent Commit.
You may pass "" as parentCommit in which case the new Commit will have
no parent and will initially appear empty.
* description: (optional) explanation of the commit for clarity.
"""
req = proto.StartCommitRequest(parent=proto.Commit(repo=proto.Repo(name=repo_name), id=parent), branch=branch,
description=description)
res = self.stub.StartCommit(req, metadata=self.metadata)
return res | python | def start_commit(self, repo_name, branch=None, parent=None, description=None):
"""
Begins the process of committing data to a Repo. Once started you can
write to the Commit with PutFile and when all the data has been
written you must finish the Commit with FinishCommit. NOTE, data is
not persisted until FinishCommit is called. A Commit object is
returned.
Params:
* repo_name: The name of the repo.
* branch: A more convenient way to build linear chains of commits.
When a commit is started with a non-empty branch the value of branch
becomes an alias for the created Commit. This enables a more intuitive
access pattern. When the commit is started on a branch the previous
head of the branch is used as the parent of the commit.
* parent: Specifies the parent Commit, upon creation the new Commit
will appear identical to the parent Commit, data can safely be added
to the new commit without affecting the contents of the parent Commit.
You may pass "" as parentCommit in which case the new Commit will have
no parent and will initially appear empty.
* description: (optional) explanation of the commit for clarity.
"""
req = proto.StartCommitRequest(parent=proto.Commit(repo=proto.Repo(name=repo_name), id=parent), branch=branch,
description=description)
res = self.stub.StartCommit(req, metadata=self.metadata)
return res | [
"def",
"start_commit",
"(",
"self",
",",
"repo_name",
",",
"branch",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"req",
"=",
"proto",
".",
"StartCommitRequest",
"(",
"parent",
"=",
"proto",
".",
"Commit",
"(",
"repo",
"=",
"proto",
".",
"Repo",
"(",
"name",
"=",
"repo_name",
")",
",",
"id",
"=",
"parent",
")",
",",
"branch",
"=",
"branch",
",",
"description",
"=",
"description",
")",
"res",
"=",
"self",
".",
"stub",
".",
"StartCommit",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"return",
"res"
] | Begins the process of committing data to a Repo. Once started you can
write to the Commit with PutFile and when all the data has been
written you must finish the Commit with FinishCommit. NOTE, data is
not persisted until FinishCommit is called. A Commit object is
returned.
Params:
* repo_name: The name of the repo.
* branch: A more convenient way to build linear chains of commits.
When a commit is started with a non-empty branch the value of branch
becomes an alias for the created Commit. This enables a more intuitive
access pattern. When the commit is started on a branch the previous
head of the branch is used as the parent of the commit.
* parent: Specifies the parent Commit, upon creation the new Commit
will appear identical to the parent Commit, data can safely be added
to the new commit without affecting the contents of the parent Commit.
You may pass "" as parentCommit in which case the new Commit will have
no parent and will initially appear empty.
* description: (optional) explanation of the commit for clarity. | [
"Begins",
"the",
"process",
"of",
"committing",
"data",
"to",
"a",
"Repo",
".",
"Once",
"started",
"you",
"can",
"write",
"to",
"the",
"Commit",
"with",
"PutFile",
"and",
"when",
"all",
"the",
"data",
"has",
"been",
"written",
"you",
"must",
"finish",
"the",
"Commit",
"with",
"FinishCommit",
".",
"NOTE",
"data",
"is",
"not",
"persisted",
"until",
"FinishCommit",
"is",
"called",
".",
"A",
"Commit",
"object",
"is",
"returned",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L104-L129 | train | 231,826 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.finish_commit | def finish_commit(self, commit):
"""
Ends the process of committing data to a Repo and persists the
Commit. Once a Commit is finished the data becomes immutable and
future attempts to write to it with PutFile will error.
Params:
* commit: A tuple, string, or Commit object representing the commit.
"""
req = proto.FinishCommitRequest(commit=commit_from(commit))
res = self.stub.FinishCommit(req, metadata=self.metadata)
return res | python | def finish_commit(self, commit):
"""
Ends the process of committing data to a Repo and persists the
Commit. Once a Commit is finished the data becomes immutable and
future attempts to write to it with PutFile will error.
Params:
* commit: A tuple, string, or Commit object representing the commit.
"""
req = proto.FinishCommitRequest(commit=commit_from(commit))
res = self.stub.FinishCommit(req, metadata=self.metadata)
return res | [
"def",
"finish_commit",
"(",
"self",
",",
"commit",
")",
":",
"req",
"=",
"proto",
".",
"FinishCommitRequest",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
")",
"res",
"=",
"self",
".",
"stub",
".",
"FinishCommit",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"return",
"res"
] | Ends the process of committing data to a Repo and persists the
Commit. Once a Commit is finished the data becomes immutable and
future attempts to write to it with PutFile will error.
Params:
* commit: A tuple, string, or Commit object representing the commit. | [
"Ends",
"the",
"process",
"of",
"committing",
"data",
"to",
"a",
"Repo",
"and",
"persists",
"the",
"Commit",
".",
"Once",
"a",
"Commit",
"is",
"finished",
"the",
"data",
"becomes",
"immutable",
"and",
"future",
"attempts",
"to",
"write",
"to",
"it",
"with",
"PutFile",
"will",
"error",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L131-L142 | train | 231,827 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.commit | def commit(self, repo_name, branch=None, parent=None, description=None):
"""A context manager for doing stuff inside a commit."""
commit = self.start_commit(repo_name, branch, parent, description)
try:
yield commit
except Exception as e:
print("An exception occurred during an open commit. "
"Trying to finish it (Currently a commit can't be cancelled)")
raise e
finally:
self.finish_commit(commit) | python | def commit(self, repo_name, branch=None, parent=None, description=None):
"""A context manager for doing stuff inside a commit."""
commit = self.start_commit(repo_name, branch, parent, description)
try:
yield commit
except Exception as e:
print("An exception occurred during an open commit. "
"Trying to finish it (Currently a commit can't be cancelled)")
raise e
finally:
self.finish_commit(commit) | [
"def",
"commit",
"(",
"self",
",",
"repo_name",
",",
"branch",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"commit",
"=",
"self",
".",
"start_commit",
"(",
"repo_name",
",",
"branch",
",",
"parent",
",",
"description",
")",
"try",
":",
"yield",
"commit",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"An exception occurred during an open commit. \"",
"\"Trying to finish it (Currently a commit can't be cancelled)\"",
")",
"raise",
"e",
"finally",
":",
"self",
".",
"finish_commit",
"(",
"commit",
")"
] | A context manager for doing stuff inside a commit. | [
"A",
"context",
"manager",
"for",
"doing",
"stuff",
"inside",
"a",
"commit",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L145-L155 | train | 231,828 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.inspect_commit | def inspect_commit(self, commit):
"""
Returns info about a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
"""
req = proto.InspectCommitRequest(commit=commit_from(commit))
return self.stub.InspectCommit(req, metadata=self.metadata) | python | def inspect_commit(self, commit):
"""
Returns info about a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
"""
req = proto.InspectCommitRequest(commit=commit_from(commit))
return self.stub.InspectCommit(req, metadata=self.metadata) | [
"def",
"inspect_commit",
"(",
"self",
",",
"commit",
")",
":",
"req",
"=",
"proto",
".",
"InspectCommitRequest",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
")",
"return",
"self",
".",
"stub",
".",
"InspectCommit",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")"
] | Returns info about a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit. | [
"Returns",
"info",
"about",
"a",
"specific",
"Commit",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L157-L165 | train | 231,829 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.list_commit | def list_commit(self, repo_name, to_commit=None, from_commit=None, number=0):
"""
Gets a list of CommitInfo objects.
Params:
* repo_name: If only `repo_name` is given, all commits in the repo are
returned.
* to_commit: Optional. Only the ancestors of `to`, including `to`
itself, are considered.
* from_commit: Optional. Only the descendants of `from`, including
`from` itself, are considered.
* number: Optional. Determines how many commits are returned. If
`number` is 0, all commits that match the aforementioned criteria are
returned.
"""
req = proto.ListCommitRequest(repo=proto.Repo(name=repo_name), number=number)
if to_commit is not None:
req.to.CopyFrom(commit_from(to_commit))
if from_commit is not None:
getattr(req, 'from').CopyFrom(commit_from(from_commit))
res = self.stub.ListCommit(req, metadata=self.metadata)
if hasattr(res, 'commit_info'):
return res.commit_info
return [] | python | def list_commit(self, repo_name, to_commit=None, from_commit=None, number=0):
"""
Gets a list of CommitInfo objects.
Params:
* repo_name: If only `repo_name` is given, all commits in the repo are
returned.
* to_commit: Optional. Only the ancestors of `to`, including `to`
itself, are considered.
* from_commit: Optional. Only the descendants of `from`, including
`from` itself, are considered.
* number: Optional. Determines how many commits are returned. If
`number` is 0, all commits that match the aforementioned criteria are
returned.
"""
req = proto.ListCommitRequest(repo=proto.Repo(name=repo_name), number=number)
if to_commit is not None:
req.to.CopyFrom(commit_from(to_commit))
if from_commit is not None:
getattr(req, 'from').CopyFrom(commit_from(from_commit))
res = self.stub.ListCommit(req, metadata=self.metadata)
if hasattr(res, 'commit_info'):
return res.commit_info
return [] | [
"def",
"list_commit",
"(",
"self",
",",
"repo_name",
",",
"to_commit",
"=",
"None",
",",
"from_commit",
"=",
"None",
",",
"number",
"=",
"0",
")",
":",
"req",
"=",
"proto",
".",
"ListCommitRequest",
"(",
"repo",
"=",
"proto",
".",
"Repo",
"(",
"name",
"=",
"repo_name",
")",
",",
"number",
"=",
"number",
")",
"if",
"to_commit",
"is",
"not",
"None",
":",
"req",
".",
"to",
".",
"CopyFrom",
"(",
"commit_from",
"(",
"to_commit",
")",
")",
"if",
"from_commit",
"is",
"not",
"None",
":",
"getattr",
"(",
"req",
",",
"'from'",
")",
".",
"CopyFrom",
"(",
"commit_from",
"(",
"from_commit",
")",
")",
"res",
"=",
"self",
".",
"stub",
".",
"ListCommit",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"if",
"hasattr",
"(",
"res",
",",
"'commit_info'",
")",
":",
"return",
"res",
".",
"commit_info",
"return",
"[",
"]"
] | Gets a list of CommitInfo objects.
Params:
* repo_name: If only `repo_name` is given, all commits in the repo are
returned.
* to_commit: Optional. Only the ancestors of `to`, including `to`
itself, are considered.
* from_commit: Optional. Only the descendants of `from`, including
`from` itself, are considered.
* number: Optional. Determines how many commits are returned. If
`number` is 0, all commits that match the aforementioned criteria are
returned. | [
"Gets",
"a",
"list",
"of",
"CommitInfo",
"objects",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L177-L200 | train | 231,830 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.delete_commit | def delete_commit(self, commit):
"""
Deletes a commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
"""
req = proto.DeleteCommitRequest(commit=commit_from(commit))
self.stub.DeleteCommit(req, metadata=self.metadata) | python | def delete_commit(self, commit):
"""
Deletes a commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
"""
req = proto.DeleteCommitRequest(commit=commit_from(commit))
self.stub.DeleteCommit(req, metadata=self.metadata) | [
"def",
"delete_commit",
"(",
"self",
",",
"commit",
")",
":",
"req",
"=",
"proto",
".",
"DeleteCommitRequest",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
")",
"self",
".",
"stub",
".",
"DeleteCommit",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")"
] | Deletes a commit.
Params:
* commit: A tuple, string, or Commit object representing the commit. | [
"Deletes",
"a",
"commit",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L202-L210 | train | 231,831 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.flush_commit | def flush_commit(self, commits, repos=tuple()):
"""
Blocks until all of the commits which have a set of commits as
provenance have finished. For commits to be considered they must have
all of the specified commits as provenance. This in effect waits for
all of the jobs that are triggered by a set of commits to complete.
It returns an error if any of the commits it's waiting on are
cancelled due to one of the jobs encountering an error during runtime.
Note that it's never necessary to call FlushCommit to run jobs,
they'll run no matter what, FlushCommit just allows you to wait for
them to complete and see their output once they do. This returns an
iterator of CommitInfo objects.
Params:
* commits: A commit or a list of commits to wait on.
* repos: Optional. Only the commits up to and including those repos.
will be considered, otherwise all repos are considered.
"""
req = proto.FlushCommitRequest(commit=[commit_from(c) for c in commits],
to_repo=[proto.Repo(name=r) for r in repos])
res = self.stub.FlushCommit(req, metadata=self.metadata)
return res | python | def flush_commit(self, commits, repos=tuple()):
"""
Blocks until all of the commits which have a set of commits as
provenance have finished. For commits to be considered they must have
all of the specified commits as provenance. This in effect waits for
all of the jobs that are triggered by a set of commits to complete.
It returns an error if any of the commits it's waiting on are
cancelled due to one of the jobs encountering an error during runtime.
Note that it's never necessary to call FlushCommit to run jobs,
they'll run no matter what, FlushCommit just allows you to wait for
them to complete and see their output once they do. This returns an
iterator of CommitInfo objects.
Params:
* commits: A commit or a list of commits to wait on.
* repos: Optional. Only the commits up to and including those repos.
will be considered, otherwise all repos are considered.
"""
req = proto.FlushCommitRequest(commit=[commit_from(c) for c in commits],
to_repo=[proto.Repo(name=r) for r in repos])
res = self.stub.FlushCommit(req, metadata=self.metadata)
return res | [
"def",
"flush_commit",
"(",
"self",
",",
"commits",
",",
"repos",
"=",
"tuple",
"(",
")",
")",
":",
"req",
"=",
"proto",
".",
"FlushCommitRequest",
"(",
"commit",
"=",
"[",
"commit_from",
"(",
"c",
")",
"for",
"c",
"in",
"commits",
"]",
",",
"to_repo",
"=",
"[",
"proto",
".",
"Repo",
"(",
"name",
"=",
"r",
")",
"for",
"r",
"in",
"repos",
"]",
")",
"res",
"=",
"self",
".",
"stub",
".",
"FlushCommit",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"return",
"res"
] | Blocks until all of the commits which have a set of commits as
provenance have finished. For commits to be considered they must have
all of the specified commits as provenance. This in effect waits for
all of the jobs that are triggered by a set of commits to complete.
It returns an error if any of the commits it's waiting on are
cancelled due to one of the jobs encountering an error during runtime.
Note that it's never necessary to call FlushCommit to run jobs,
they'll run no matter what, FlushCommit just allows you to wait for
them to complete and see their output once they do. This returns an
iterator of CommitInfo objects.
Params:
* commits: A commit or a list of commits to wait on.
* repos: Optional. Only the commits up to and including those repos.
will be considered, otherwise all repos are considered. | [
"Blocks",
"until",
"all",
"of",
"the",
"commits",
"which",
"have",
"a",
"set",
"of",
"commits",
"as",
"provenance",
"have",
"finished",
".",
"For",
"commits",
"to",
"be",
"considered",
"they",
"must",
"have",
"all",
"of",
"the",
"specified",
"commits",
"as",
"provenance",
".",
"This",
"in",
"effect",
"waits",
"for",
"all",
"of",
"the",
"jobs",
"that",
"are",
"triggered",
"by",
"a",
"set",
"of",
"commits",
"to",
"complete",
".",
"It",
"returns",
"an",
"error",
"if",
"any",
"of",
"the",
"commits",
"it",
"s",
"waiting",
"on",
"are",
"cancelled",
"due",
"to",
"one",
"of",
"the",
"jobs",
"encountering",
"an",
"error",
"during",
"runtime",
".",
"Note",
"that",
"it",
"s",
"never",
"necessary",
"to",
"call",
"FlushCommit",
"to",
"run",
"jobs",
"they",
"ll",
"run",
"no",
"matter",
"what",
"FlushCommit",
"just",
"allows",
"you",
"to",
"wait",
"for",
"them",
"to",
"complete",
"and",
"see",
"their",
"output",
"once",
"they",
"do",
".",
"This",
"returns",
"an",
"iterator",
"of",
"CommitInfo",
"objects",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L212-L233 | train | 231,832 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.subscribe_commit | def subscribe_commit(self, repo_name, branch, from_commit_id=None):
"""
SubscribeCommit is like ListCommit but it keeps listening for commits as
they come in. This returns an iterator Commit objects.
Params:
* repo_name: Name of the repo.
* branch: Branch to subscribe to.
* from_commit_id: Optional. Only commits created since this commit
are returned.
"""
repo = proto.Repo(name=repo_name)
req = proto.SubscribeCommitRequest(repo=repo, branch=branch)
if from_commit_id is not None:
getattr(req, 'from').CopyFrom(proto.Commit(repo=repo, id=from_commit_id))
res = self.stub.SubscribeCommit(req, metadata=self.metadata)
return res | python | def subscribe_commit(self, repo_name, branch, from_commit_id=None):
"""
SubscribeCommit is like ListCommit but it keeps listening for commits as
they come in. This returns an iterator Commit objects.
Params:
* repo_name: Name of the repo.
* branch: Branch to subscribe to.
* from_commit_id: Optional. Only commits created since this commit
are returned.
"""
repo = proto.Repo(name=repo_name)
req = proto.SubscribeCommitRequest(repo=repo, branch=branch)
if from_commit_id is not None:
getattr(req, 'from').CopyFrom(proto.Commit(repo=repo, id=from_commit_id))
res = self.stub.SubscribeCommit(req, metadata=self.metadata)
return res | [
"def",
"subscribe_commit",
"(",
"self",
",",
"repo_name",
",",
"branch",
",",
"from_commit_id",
"=",
"None",
")",
":",
"repo",
"=",
"proto",
".",
"Repo",
"(",
"name",
"=",
"repo_name",
")",
"req",
"=",
"proto",
".",
"SubscribeCommitRequest",
"(",
"repo",
"=",
"repo",
",",
"branch",
"=",
"branch",
")",
"if",
"from_commit_id",
"is",
"not",
"None",
":",
"getattr",
"(",
"req",
",",
"'from'",
")",
".",
"CopyFrom",
"(",
"proto",
".",
"Commit",
"(",
"repo",
"=",
"repo",
",",
"id",
"=",
"from_commit_id",
")",
")",
"res",
"=",
"self",
".",
"stub",
".",
"SubscribeCommit",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"return",
"res"
] | SubscribeCommit is like ListCommit but it keeps listening for commits as
they come in. This returns an iterator Commit objects.
Params:
* repo_name: Name of the repo.
* branch: Branch to subscribe to.
* from_commit_id: Optional. Only commits created since this commit
are returned. | [
"SubscribeCommit",
"is",
"like",
"ListCommit",
"but",
"it",
"keeps",
"listening",
"for",
"commits",
"as",
"they",
"come",
"in",
".",
"This",
"returns",
"an",
"iterator",
"Commit",
"objects",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L235-L251 | train | 231,833 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.list_branch | def list_branch(self, repo_name):
"""
Lists the active Branch objects on a Repo.
Params:
* repo_name: The name of the repo.
"""
req = proto.ListBranchRequest(repo=proto.Repo(name=repo_name))
res = self.stub.ListBranch(req, metadata=self.metadata)
if hasattr(res, 'branch_info'):
return res.branch_info
return [] | python | def list_branch(self, repo_name):
"""
Lists the active Branch objects on a Repo.
Params:
* repo_name: The name of the repo.
"""
req = proto.ListBranchRequest(repo=proto.Repo(name=repo_name))
res = self.stub.ListBranch(req, metadata=self.metadata)
if hasattr(res, 'branch_info'):
return res.branch_info
return [] | [
"def",
"list_branch",
"(",
"self",
",",
"repo_name",
")",
":",
"req",
"=",
"proto",
".",
"ListBranchRequest",
"(",
"repo",
"=",
"proto",
".",
"Repo",
"(",
"name",
"=",
"repo_name",
")",
")",
"res",
"=",
"self",
".",
"stub",
".",
"ListBranch",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"if",
"hasattr",
"(",
"res",
",",
"'branch_info'",
")",
":",
"return",
"res",
".",
"branch_info",
"return",
"[",
"]"
] | Lists the active Branch objects on a Repo.
Params:
* repo_name: The name of the repo. | [
"Lists",
"the",
"active",
"Branch",
"objects",
"on",
"a",
"Repo",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L253-L264 | train | 231,834 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.set_branch | def set_branch(self, commit, branch_name):
"""
Sets a commit and its ancestors as a branch.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* branch_name: The name for the branch to set.
"""
res = proto.SetBranchRequest(commit=commit_from(commit), branch=branch_name)
self.stub.SetBranch(res, metadata=self.metadata) | python | def set_branch(self, commit, branch_name):
"""
Sets a commit and its ancestors as a branch.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* branch_name: The name for the branch to set.
"""
res = proto.SetBranchRequest(commit=commit_from(commit), branch=branch_name)
self.stub.SetBranch(res, metadata=self.metadata) | [
"def",
"set_branch",
"(",
"self",
",",
"commit",
",",
"branch_name",
")",
":",
"res",
"=",
"proto",
".",
"SetBranchRequest",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
",",
"branch",
"=",
"branch_name",
")",
"self",
".",
"stub",
".",
"SetBranch",
"(",
"res",
",",
"metadata",
"=",
"self",
".",
"metadata",
")"
] | Sets a commit and its ancestors as a branch.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* branch_name: The name for the branch to set. | [
"Sets",
"a",
"commit",
"and",
"its",
"ancestors",
"as",
"a",
"branch",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L266-L275 | train | 231,835 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.delete_branch | def delete_branch(self, repo_name, branch_name):
"""
Deletes a branch, but leaves the commits themselves intact. In other
words, those commits can still be accessed via commit IDs and other
branches they happen to be on.
Params:
* repo_name: The name of the repo.
* branch_name: The name of the branch to delete.
"""
res = proto.DeleteBranchRequest(repo=Repo(name=repo_name), branch=branch_name)
self.stub.DeleteBranch(res, metadata=self.metadata) | python | def delete_branch(self, repo_name, branch_name):
"""
Deletes a branch, but leaves the commits themselves intact. In other
words, those commits can still be accessed via commit IDs and other
branches they happen to be on.
Params:
* repo_name: The name of the repo.
* branch_name: The name of the branch to delete.
"""
res = proto.DeleteBranchRequest(repo=Repo(name=repo_name), branch=branch_name)
self.stub.DeleteBranch(res, metadata=self.metadata) | [
"def",
"delete_branch",
"(",
"self",
",",
"repo_name",
",",
"branch_name",
")",
":",
"res",
"=",
"proto",
".",
"DeleteBranchRequest",
"(",
"repo",
"=",
"Repo",
"(",
"name",
"=",
"repo_name",
")",
",",
"branch",
"=",
"branch_name",
")",
"self",
".",
"stub",
".",
"DeleteBranch",
"(",
"res",
",",
"metadata",
"=",
"self",
".",
"metadata",
")"
] | Deletes a branch, but leaves the commits themselves intact. In other
words, those commits can still be accessed via commit IDs and other
branches they happen to be on.
Params:
* repo_name: The name of the repo.
* branch_name: The name of the branch to delete. | [
"Deletes",
"a",
"branch",
"but",
"leaves",
"the",
"commits",
"themselves",
"intact",
".",
"In",
"other",
"words",
"those",
"commits",
"can",
"still",
"be",
"accessed",
"via",
"commit",
"IDs",
"and",
"other",
"branches",
"they",
"happen",
"to",
"be",
"on",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L277-L288 | train | 231,836 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.put_file_url | def put_file_url(self, commit, path, url, recursive=False):
"""
Puts a file using the content found at a URL. The URL is sent to the
server which performs the request.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the file.
* url: The url of the file to put.
* recursive: allow for recursive scraping of some types URLs for
example on s3:// urls.
"""
req = iter([
proto.PutFileRequest(
file=proto.File(commit=commit_from(commit), path=path),
url=url,
recursive=recursive
)
])
self.stub.PutFile(req, metadata=self.metadata) | python | def put_file_url(self, commit, path, url, recursive=False):
"""
Puts a file using the content found at a URL. The URL is sent to the
server which performs the request.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the file.
* url: The url of the file to put.
* recursive: allow for recursive scraping of some types URLs for
example on s3:// urls.
"""
req = iter([
proto.PutFileRequest(
file=proto.File(commit=commit_from(commit), path=path),
url=url,
recursive=recursive
)
])
self.stub.PutFile(req, metadata=self.metadata) | [
"def",
"put_file_url",
"(",
"self",
",",
"commit",
",",
"path",
",",
"url",
",",
"recursive",
"=",
"False",
")",
":",
"req",
"=",
"iter",
"(",
"[",
"proto",
".",
"PutFileRequest",
"(",
"file",
"=",
"proto",
".",
"File",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
",",
"path",
"=",
"path",
")",
",",
"url",
"=",
"url",
",",
"recursive",
"=",
"recursive",
")",
"]",
")",
"self",
".",
"stub",
".",
"PutFile",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")"
] | Puts a file using the content found at a URL. The URL is sent to the
server which performs the request.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the file.
* url: The url of the file to put.
* recursive: allow for recursive scraping of some types URLs for
example on s3:// urls. | [
"Puts",
"a",
"file",
"using",
"the",
"content",
"found",
"at",
"a",
"URL",
".",
"The",
"URL",
"is",
"sent",
"to",
"the",
"server",
"which",
"performs",
"the",
"request",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L363-L382 | train | 231,837 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.get_file | def get_file(self, commit, path, offset_bytes=0, size_bytes=0, extract_value=True):
"""
Returns an iterator of the contents contents of a file at a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path of the file.
* offset_bytes: Optional. specifies a number of bytes that should be
skipped in the beginning of the file.
* size_bytes: Optional. limits the total amount of data returned, note
you will get fewer bytes than size if you pass a value larger than the
size of the file. If size is set to 0 then all of the data will be
returned.
* extract_value: If True, then an ExtractValueIterator will be return,
which will iterate over the bytes of the file. If False, then the
protobuf response iterator will return.
"""
req = proto.GetFileRequest(
file=proto.File(commit=commit_from(commit), path=path),
offset_bytes=offset_bytes,
size_bytes=size_bytes
)
res = self.stub.GetFile(req, metadata=self.metadata)
if extract_value:
return ExtractValueIterator(res)
return res | python | def get_file(self, commit, path, offset_bytes=0, size_bytes=0, extract_value=True):
"""
Returns an iterator of the contents contents of a file at a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path of the file.
* offset_bytes: Optional. specifies a number of bytes that should be
skipped in the beginning of the file.
* size_bytes: Optional. limits the total amount of data returned, note
you will get fewer bytes than size if you pass a value larger than the
size of the file. If size is set to 0 then all of the data will be
returned.
* extract_value: If True, then an ExtractValueIterator will be return,
which will iterate over the bytes of the file. If False, then the
protobuf response iterator will return.
"""
req = proto.GetFileRequest(
file=proto.File(commit=commit_from(commit), path=path),
offset_bytes=offset_bytes,
size_bytes=size_bytes
)
res = self.stub.GetFile(req, metadata=self.metadata)
if extract_value:
return ExtractValueIterator(res)
return res | [
"def",
"get_file",
"(",
"self",
",",
"commit",
",",
"path",
",",
"offset_bytes",
"=",
"0",
",",
"size_bytes",
"=",
"0",
",",
"extract_value",
"=",
"True",
")",
":",
"req",
"=",
"proto",
".",
"GetFileRequest",
"(",
"file",
"=",
"proto",
".",
"File",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
",",
"path",
"=",
"path",
")",
",",
"offset_bytes",
"=",
"offset_bytes",
",",
"size_bytes",
"=",
"size_bytes",
")",
"res",
"=",
"self",
".",
"stub",
".",
"GetFile",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"if",
"extract_value",
":",
"return",
"ExtractValueIterator",
"(",
"res",
")",
"return",
"res"
] | Returns an iterator of the contents contents of a file at a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path of the file.
* offset_bytes: Optional. specifies a number of bytes that should be
skipped in the beginning of the file.
* size_bytes: Optional. limits the total amount of data returned, note
you will get fewer bytes than size if you pass a value larger than the
size of the file. If size is set to 0 then all of the data will be
returned.
* extract_value: If True, then an ExtractValueIterator will be return,
which will iterate over the bytes of the file. If False, then the
protobuf response iterator will return. | [
"Returns",
"an",
"iterator",
"of",
"the",
"contents",
"contents",
"of",
"a",
"file",
"at",
"a",
"specific",
"Commit",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L384-L409 | train | 231,838 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.get_files | def get_files(self, commit, paths, recursive=False):
"""
Returns the contents of a list of files at a specific Commit as a
dictionary of file paths to data.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* paths: A list of paths to retrieve.
* recursive: If True, will go into each directory in the list
recursively.
"""
filtered_file_infos = []
for path in paths:
fi = self.inspect_file(commit, path)
if fi.file_type == proto.FILE:
filtered_file_infos.append(fi)
else:
filtered_file_infos += self.list_file(commit, path, recursive=recursive)
filtered_paths = [fi.file.path for fi in filtered_file_infos if fi.file_type == proto.FILE]
return {path: b''.join(self.get_file(commit, path)) for path in filtered_paths} | python | def get_files(self, commit, paths, recursive=False):
"""
Returns the contents of a list of files at a specific Commit as a
dictionary of file paths to data.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* paths: A list of paths to retrieve.
* recursive: If True, will go into each directory in the list
recursively.
"""
filtered_file_infos = []
for path in paths:
fi = self.inspect_file(commit, path)
if fi.file_type == proto.FILE:
filtered_file_infos.append(fi)
else:
filtered_file_infos += self.list_file(commit, path, recursive=recursive)
filtered_paths = [fi.file.path for fi in filtered_file_infos if fi.file_type == proto.FILE]
return {path: b''.join(self.get_file(commit, path)) for path in filtered_paths} | [
"def",
"get_files",
"(",
"self",
",",
"commit",
",",
"paths",
",",
"recursive",
"=",
"False",
")",
":",
"filtered_file_infos",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
"fi",
"=",
"self",
".",
"inspect_file",
"(",
"commit",
",",
"path",
")",
"if",
"fi",
".",
"file_type",
"==",
"proto",
".",
"FILE",
":",
"filtered_file_infos",
".",
"append",
"(",
"fi",
")",
"else",
":",
"filtered_file_infos",
"+=",
"self",
".",
"list_file",
"(",
"commit",
",",
"path",
",",
"recursive",
"=",
"recursive",
")",
"filtered_paths",
"=",
"[",
"fi",
".",
"file",
".",
"path",
"for",
"fi",
"in",
"filtered_file_infos",
"if",
"fi",
".",
"file_type",
"==",
"proto",
".",
"FILE",
"]",
"return",
"{",
"path",
":",
"b''",
".",
"join",
"(",
"self",
".",
"get_file",
"(",
"commit",
",",
"path",
")",
")",
"for",
"path",
"in",
"filtered_paths",
"}"
] | Returns the contents of a list of files at a specific Commit as a
dictionary of file paths to data.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* paths: A list of paths to retrieve.
* recursive: If True, will go into each directory in the list
recursively. | [
"Returns",
"the",
"contents",
"of",
"a",
"list",
"of",
"files",
"at",
"a",
"specific",
"Commit",
"as",
"a",
"dictionary",
"of",
"file",
"paths",
"to",
"data",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L411-L432 | train | 231,839 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.inspect_file | def inspect_file(self, commit, path):
"""
Returns info about a specific file.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: Path to file.
"""
req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=path))
res = self.stub.InspectFile(req, metadata=self.metadata)
return res | python | def inspect_file(self, commit, path):
"""
Returns info about a specific file.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: Path to file.
"""
req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=path))
res = self.stub.InspectFile(req, metadata=self.metadata)
return res | [
"def",
"inspect_file",
"(",
"self",
",",
"commit",
",",
"path",
")",
":",
"req",
"=",
"proto",
".",
"InspectFileRequest",
"(",
"file",
"=",
"proto",
".",
"File",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
",",
"path",
"=",
"path",
")",
")",
"res",
"=",
"self",
".",
"stub",
".",
"InspectFile",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"return",
"res"
] | Returns info about a specific file.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: Path to file. | [
"Returns",
"info",
"about",
"a",
"specific",
"file",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L434-L444 | train | 231,840 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.list_file | def list_file(self, commit, path, recursive=False):
"""
Lists the files in a directory.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the directory.
* recursive: If True, continue listing the files for sub-directories.
"""
req = proto.ListFileRequest(
file=proto.File(commit=commit_from(commit), path=path)
)
res = self.stub.ListFile(req, metadata=self.metadata)
file_infos = res.file_info
if recursive:
dirs = [f for f in file_infos if f.file_type == proto.DIR]
files = [f for f in file_infos if f.file_type == proto.FILE]
return sum([self.list_file(commit, d.file.path, recursive) for d in dirs], files)
return list(file_infos) | python | def list_file(self, commit, path, recursive=False):
"""
Lists the files in a directory.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the directory.
* recursive: If True, continue listing the files for sub-directories.
"""
req = proto.ListFileRequest(
file=proto.File(commit=commit_from(commit), path=path)
)
res = self.stub.ListFile(req, metadata=self.metadata)
file_infos = res.file_info
if recursive:
dirs = [f for f in file_infos if f.file_type == proto.DIR]
files = [f for f in file_infos if f.file_type == proto.FILE]
return sum([self.list_file(commit, d.file.path, recursive) for d in dirs], files)
return list(file_infos) | [
"def",
"list_file",
"(",
"self",
",",
"commit",
",",
"path",
",",
"recursive",
"=",
"False",
")",
":",
"req",
"=",
"proto",
".",
"ListFileRequest",
"(",
"file",
"=",
"proto",
".",
"File",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
",",
"path",
"=",
"path",
")",
")",
"res",
"=",
"self",
".",
"stub",
".",
"ListFile",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")",
"file_infos",
"=",
"res",
".",
"file_info",
"if",
"recursive",
":",
"dirs",
"=",
"[",
"f",
"for",
"f",
"in",
"file_infos",
"if",
"f",
".",
"file_type",
"==",
"proto",
".",
"DIR",
"]",
"files",
"=",
"[",
"f",
"for",
"f",
"in",
"file_infos",
"if",
"f",
".",
"file_type",
"==",
"proto",
".",
"FILE",
"]",
"return",
"sum",
"(",
"[",
"self",
".",
"list_file",
"(",
"commit",
",",
"d",
".",
"file",
".",
"path",
",",
"recursive",
")",
"for",
"d",
"in",
"dirs",
"]",
",",
"files",
")",
"return",
"list",
"(",
"file_infos",
")"
] | Lists the files in a directory.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the directory.
* recursive: If True, continue listing the files for sub-directories. | [
"Lists",
"the",
"files",
"in",
"a",
"directory",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L446-L466 | train | 231,841 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | PfsClient.delete_file | def delete_file(self, commit, path):
"""
Deletes a file from a Commit. DeleteFile leaves a tombstone in the
Commit, assuming the file isn't written to later attempting to get the
file from the finished commit will result in not found error. The file
will of course remain intact in the Commit's parent.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the file.
"""
req = proto.DeleteFileRequest(file=proto.File(commit=commit_from(commit), path=path))
self.stub.DeleteFile(req, metadata=self.metadata) | python | def delete_file(self, commit, path):
"""
Deletes a file from a Commit. DeleteFile leaves a tombstone in the
Commit, assuming the file isn't written to later attempting to get the
file from the finished commit will result in not found error. The file
will of course remain intact in the Commit's parent.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the file.
"""
req = proto.DeleteFileRequest(file=proto.File(commit=commit_from(commit), path=path))
self.stub.DeleteFile(req, metadata=self.metadata) | [
"def",
"delete_file",
"(",
"self",
",",
"commit",
",",
"path",
")",
":",
"req",
"=",
"proto",
".",
"DeleteFileRequest",
"(",
"file",
"=",
"proto",
".",
"File",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
",",
"path",
"=",
"path",
")",
")",
"self",
".",
"stub",
".",
"DeleteFile",
"(",
"req",
",",
"metadata",
"=",
"self",
".",
"metadata",
")"
] | Deletes a file from a Commit. DeleteFile leaves a tombstone in the
Commit, assuming the file isn't written to later attempting to get the
file from the finished commit will result in not found error. The file
will of course remain intact in the Commit's parent.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path to the file. | [
"Deletes",
"a",
"file",
"from",
"a",
"Commit",
".",
"DeleteFile",
"leaves",
"a",
"tombstone",
"in",
"the",
"Commit",
"assuming",
"the",
"file",
"isn",
"t",
"written",
"to",
"later",
"attempting",
"to",
"get",
"the",
"file",
"from",
"the",
"finished",
"commit",
"will",
"result",
"in",
"not",
"found",
"error",
".",
"The",
"file",
"will",
"of",
"course",
"remain",
"intact",
"in",
"the",
"Commit",
"s",
"parent",
"."
] | 1c58cf91d30e03716a4f45213989e890f7b8a78c | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L475-L487 | train | 231,842 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLFrontend.handle_authn_request | def handle_authn_request(self, context, binding_in):
"""
This method is bound to the starting endpoint of the authentication.
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The binding type (http post, http redirect, ...)
:return: response
"""
return self._handle_authn_request(context, binding_in, self.idp) | python | def handle_authn_request(self, context, binding_in):
"""
This method is bound to the starting endpoint of the authentication.
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The binding type (http post, http redirect, ...)
:return: response
"""
return self._handle_authn_request(context, binding_in, self.idp) | [
"def",
"handle_authn_request",
"(",
"self",
",",
"context",
",",
"binding_in",
")",
":",
"return",
"self",
".",
"_handle_authn_request",
"(",
"context",
",",
"binding_in",
",",
"self",
".",
"idp",
")"
] | This method is bound to the starting endpoint of the authentication.
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The binding type (http post, http redirect, ...)
:return: response | [
"This",
"method",
"is",
"bound",
"to",
"the",
"starting",
"endpoint",
"of",
"the",
"authentication",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L90-L102 | train | 231,843 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLFrontend._create_state_data | def _create_state_data(self, context, resp_args, relay_state):
"""
Returns a dict containing the state needed in the response flow.
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:type relay_state: str
:rtype: dict[str, dict[str, str] | str]
:param context: The current context
:param resp_args: Response arguments
:param relay_state: Request relay state
:return: A state as a dict
"""
if "name_id_policy" in resp_args and resp_args["name_id_policy"] is not None:
resp_args["name_id_policy"] = resp_args["name_id_policy"].to_string().decode("utf-8")
return {"resp_args": resp_args, "relay_state": relay_state} | python | def _create_state_data(self, context, resp_args, relay_state):
"""
Returns a dict containing the state needed in the response flow.
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:type relay_state: str
:rtype: dict[str, dict[str, str] | str]
:param context: The current context
:param resp_args: Response arguments
:param relay_state: Request relay state
:return: A state as a dict
"""
if "name_id_policy" in resp_args and resp_args["name_id_policy"] is not None:
resp_args["name_id_policy"] = resp_args["name_id_policy"].to_string().decode("utf-8")
return {"resp_args": resp_args, "relay_state": relay_state} | [
"def",
"_create_state_data",
"(",
"self",
",",
"context",
",",
"resp_args",
",",
"relay_state",
")",
":",
"if",
"\"name_id_policy\"",
"in",
"resp_args",
"and",
"resp_args",
"[",
"\"name_id_policy\"",
"]",
"is",
"not",
"None",
":",
"resp_args",
"[",
"\"name_id_policy\"",
"]",
"=",
"resp_args",
"[",
"\"name_id_policy\"",
"]",
".",
"to_string",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"{",
"\"resp_args\"",
":",
"resp_args",
",",
"\"relay_state\"",
":",
"relay_state",
"}"
] | Returns a dict containing the state needed in the response flow.
:type context: satosa.context.Context
:type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]
:type relay_state: str
:rtype: dict[str, dict[str, str] | str]
:param context: The current context
:param resp_args: Response arguments
:param relay_state: Request relay state
:return: A state as a dict | [
"Returns",
"a",
"dict",
"containing",
"the",
"state",
"needed",
"in",
"the",
"response",
"flow",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L125-L141 | train | 231,844 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLFrontend._handle_authn_request | def _handle_authn_request(self, context, binding_in, idp):
"""
See doc for handle_authn_request method.
:type context: satosa.context.Context
:type binding_in: str
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The pysaml binding type
:param idp: The saml frontend idp server
:return: response
"""
req_info = idp.parse_authn_request(context.request["SAMLRequest"], binding_in)
authn_req = req_info.message
satosa_logging(logger, logging.DEBUG, "%s" % authn_req, context.state)
try:
resp_args = idp.response_args(authn_req)
except SAMLError as e:
satosa_logging(logger, logging.ERROR, "Could not find necessary info about entity: %s" % e, context.state)
return ServiceError("Incorrect request from requester: %s" % e)
requester = resp_args["sp_entity_id"]
context.state[self.name] = self._create_state_data(context, idp.response_args(authn_req),
context.request.get("RelayState"))
subject = authn_req.subject
name_id_value = subject.name_id.text if subject else None
nameid_formats = {
"from_policy": authn_req.name_id_policy and authn_req.name_id_policy.format,
"from_response": subject and subject.name_id and subject.name_id.format,
"from_metadata": (
idp.metadata[requester]
.get("spsso_descriptor", [{}])[0]
.get("name_id_format", [{}])[0]
.get("text")
),
"default": NAMEID_FORMAT_TRANSIENT,
}
name_id_format = (
nameid_formats["from_policy"]
or (
nameid_formats["from_response"] != NAMEID_FORMAT_UNSPECIFIED
and nameid_formats["from_response"]
)
or nameid_formats["from_metadata"]
or nameid_formats["from_response"]
or nameid_formats["default"]
)
requester_name = self._get_sp_display_name(idp, requester)
internal_req = InternalData(
subject_id=name_id_value,
subject_type=name_id_format,
requester=requester,
requester_name=requester_name,
)
idp_policy = idp.config.getattr("policy", "idp")
if idp_policy:
internal_req.attributes = self._get_approved_attributes(
idp, idp_policy, requester, context.state
)
return self.auth_req_callback_func(context, internal_req) | python | def _handle_authn_request(self, context, binding_in, idp):
"""
See doc for handle_authn_request method.
:type context: satosa.context.Context
:type binding_in: str
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The pysaml binding type
:param idp: The saml frontend idp server
:return: response
"""
req_info = idp.parse_authn_request(context.request["SAMLRequest"], binding_in)
authn_req = req_info.message
satosa_logging(logger, logging.DEBUG, "%s" % authn_req, context.state)
try:
resp_args = idp.response_args(authn_req)
except SAMLError as e:
satosa_logging(logger, logging.ERROR, "Could not find necessary info about entity: %s" % e, context.state)
return ServiceError("Incorrect request from requester: %s" % e)
requester = resp_args["sp_entity_id"]
context.state[self.name] = self._create_state_data(context, idp.response_args(authn_req),
context.request.get("RelayState"))
subject = authn_req.subject
name_id_value = subject.name_id.text if subject else None
nameid_formats = {
"from_policy": authn_req.name_id_policy and authn_req.name_id_policy.format,
"from_response": subject and subject.name_id and subject.name_id.format,
"from_metadata": (
idp.metadata[requester]
.get("spsso_descriptor", [{}])[0]
.get("name_id_format", [{}])[0]
.get("text")
),
"default": NAMEID_FORMAT_TRANSIENT,
}
name_id_format = (
nameid_formats["from_policy"]
or (
nameid_formats["from_response"] != NAMEID_FORMAT_UNSPECIFIED
and nameid_formats["from_response"]
)
or nameid_formats["from_metadata"]
or nameid_formats["from_response"]
or nameid_formats["default"]
)
requester_name = self._get_sp_display_name(idp, requester)
internal_req = InternalData(
subject_id=name_id_value,
subject_type=name_id_format,
requester=requester,
requester_name=requester_name,
)
idp_policy = idp.config.getattr("policy", "idp")
if idp_policy:
internal_req.attributes = self._get_approved_attributes(
idp, idp_policy, requester, context.state
)
return self.auth_req_callback_func(context, internal_req) | [
"def",
"_handle_authn_request",
"(",
"self",
",",
"context",
",",
"binding_in",
",",
"idp",
")",
":",
"req_info",
"=",
"idp",
".",
"parse_authn_request",
"(",
"context",
".",
"request",
"[",
"\"SAMLRequest\"",
"]",
",",
"binding_in",
")",
"authn_req",
"=",
"req_info",
".",
"message",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"%s\"",
"%",
"authn_req",
",",
"context",
".",
"state",
")",
"try",
":",
"resp_args",
"=",
"idp",
".",
"response_args",
"(",
"authn_req",
")",
"except",
"SAMLError",
"as",
"e",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"Could not find necessary info about entity: %s\"",
"%",
"e",
",",
"context",
".",
"state",
")",
"return",
"ServiceError",
"(",
"\"Incorrect request from requester: %s\"",
"%",
"e",
")",
"requester",
"=",
"resp_args",
"[",
"\"sp_entity_id\"",
"]",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"=",
"self",
".",
"_create_state_data",
"(",
"context",
",",
"idp",
".",
"response_args",
"(",
"authn_req",
")",
",",
"context",
".",
"request",
".",
"get",
"(",
"\"RelayState\"",
")",
")",
"subject",
"=",
"authn_req",
".",
"subject",
"name_id_value",
"=",
"subject",
".",
"name_id",
".",
"text",
"if",
"subject",
"else",
"None",
"nameid_formats",
"=",
"{",
"\"from_policy\"",
":",
"authn_req",
".",
"name_id_policy",
"and",
"authn_req",
".",
"name_id_policy",
".",
"format",
",",
"\"from_response\"",
":",
"subject",
"and",
"subject",
".",
"name_id",
"and",
"subject",
".",
"name_id",
".",
"format",
",",
"\"from_metadata\"",
":",
"(",
"idp",
".",
"metadata",
"[",
"requester",
"]",
".",
"get",
"(",
"\"spsso_descriptor\"",
",",
"[",
"{",
"}",
"]",
")",
"[",
"0",
"]",
".",
"get",
"(",
"\"name_id_format\"",
",",
"[",
"{",
"}",
"]",
")",
"[",
"0",
"]",
".",
"get",
"(",
"\"text\"",
")",
")",
",",
"\"default\"",
":",
"NAMEID_FORMAT_TRANSIENT",
",",
"}",
"name_id_format",
"=",
"(",
"nameid_formats",
"[",
"\"from_policy\"",
"]",
"or",
"(",
"nameid_formats",
"[",
"\"from_response\"",
"]",
"!=",
"NAMEID_FORMAT_UNSPECIFIED",
"and",
"nameid_formats",
"[",
"\"from_response\"",
"]",
")",
"or",
"nameid_formats",
"[",
"\"from_metadata\"",
"]",
"or",
"nameid_formats",
"[",
"\"from_response\"",
"]",
"or",
"nameid_formats",
"[",
"\"default\"",
"]",
")",
"requester_name",
"=",
"self",
".",
"_get_sp_display_name",
"(",
"idp",
",",
"requester",
")",
"internal_req",
"=",
"InternalData",
"(",
"subject_id",
"=",
"name_id_value",
",",
"subject_type",
"=",
"name_id_format",
",",
"requester",
"=",
"requester",
",",
"requester_name",
"=",
"requester_name",
",",
")",
"idp_policy",
"=",
"idp",
".",
"config",
".",
"getattr",
"(",
"\"policy\"",
",",
"\"idp\"",
")",
"if",
"idp_policy",
":",
"internal_req",
".",
"attributes",
"=",
"self",
".",
"_get_approved_attributes",
"(",
"idp",
",",
"idp_policy",
",",
"requester",
",",
"context",
".",
"state",
")",
"return",
"self",
".",
"auth_req_callback_func",
"(",
"context",
",",
"internal_req",
")"
] | See doc for handle_authn_request method.
:type context: satosa.context.Context
:type binding_in: str
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param context: The current context
:param binding_in: The pysaml binding type
:param idp: The saml frontend idp server
:return: response | [
"See",
"doc",
"for",
"handle_authn_request",
"method",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L177-L245 | train | 231,845 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLFrontend._get_approved_attributes | def _get_approved_attributes(self, idp, idp_policy, sp_entity_id, state):
"""
Returns a list of approved attributes
:type idp: saml.server.Server
:type idp_policy: saml2.assertion.Policy
:type sp_entity_id: str
:type state: satosa.state.State
:rtype: list[str]
:param idp: The saml frontend idp server
:param idp_policy: The idp policy
:param sp_entity_id: The requesting sp entity id
:param state: The current state
:return: A list containing approved attributes
"""
name_format = idp_policy.get_name_form(sp_entity_id)
attrconvs = idp.config.attribute_converters
idp_policy.acs = attrconvs
attribute_filter = []
for aconv in attrconvs:
if aconv.name_format == name_format:
all_attributes = {v: None for v in aconv._fro.values()}
attribute_filter = list(idp_policy.restrict(all_attributes, sp_entity_id, idp.metadata).keys())
break
attribute_filter = self.converter.to_internal_filter(self.attribute_profile, attribute_filter)
satosa_logging(logger, logging.DEBUG, "Filter: %s" % attribute_filter, state)
return attribute_filter | python | def _get_approved_attributes(self, idp, idp_policy, sp_entity_id, state):
"""
Returns a list of approved attributes
:type idp: saml.server.Server
:type idp_policy: saml2.assertion.Policy
:type sp_entity_id: str
:type state: satosa.state.State
:rtype: list[str]
:param idp: The saml frontend idp server
:param idp_policy: The idp policy
:param sp_entity_id: The requesting sp entity id
:param state: The current state
:return: A list containing approved attributes
"""
name_format = idp_policy.get_name_form(sp_entity_id)
attrconvs = idp.config.attribute_converters
idp_policy.acs = attrconvs
attribute_filter = []
for aconv in attrconvs:
if aconv.name_format == name_format:
all_attributes = {v: None for v in aconv._fro.values()}
attribute_filter = list(idp_policy.restrict(all_attributes, sp_entity_id, idp.metadata).keys())
break
attribute_filter = self.converter.to_internal_filter(self.attribute_profile, attribute_filter)
satosa_logging(logger, logging.DEBUG, "Filter: %s" % attribute_filter, state)
return attribute_filter | [
"def",
"_get_approved_attributes",
"(",
"self",
",",
"idp",
",",
"idp_policy",
",",
"sp_entity_id",
",",
"state",
")",
":",
"name_format",
"=",
"idp_policy",
".",
"get_name_form",
"(",
"sp_entity_id",
")",
"attrconvs",
"=",
"idp",
".",
"config",
".",
"attribute_converters",
"idp_policy",
".",
"acs",
"=",
"attrconvs",
"attribute_filter",
"=",
"[",
"]",
"for",
"aconv",
"in",
"attrconvs",
":",
"if",
"aconv",
".",
"name_format",
"==",
"name_format",
":",
"all_attributes",
"=",
"{",
"v",
":",
"None",
"for",
"v",
"in",
"aconv",
".",
"_fro",
".",
"values",
"(",
")",
"}",
"attribute_filter",
"=",
"list",
"(",
"idp_policy",
".",
"restrict",
"(",
"all_attributes",
",",
"sp_entity_id",
",",
"idp",
".",
"metadata",
")",
".",
"keys",
"(",
")",
")",
"break",
"attribute_filter",
"=",
"self",
".",
"converter",
".",
"to_internal_filter",
"(",
"self",
".",
"attribute_profile",
",",
"attribute_filter",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Filter: %s\"",
"%",
"attribute_filter",
",",
"state",
")",
"return",
"attribute_filter"
] | Returns a list of approved attributes
:type idp: saml.server.Server
:type idp_policy: saml2.assertion.Policy
:type sp_entity_id: str
:type state: satosa.state.State
:rtype: list[str]
:param idp: The saml frontend idp server
:param idp_policy: The idp policy
:param sp_entity_id: The requesting sp entity id
:param state: The current state
:return: A list containing approved attributes | [
"Returns",
"a",
"list",
"of",
"approved",
"attributes"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L247-L274 | train | 231,846 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLFrontend._build_idp_config_endpoints | def _build_idp_config_endpoints(self, config, providers):
"""
Builds the final frontend module config
:type config: dict[str, Any]
:type providers: list[str]
:rtype: dict[str, Any]
:param config: The module config
:param providers: A list of backend names
:return: The final config
"""
# Add an endpoint to each provider
idp_endpoints = []
for endp_category in self.endpoints:
for func, endpoint in self.endpoints[endp_category].items():
for provider in providers:
_endpoint = "{base}/{provider}/{endpoint}".format(
base=self.base_url, provider=provider, endpoint=endpoint)
idp_endpoints.append((_endpoint, func))
config["service"]["idp"]["endpoints"][endp_category] = idp_endpoints
return config | python | def _build_idp_config_endpoints(self, config, providers):
"""
Builds the final frontend module config
:type config: dict[str, Any]
:type providers: list[str]
:rtype: dict[str, Any]
:param config: The module config
:param providers: A list of backend names
:return: The final config
"""
# Add an endpoint to each provider
idp_endpoints = []
for endp_category in self.endpoints:
for func, endpoint in self.endpoints[endp_category].items():
for provider in providers:
_endpoint = "{base}/{provider}/{endpoint}".format(
base=self.base_url, provider=provider, endpoint=endpoint)
idp_endpoints.append((_endpoint, func))
config["service"]["idp"]["endpoints"][endp_category] = idp_endpoints
return config | [
"def",
"_build_idp_config_endpoints",
"(",
"self",
",",
"config",
",",
"providers",
")",
":",
"# Add an endpoint to each provider",
"idp_endpoints",
"=",
"[",
"]",
"for",
"endp_category",
"in",
"self",
".",
"endpoints",
":",
"for",
"func",
",",
"endpoint",
"in",
"self",
".",
"endpoints",
"[",
"endp_category",
"]",
".",
"items",
"(",
")",
":",
"for",
"provider",
"in",
"providers",
":",
"_endpoint",
"=",
"\"{base}/{provider}/{endpoint}\"",
".",
"format",
"(",
"base",
"=",
"self",
".",
"base_url",
",",
"provider",
"=",
"provider",
",",
"endpoint",
"=",
"endpoint",
")",
"idp_endpoints",
".",
"append",
"(",
"(",
"_endpoint",
",",
"func",
")",
")",
"config",
"[",
"\"service\"",
"]",
"[",
"\"idp\"",
"]",
"[",
"\"endpoints\"",
"]",
"[",
"endp_category",
"]",
"=",
"idp_endpoints",
"return",
"config"
] | Builds the final frontend module config
:type config: dict[str, Any]
:type providers: list[str]
:rtype: dict[str, Any]
:param config: The module config
:param providers: A list of backend names
:return: The final config | [
"Builds",
"the",
"final",
"frontend",
"module",
"config"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L522-L544 | train | 231,847 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLMirrorFrontend._load_endpoints_to_config | def _load_endpoints_to_config(self, provider, target_entity_id, config=None):
"""
Loads approved endpoints to the config.
:type url_base: str
:type provider: str
:type target_entity_id: str
:rtype: dict[str, Any]
:param url_base: The proxy base url
:param provider: target backend name
:param target_entity_id: frontend target entity id
:return: IDP config with endpoints
"""
idp_conf = copy.deepcopy(config or self.idp_config)
for service, endpoint in self.endpoints.items():
idp_endpoints = []
for binding, path in endpoint.items():
url = "{base}/{provider}/{target_id}/{path}".format(
base=self.base_url, provider=provider,
target_id=target_entity_id, path=path)
idp_endpoints.append((url, binding))
idp_conf["service"]["idp"]["endpoints"][service] = idp_endpoints
return idp_conf | python | def _load_endpoints_to_config(self, provider, target_entity_id, config=None):
"""
Loads approved endpoints to the config.
:type url_base: str
:type provider: str
:type target_entity_id: str
:rtype: dict[str, Any]
:param url_base: The proxy base url
:param provider: target backend name
:param target_entity_id: frontend target entity id
:return: IDP config with endpoints
"""
idp_conf = copy.deepcopy(config or self.idp_config)
for service, endpoint in self.endpoints.items():
idp_endpoints = []
for binding, path in endpoint.items():
url = "{base}/{provider}/{target_id}/{path}".format(
base=self.base_url, provider=provider,
target_id=target_entity_id, path=path)
idp_endpoints.append((url, binding))
idp_conf["service"]["idp"]["endpoints"][service] = idp_endpoints
return idp_conf | [
"def",
"_load_endpoints_to_config",
"(",
"self",
",",
"provider",
",",
"target_entity_id",
",",
"config",
"=",
"None",
")",
":",
"idp_conf",
"=",
"copy",
".",
"deepcopy",
"(",
"config",
"or",
"self",
".",
"idp_config",
")",
"for",
"service",
",",
"endpoint",
"in",
"self",
".",
"endpoints",
".",
"items",
"(",
")",
":",
"idp_endpoints",
"=",
"[",
"]",
"for",
"binding",
",",
"path",
"in",
"endpoint",
".",
"items",
"(",
")",
":",
"url",
"=",
"\"{base}/{provider}/{target_id}/{path}\"",
".",
"format",
"(",
"base",
"=",
"self",
".",
"base_url",
",",
"provider",
"=",
"provider",
",",
"target_id",
"=",
"target_entity_id",
",",
"path",
"=",
"path",
")",
"idp_endpoints",
".",
"append",
"(",
"(",
"url",
",",
"binding",
")",
")",
"idp_conf",
"[",
"\"service\"",
"]",
"[",
"\"idp\"",
"]",
"[",
"\"endpoints\"",
"]",
"[",
"service",
"]",
"=",
"idp_endpoints",
"return",
"idp_conf"
] | Loads approved endpoints to the config.
:type url_base: str
:type provider: str
:type target_entity_id: str
:rtype: dict[str, Any]
:param url_base: The proxy base url
:param provider: target backend name
:param target_entity_id: frontend target entity id
:return: IDP config with endpoints | [
"Loads",
"approved",
"endpoints",
"to",
"the",
"config",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L564-L587 | train | 231,848 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLMirrorFrontend._load_idp_dynamic_entity_id | def _load_idp_dynamic_entity_id(self, state):
"""
Loads an idp server with the entity id saved in state
:type state: satosa.state.State
:rtype: saml.server.Server
:param state: The current state
:return: An idp server
"""
# Change the idp entity id dynamically
idp_config_file = copy.deepcopy(self.idp_config)
idp_config_file["entityid"] = "{}/{}".format(self.idp_config["entityid"], state[self.name]["target_entity_id"])
idp_config = IdPConfig().load(idp_config_file, metadata_construction=False)
return Server(config=idp_config) | python | def _load_idp_dynamic_entity_id(self, state):
"""
Loads an idp server with the entity id saved in state
:type state: satosa.state.State
:rtype: saml.server.Server
:param state: The current state
:return: An idp server
"""
# Change the idp entity id dynamically
idp_config_file = copy.deepcopy(self.idp_config)
idp_config_file["entityid"] = "{}/{}".format(self.idp_config["entityid"], state[self.name]["target_entity_id"])
idp_config = IdPConfig().load(idp_config_file, metadata_construction=False)
return Server(config=idp_config) | [
"def",
"_load_idp_dynamic_entity_id",
"(",
"self",
",",
"state",
")",
":",
"# Change the idp entity id dynamically",
"idp_config_file",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"idp_config",
")",
"idp_config_file",
"[",
"\"entityid\"",
"]",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"self",
".",
"idp_config",
"[",
"\"entityid\"",
"]",
",",
"state",
"[",
"self",
".",
"name",
"]",
"[",
"\"target_entity_id\"",
"]",
")",
"idp_config",
"=",
"IdPConfig",
"(",
")",
".",
"load",
"(",
"idp_config_file",
",",
"metadata_construction",
"=",
"False",
")",
"return",
"Server",
"(",
"config",
"=",
"idp_config",
")"
] | Loads an idp server with the entity id saved in state
:type state: satosa.state.State
:rtype: saml.server.Server
:param state: The current state
:return: An idp server | [
"Loads",
"an",
"idp",
"server",
"with",
"the",
"entity",
"id",
"saved",
"in",
"state"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L605-L619 | train | 231,849 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLVirtualCoFrontend._get_co_name_from_path | def _get_co_name_from_path(self, context):
"""
The CO name is URL encoded and obtained from the request path
for a request coming into one of the standard binding endpoints.
For example the HTTP-Redirect binding request path will have the
format
{base}/{backend}/{co_name}/sso/redirect
:type context: satosa.context.Context
:rtype: str
:param context:
"""
url_encoded_co_name = context.path.split("/")[1]
co_name = unquote_plus(url_encoded_co_name)
return co_name | python | def _get_co_name_from_path(self, context):
"""
The CO name is URL encoded and obtained from the request path
for a request coming into one of the standard binding endpoints.
For example the HTTP-Redirect binding request path will have the
format
{base}/{backend}/{co_name}/sso/redirect
:type context: satosa.context.Context
:rtype: str
:param context:
"""
url_encoded_co_name = context.path.split("/")[1]
co_name = unquote_plus(url_encoded_co_name)
return co_name | [
"def",
"_get_co_name_from_path",
"(",
"self",
",",
"context",
")",
":",
"url_encoded_co_name",
"=",
"context",
".",
"path",
".",
"split",
"(",
"\"/\"",
")",
"[",
"1",
"]",
"co_name",
"=",
"unquote_plus",
"(",
"url_encoded_co_name",
")",
"return",
"co_name"
] | The CO name is URL encoded and obtained from the request path
for a request coming into one of the standard binding endpoints.
For example the HTTP-Redirect binding request path will have the
format
{base}/{backend}/{co_name}/sso/redirect
:type context: satosa.context.Context
:rtype: str
:param context: | [
"The",
"CO",
"name",
"is",
"URL",
"encoded",
"and",
"obtained",
"from",
"the",
"request",
"path",
"for",
"a",
"request",
"coming",
"into",
"one",
"of",
"the",
"standard",
"binding",
"endpoints",
".",
"For",
"example",
"the",
"HTTP",
"-",
"Redirect",
"binding",
"request",
"path",
"will",
"have",
"the",
"format"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L750-L768 | train | 231,850 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLVirtualCoFrontend._get_co_name | def _get_co_name(self, context):
"""
Obtain the CO name previously saved in the request state, or if not set
use the request path obtained from the current context to determine
the target CO.
:type context: The current context
:rtype: string
:param context: The current context
:return: CO name
"""
try:
co_name = context.state[self.name][self.KEY_CO_NAME]
logger.debug("Found CO {} from state".format(co_name))
except KeyError:
co_name = self._get_co_name_from_path(context)
logger.debug("Found CO {} from request path".format(co_name))
return co_name | python | def _get_co_name(self, context):
"""
Obtain the CO name previously saved in the request state, or if not set
use the request path obtained from the current context to determine
the target CO.
:type context: The current context
:rtype: string
:param context: The current context
:return: CO name
"""
try:
co_name = context.state[self.name][self.KEY_CO_NAME]
logger.debug("Found CO {} from state".format(co_name))
except KeyError:
co_name = self._get_co_name_from_path(context)
logger.debug("Found CO {} from request path".format(co_name))
return co_name | [
"def",
"_get_co_name",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"co_name",
"=",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"[",
"self",
".",
"KEY_CO_NAME",
"]",
"logger",
".",
"debug",
"(",
"\"Found CO {} from state\"",
".",
"format",
"(",
"co_name",
")",
")",
"except",
"KeyError",
":",
"co_name",
"=",
"self",
".",
"_get_co_name_from_path",
"(",
"context",
")",
"logger",
".",
"debug",
"(",
"\"Found CO {} from request path\"",
".",
"format",
"(",
"co_name",
")",
")",
"return",
"co_name"
] | Obtain the CO name previously saved in the request state, or if not set
use the request path obtained from the current context to determine
the target CO.
:type context: The current context
:rtype: string
:param context: The current context
:return: CO name | [
"Obtain",
"the",
"CO",
"name",
"previously",
"saved",
"in",
"the",
"request",
"state",
"or",
"if",
"not",
"set",
"use",
"the",
"request",
"path",
"obtained",
"from",
"the",
"current",
"context",
"to",
"determine",
"the",
"target",
"CO",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L770-L789 | train | 231,851 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLVirtualCoFrontend._add_endpoints_to_config | def _add_endpoints_to_config(self, config, co_name, backend_name):
"""
Use the request path from the context to determine the target backend,
then construct mappings from bindings to endpoints for the virtual
IdP for the CO.
The endpoint URLs have the form
{base}/{backend}/{co_name}/{path}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:type backend_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:param backend_name: The target backend name
:return: config with mappings for CO IdP
"""
for service, endpoint in self.endpoints.items():
idp_endpoints = []
for binding, path in endpoint.items():
url = "{base}/{backend}/{co_name}/{path}".format(
base=self.base_url,
backend=backend_name,
co_name=quote_plus(co_name),
path=path)
mapping = (url, binding)
idp_endpoints.append(mapping)
# Overwrite the IdP config with the CO specific mappings between
# SAML binding and URL endpoints.
config["service"]["idp"]["endpoints"][service] = idp_endpoints
return config | python | def _add_endpoints_to_config(self, config, co_name, backend_name):
"""
Use the request path from the context to determine the target backend,
then construct mappings from bindings to endpoints for the virtual
IdP for the CO.
The endpoint URLs have the form
{base}/{backend}/{co_name}/{path}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:type backend_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:param backend_name: The target backend name
:return: config with mappings for CO IdP
"""
for service, endpoint in self.endpoints.items():
idp_endpoints = []
for binding, path in endpoint.items():
url = "{base}/{backend}/{co_name}/{path}".format(
base=self.base_url,
backend=backend_name,
co_name=quote_plus(co_name),
path=path)
mapping = (url, binding)
idp_endpoints.append(mapping)
# Overwrite the IdP config with the CO specific mappings between
# SAML binding and URL endpoints.
config["service"]["idp"]["endpoints"][service] = idp_endpoints
return config | [
"def",
"_add_endpoints_to_config",
"(",
"self",
",",
"config",
",",
"co_name",
",",
"backend_name",
")",
":",
"for",
"service",
",",
"endpoint",
"in",
"self",
".",
"endpoints",
".",
"items",
"(",
")",
":",
"idp_endpoints",
"=",
"[",
"]",
"for",
"binding",
",",
"path",
"in",
"endpoint",
".",
"items",
"(",
")",
":",
"url",
"=",
"\"{base}/{backend}/{co_name}/{path}\"",
".",
"format",
"(",
"base",
"=",
"self",
".",
"base_url",
",",
"backend",
"=",
"backend_name",
",",
"co_name",
"=",
"quote_plus",
"(",
"co_name",
")",
",",
"path",
"=",
"path",
")",
"mapping",
"=",
"(",
"url",
",",
"binding",
")",
"idp_endpoints",
".",
"append",
"(",
"mapping",
")",
"# Overwrite the IdP config with the CO specific mappings between",
"# SAML binding and URL endpoints.",
"config",
"[",
"\"service\"",
"]",
"[",
"\"idp\"",
"]",
"[",
"\"endpoints\"",
"]",
"[",
"service",
"]",
"=",
"idp_endpoints",
"return",
"config"
] | Use the request path from the context to determine the target backend,
then construct mappings from bindings to endpoints for the virtual
IdP for the CO.
The endpoint URLs have the form
{base}/{backend}/{co_name}/{path}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:type backend_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:param backend_name: The target backend name
:return: config with mappings for CO IdP | [
"Use",
"the",
"request",
"path",
"from",
"the",
"context",
"to",
"determine",
"the",
"target",
"backend",
"then",
"construct",
"mappings",
"from",
"bindings",
"to",
"endpoints",
"for",
"the",
"virtual",
"IdP",
"for",
"the",
"CO",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L791-L828 | train | 231,852 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLVirtualCoFrontend._add_entity_id | def _add_entity_id(self, config, co_name):
"""
Use the CO name to construct the entity ID for the virtual IdP
for the CO.
The entity ID has the form
{base_entity_id}/{co_name}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated entity ID
"""
base_entity_id = config['entityid']
co_entity_id = "{}/{}".format(base_entity_id, quote_plus(co_name))
config['entityid'] = co_entity_id
return config | python | def _add_entity_id(self, config, co_name):
"""
Use the CO name to construct the entity ID for the virtual IdP
for the CO.
The entity ID has the form
{base_entity_id}/{co_name}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated entity ID
"""
base_entity_id = config['entityid']
co_entity_id = "{}/{}".format(base_entity_id, quote_plus(co_name))
config['entityid'] = co_entity_id
return config | [
"def",
"_add_entity_id",
"(",
"self",
",",
"config",
",",
"co_name",
")",
":",
"base_entity_id",
"=",
"config",
"[",
"'entityid'",
"]",
"co_entity_id",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"base_entity_id",
",",
"quote_plus",
"(",
"co_name",
")",
")",
"config",
"[",
"'entityid'",
"]",
"=",
"co_entity_id",
"return",
"config"
] | Use the CO name to construct the entity ID for the virtual IdP
for the CO.
The entity ID has the form
{base_entity_id}/{co_name}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated entity ID | [
"Use",
"the",
"CO",
"name",
"to",
"construct",
"the",
"entity",
"ID",
"for",
"the",
"virtual",
"IdP",
"for",
"the",
"CO",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L830-L852 | train | 231,853 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLVirtualCoFrontend._overlay_for_saml_metadata | def _overlay_for_saml_metadata(self, config, co_name):
"""
Overlay configuration details like organization and contact person
from the front end configuration onto the IdP configuration to
support SAML metadata generation.
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated details for SAML metadata
"""
for co in self.config[self.KEY_CO]:
if co[self.KEY_ENCODEABLE_NAME] == co_name:
break
key = self.KEY_ORGANIZATION
if key in co:
if key not in config:
config[key] = {}
for org_key in self.KEY_ORGANIZATION_KEYS:
if org_key in co[key]:
config[key][org_key] = co[key][org_key]
key = self.KEY_CONTACT_PERSON
if key in co:
config[key] = co[key]
return config | python | def _overlay_for_saml_metadata(self, config, co_name):
"""
Overlay configuration details like organization and contact person
from the front end configuration onto the IdP configuration to
support SAML metadata generation.
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated details for SAML metadata
"""
for co in self.config[self.KEY_CO]:
if co[self.KEY_ENCODEABLE_NAME] == co_name:
break
key = self.KEY_ORGANIZATION
if key in co:
if key not in config:
config[key] = {}
for org_key in self.KEY_ORGANIZATION_KEYS:
if org_key in co[key]:
config[key][org_key] = co[key][org_key]
key = self.KEY_CONTACT_PERSON
if key in co:
config[key] = co[key]
return config | [
"def",
"_overlay_for_saml_metadata",
"(",
"self",
",",
"config",
",",
"co_name",
")",
":",
"for",
"co",
"in",
"self",
".",
"config",
"[",
"self",
".",
"KEY_CO",
"]",
":",
"if",
"co",
"[",
"self",
".",
"KEY_ENCODEABLE_NAME",
"]",
"==",
"co_name",
":",
"break",
"key",
"=",
"self",
".",
"KEY_ORGANIZATION",
"if",
"key",
"in",
"co",
":",
"if",
"key",
"not",
"in",
"config",
":",
"config",
"[",
"key",
"]",
"=",
"{",
"}",
"for",
"org_key",
"in",
"self",
".",
"KEY_ORGANIZATION_KEYS",
":",
"if",
"org_key",
"in",
"co",
"[",
"key",
"]",
":",
"config",
"[",
"key",
"]",
"[",
"org_key",
"]",
"=",
"co",
"[",
"key",
"]",
"[",
"org_key",
"]",
"key",
"=",
"self",
".",
"KEY_CONTACT_PERSON",
"if",
"key",
"in",
"co",
":",
"config",
"[",
"key",
"]",
"=",
"co",
"[",
"key",
"]",
"return",
"config"
] | Overlay configuration details like organization and contact person
from the front end configuration onto the IdP configuration to
support SAML metadata generation.
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated details for SAML metadata | [
"Overlay",
"configuration",
"details",
"like",
"organization",
"and",
"contact",
"person",
"from",
"the",
"front",
"end",
"configuration",
"onto",
"the",
"IdP",
"configuration",
"to",
"support",
"SAML",
"metadata",
"generation",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L854-L885 | train | 231,854 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLVirtualCoFrontend._co_names_from_config | def _co_names_from_config(self):
"""
Parse the configuration for the names of the COs for which to
construct virtual IdPs.
:rtype: [str]
:return: list of CO names
"""
co_names = [co[self.KEY_ENCODEABLE_NAME] for
co in self.config[self.KEY_CO]]
return co_names | python | def _co_names_from_config(self):
"""
Parse the configuration for the names of the COs for which to
construct virtual IdPs.
:rtype: [str]
:return: list of CO names
"""
co_names = [co[self.KEY_ENCODEABLE_NAME] for
co in self.config[self.KEY_CO]]
return co_names | [
"def",
"_co_names_from_config",
"(",
"self",
")",
":",
"co_names",
"=",
"[",
"co",
"[",
"self",
".",
"KEY_ENCODEABLE_NAME",
"]",
"for",
"co",
"in",
"self",
".",
"config",
"[",
"self",
".",
"KEY_CO",
"]",
"]",
"return",
"co_names"
] | Parse the configuration for the names of the COs for which to
construct virtual IdPs.
:rtype: [str]
:return: list of CO names | [
"Parse",
"the",
"configuration",
"for",
"the",
"names",
"of",
"the",
"COs",
"for",
"which",
"to",
"construct",
"virtual",
"IdPs",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L887-L899 | train | 231,855 |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | SAMLVirtualCoFrontend._create_co_virtual_idp | def _create_co_virtual_idp(self, context):
"""
Create a virtual IdP to represent the CO.
:type context: The current context
:rtype: saml.server.Server
:param context:
:return: An idp server
"""
co_name = self._get_co_name(context)
context.decorate(self.KEY_CO_NAME, co_name)
# Verify that we are configured for this CO. If the CO was not
# configured most likely the endpoint used was not registered and
# SATOSA core code threw an exception before getting here, but we
# include this check in case later the regex used to register the
# endpoints is relaxed.
co_names = self._co_names_from_config()
if co_name not in co_names:
msg = "CO {} not in configured list of COs {}".format(co_name,
co_names)
satosa_logging(logger, logging.WARN, msg, context.state)
raise SATOSAError(msg)
# Make a copy of the general IdP config that we will then overwrite
# with mappings between SAML bindings and CO specific URL endpoints,
# and the entityID for the CO virtual IdP.
backend_name = context.target_backend
idp_config = copy.deepcopy(self.idp_config)
idp_config = self._add_endpoints_to_config(idp_config,
co_name,
backend_name)
idp_config = self._add_entity_id(idp_config, co_name)
# Use the overwritten IdP config to generate a pysaml2 config object
# and from it a server object.
pysaml2_idp_config = IdPConfig().load(idp_config,
metadata_construction=False)
server = Server(config=pysaml2_idp_config)
return server | python | def _create_co_virtual_idp(self, context):
"""
Create a virtual IdP to represent the CO.
:type context: The current context
:rtype: saml.server.Server
:param context:
:return: An idp server
"""
co_name = self._get_co_name(context)
context.decorate(self.KEY_CO_NAME, co_name)
# Verify that we are configured for this CO. If the CO was not
# configured most likely the endpoint used was not registered and
# SATOSA core code threw an exception before getting here, but we
# include this check in case later the regex used to register the
# endpoints is relaxed.
co_names = self._co_names_from_config()
if co_name not in co_names:
msg = "CO {} not in configured list of COs {}".format(co_name,
co_names)
satosa_logging(logger, logging.WARN, msg, context.state)
raise SATOSAError(msg)
# Make a copy of the general IdP config that we will then overwrite
# with mappings between SAML bindings and CO specific URL endpoints,
# and the entityID for the CO virtual IdP.
backend_name = context.target_backend
idp_config = copy.deepcopy(self.idp_config)
idp_config = self._add_endpoints_to_config(idp_config,
co_name,
backend_name)
idp_config = self._add_entity_id(idp_config, co_name)
# Use the overwritten IdP config to generate a pysaml2 config object
# and from it a server object.
pysaml2_idp_config = IdPConfig().load(idp_config,
metadata_construction=False)
server = Server(config=pysaml2_idp_config)
return server | [
"def",
"_create_co_virtual_idp",
"(",
"self",
",",
"context",
")",
":",
"co_name",
"=",
"self",
".",
"_get_co_name",
"(",
"context",
")",
"context",
".",
"decorate",
"(",
"self",
".",
"KEY_CO_NAME",
",",
"co_name",
")",
"# Verify that we are configured for this CO. If the CO was not",
"# configured most likely the endpoint used was not registered and",
"# SATOSA core code threw an exception before getting here, but we",
"# include this check in case later the regex used to register the",
"# endpoints is relaxed.",
"co_names",
"=",
"self",
".",
"_co_names_from_config",
"(",
")",
"if",
"co_name",
"not",
"in",
"co_names",
":",
"msg",
"=",
"\"CO {} not in configured list of COs {}\"",
".",
"format",
"(",
"co_name",
",",
"co_names",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARN",
",",
"msg",
",",
"context",
".",
"state",
")",
"raise",
"SATOSAError",
"(",
"msg",
")",
"# Make a copy of the general IdP config that we will then overwrite",
"# with mappings between SAML bindings and CO specific URL endpoints,",
"# and the entityID for the CO virtual IdP.",
"backend_name",
"=",
"context",
".",
"target_backend",
"idp_config",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"idp_config",
")",
"idp_config",
"=",
"self",
".",
"_add_endpoints_to_config",
"(",
"idp_config",
",",
"co_name",
",",
"backend_name",
")",
"idp_config",
"=",
"self",
".",
"_add_entity_id",
"(",
"idp_config",
",",
"co_name",
")",
"# Use the overwritten IdP config to generate a pysaml2 config object",
"# and from it a server object.",
"pysaml2_idp_config",
"=",
"IdPConfig",
"(",
")",
".",
"load",
"(",
"idp_config",
",",
"metadata_construction",
"=",
"False",
")",
"server",
"=",
"Server",
"(",
"config",
"=",
"pysaml2_idp_config",
")",
"return",
"server"
] | Create a virtual IdP to represent the CO.
:type context: The current context
:rtype: saml.server.Server
:param context:
:return: An idp server | [
"Create",
"a",
"virtual",
"IdP",
"to",
"represent",
"the",
"CO",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L901-L943 | train | 231,856 |
IdentityPython/SATOSA | src/satosa/backends/oauth.py | _OAuthBackend._authn_response | def _authn_response(self, context):
"""
Handles the authentication response from the AS.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The context in SATOSA
:return: A SATOSA response. This method is only responsible to call the callback function
which generates the Response object.
"""
state_data = context.state[self.name]
aresp = self.consumer.parse_response(AuthorizationResponse, info=json.dumps(context.request))
self._verify_state(aresp, state_data, context.state)
rargs = {"code": aresp["code"], "redirect_uri": self.redirect_url,
"state": state_data["state"]}
atresp = self.consumer.do_access_token_request(request_args=rargs, state=aresp["state"])
if "verify_accesstoken_state" not in self.config or self.config["verify_accesstoken_state"]:
self._verify_state(atresp, state_data, context.state)
user_info = self.user_information(atresp["access_token"])
internal_response = InternalData(auth_info=self.auth_info(context.request))
internal_response.attributes = self.converter.to_internal(self.external_type, user_info)
internal_response.subject_id = user_info[self.user_id_attr]
del context.state[self.name]
return self.auth_callback_func(context, internal_response) | python | def _authn_response(self, context):
"""
Handles the authentication response from the AS.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The context in SATOSA
:return: A SATOSA response. This method is only responsible to call the callback function
which generates the Response object.
"""
state_data = context.state[self.name]
aresp = self.consumer.parse_response(AuthorizationResponse, info=json.dumps(context.request))
self._verify_state(aresp, state_data, context.state)
rargs = {"code": aresp["code"], "redirect_uri": self.redirect_url,
"state": state_data["state"]}
atresp = self.consumer.do_access_token_request(request_args=rargs, state=aresp["state"])
if "verify_accesstoken_state" not in self.config or self.config["verify_accesstoken_state"]:
self._verify_state(atresp, state_data, context.state)
user_info = self.user_information(atresp["access_token"])
internal_response = InternalData(auth_info=self.auth_info(context.request))
internal_response.attributes = self.converter.to_internal(self.external_type, user_info)
internal_response.subject_id = user_info[self.user_id_attr]
del context.state[self.name]
return self.auth_callback_func(context, internal_response) | [
"def",
"_authn_response",
"(",
"self",
",",
"context",
")",
":",
"state_data",
"=",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"aresp",
"=",
"self",
".",
"consumer",
".",
"parse_response",
"(",
"AuthorizationResponse",
",",
"info",
"=",
"json",
".",
"dumps",
"(",
"context",
".",
"request",
")",
")",
"self",
".",
"_verify_state",
"(",
"aresp",
",",
"state_data",
",",
"context",
".",
"state",
")",
"rargs",
"=",
"{",
"\"code\"",
":",
"aresp",
"[",
"\"code\"",
"]",
",",
"\"redirect_uri\"",
":",
"self",
".",
"redirect_url",
",",
"\"state\"",
":",
"state_data",
"[",
"\"state\"",
"]",
"}",
"atresp",
"=",
"self",
".",
"consumer",
".",
"do_access_token_request",
"(",
"request_args",
"=",
"rargs",
",",
"state",
"=",
"aresp",
"[",
"\"state\"",
"]",
")",
"if",
"\"verify_accesstoken_state\"",
"not",
"in",
"self",
".",
"config",
"or",
"self",
".",
"config",
"[",
"\"verify_accesstoken_state\"",
"]",
":",
"self",
".",
"_verify_state",
"(",
"atresp",
",",
"state_data",
",",
"context",
".",
"state",
")",
"user_info",
"=",
"self",
".",
"user_information",
"(",
"atresp",
"[",
"\"access_token\"",
"]",
")",
"internal_response",
"=",
"InternalData",
"(",
"auth_info",
"=",
"self",
".",
"auth_info",
"(",
"context",
".",
"request",
")",
")",
"internal_response",
".",
"attributes",
"=",
"self",
".",
"converter",
".",
"to_internal",
"(",
"self",
".",
"external_type",
",",
"user_info",
")",
"internal_response",
".",
"subject_id",
"=",
"user_info",
"[",
"self",
".",
"user_id_attr",
"]",
"del",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"return",
"self",
".",
"auth_callback_func",
"(",
"context",
",",
"internal_response",
")"
] | Handles the authentication response from the AS.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The context in SATOSA
:return: A SATOSA response. This method is only responsible to call the callback function
which generates the Response object. | [
"Handles",
"the",
"authentication",
"response",
"from",
"the",
"AS",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/oauth.py#L117-L143 | train | 231,857 |
IdentityPython/SATOSA | src/satosa/util.py | hash_data | def hash_data(salt, value, hash_alg=None):
"""
Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together with the salt
:return: hashed value
"""
hash_alg = hash_alg or 'sha512'
hasher = hashlib.new(hash_alg)
hasher.update(value.encode('utf-8'))
hasher.update(salt.encode('utf-8'))
value_hashed = hasher.hexdigest()
return value_hashed | python | def hash_data(salt, value, hash_alg=None):
"""
Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together with the salt
:return: hashed value
"""
hash_alg = hash_alg or 'sha512'
hasher = hashlib.new(hash_alg)
hasher.update(value.encode('utf-8'))
hasher.update(salt.encode('utf-8'))
value_hashed = hasher.hexdigest()
return value_hashed | [
"def",
"hash_data",
"(",
"salt",
",",
"value",
",",
"hash_alg",
"=",
"None",
")",
":",
"hash_alg",
"=",
"hash_alg",
"or",
"'sha512'",
"hasher",
"=",
"hashlib",
".",
"new",
"(",
"hash_alg",
")",
"hasher",
".",
"update",
"(",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"hasher",
".",
"update",
"(",
"salt",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"value_hashed",
"=",
"hasher",
".",
"hexdigest",
"(",
")",
"return",
"value_hashed"
] | Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together with the salt
:return: hashed value | [
"Hashes",
"a",
"value",
"together",
"with",
"a",
"salt",
"with",
"the",
"given",
"hash",
"algorithm",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/util.py#L15-L32 | train | 231,858 |
IdentityPython/SATOSA | src/satosa/micro_services/ldap_attribute_store.py | LdapAttributeStore._construct_filter_value | def _construct_filter_value(self, candidate, data):
"""
Construct and return a LDAP directory search filter value from the
candidate identifier.
Argument 'canidate' is a dictionary with one required key and
two optional keys:
key required value
--------------- -------- ---------------------------------
attribute_names Y list of identifier names
name_id_format N NameID format (string)
add_scope N "issuer_entityid" or other string
Argument 'data' is that object passed into the microservice
method process().
If the attribute_names list consists of more than one identifier
name then the values of the identifiers will be concatenated together
to create the filter value.
If one of the identifier names in the attribute_names is the string
'name_id' then the NameID value with format name_id_format
will be concatenated to the filter value.
If the add_scope key is present with value 'issuer_entityid' then the
entityID for the IdP will be concatenated to "scope" the value. If the
string is any other value it will be directly concatenated.
"""
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "Input attributes {}".format(attributes), context.state)
# Get the values configured list of identifier names for this candidate
# and substitute None if there are no values for a configured identifier.
values = []
for identifier_name in candidate['attribute_names']:
v = attributes.get(identifier_name, None)
if isinstance(v, list):
v = v[0]
values.append(v)
satosa_logging(logger, logging.DEBUG, "Found candidate values {}".format(values), context.state)
# If one of the configured identifier names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "IdP asserted NameID {}".format(name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "Added NameID {} to candidate values".format(candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "NameID {} value also asserted as attribute value".format(candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of identifier names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "Candidate is missing value so skipping", context.state)
return None
# All values for the configured list of attribute names are present
# so we can create a value. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "Added scope {} to values".format(scope), context.state)
values.append(scope)
# Concatenate all values to create the filter value.
value = ''.join(values)
satosa_logging(logger, logging.DEBUG, "Constructed filter value {}".format(value), context.state)
return value | python | def _construct_filter_value(self, candidate, data):
"""
Construct and return a LDAP directory search filter value from the
candidate identifier.
Argument 'canidate' is a dictionary with one required key and
two optional keys:
key required value
--------------- -------- ---------------------------------
attribute_names Y list of identifier names
name_id_format N NameID format (string)
add_scope N "issuer_entityid" or other string
Argument 'data' is that object passed into the microservice
method process().
If the attribute_names list consists of more than one identifier
name then the values of the identifiers will be concatenated together
to create the filter value.
If one of the identifier names in the attribute_names is the string
'name_id' then the NameID value with format name_id_format
will be concatenated to the filter value.
If the add_scope key is present with value 'issuer_entityid' then the
entityID for the IdP will be concatenated to "scope" the value. If the
string is any other value it will be directly concatenated.
"""
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "Input attributes {}".format(attributes), context.state)
# Get the values configured list of identifier names for this candidate
# and substitute None if there are no values for a configured identifier.
values = []
for identifier_name in candidate['attribute_names']:
v = attributes.get(identifier_name, None)
if isinstance(v, list):
v = v[0]
values.append(v)
satosa_logging(logger, logging.DEBUG, "Found candidate values {}".format(values), context.state)
# If one of the configured identifier names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "IdP asserted NameID {}".format(name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "Added NameID {} to candidate values".format(candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "NameID {} value also asserted as attribute value".format(candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of identifier names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "Candidate is missing value so skipping", context.state)
return None
# All values for the configured list of attribute names are present
# so we can create a value. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "Added scope {} to values".format(scope), context.state)
values.append(scope)
# Concatenate all values to create the filter value.
value = ''.join(values)
satosa_logging(logger, logging.DEBUG, "Constructed filter value {}".format(value), context.state)
return value | [
"def",
"_construct_filter_value",
"(",
"self",
",",
"candidate",
",",
"data",
")",
":",
"context",
"=",
"self",
".",
"context",
"attributes",
"=",
"data",
".",
"attributes",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Input attributes {}\"",
".",
"format",
"(",
"attributes",
")",
",",
"context",
".",
"state",
")",
"# Get the values configured list of identifier names for this candidate",
"# and substitute None if there are no values for a configured identifier.",
"values",
"=",
"[",
"]",
"for",
"identifier_name",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
":",
"v",
"=",
"attributes",
".",
"get",
"(",
"identifier_name",
",",
"None",
")",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"v",
"=",
"v",
"[",
"0",
"]",
"values",
".",
"append",
"(",
"v",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Found candidate values {}\"",
".",
"format",
"(",
"values",
")",
",",
"context",
".",
"state",
")",
"# If one of the configured identifier names is name_id then if there is also a configured",
"# name_id_format add the value for the NameID of that format if it was asserted by the IdP",
"# or else add the value None.",
"if",
"'name_id'",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
":",
"candidate_nameid_value",
"=",
"None",
"candidate_name_id_format",
"=",
"candidate",
".",
"get",
"(",
"'name_id_format'",
")",
"name_id_value",
"=",
"data",
".",
"subject_id",
"name_id_format",
"=",
"data",
".",
"subject_type",
"if",
"(",
"name_id_value",
"and",
"candidate_name_id_format",
"and",
"candidate_name_id_format",
"==",
"name_id_format",
")",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"IdP asserted NameID {}\"",
".",
"format",
"(",
"name_id_value",
")",
",",
"context",
".",
"state",
")",
"candidate_nameid_value",
"=",
"name_id_value",
"# Only add the NameID value asserted by the IdP if it is not already",
"# in the list of values. This is necessary because some non-compliant IdPs",
"# have been known, for example, to assert the value of eduPersonPrincipalName",
"# in the value for SAML2 persistent NameID as well as asserting",
"# eduPersonPrincipalName.",
"if",
"candidate_nameid_value",
"not",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added NameID {} to candidate values\"",
".",
"format",
"(",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"candidate_nameid_value",
")",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARN",
",",
"\"NameID {} value also asserted as attribute value\"",
".",
"format",
"(",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"# If no value was asserted by the IdP for one of the configured list of identifier names",
"# for this candidate then go onto the next candidate.",
"if",
"None",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Candidate is missing value so skipping\"",
",",
"context",
".",
"state",
")",
"return",
"None",
"# All values for the configured list of attribute names are present",
"# so we can create a value. Add a scope if configured",
"# to do so.",
"if",
"'add_scope'",
"in",
"candidate",
":",
"if",
"candidate",
"[",
"'add_scope'",
"]",
"==",
"'issuer_entityid'",
":",
"scope",
"=",
"data",
".",
"auth_info",
".",
"issuer",
"else",
":",
"scope",
"=",
"candidate",
"[",
"'add_scope'",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added scope {} to values\"",
".",
"format",
"(",
"scope",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"scope",
")",
"# Concatenate all values to create the filter value.",
"value",
"=",
"''",
".",
"join",
"(",
"values",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Constructed filter value {}\"",
".",
"format",
"(",
"value",
")",
",",
"context",
".",
"state",
")",
"return",
"value"
] | Construct and return a LDAP directory search filter value from the
candidate identifier.
Argument 'canidate' is a dictionary with one required key and
two optional keys:
key required value
--------------- -------- ---------------------------------
attribute_names Y list of identifier names
name_id_format N NameID format (string)
add_scope N "issuer_entityid" or other string
Argument 'data' is that object passed into the microservice
method process().
If the attribute_names list consists of more than one identifier
name then the values of the identifiers will be concatenated together
to create the filter value.
If one of the identifier names in the attribute_names is the string
'name_id' then the NameID value with format name_id_format
will be concatenated to the filter value.
If the add_scope key is present with value 'issuer_entityid' then the
entityID for the IdP will be concatenated to "scope" the value. If the
string is any other value it will be directly concatenated. | [
"Construct",
"and",
"return",
"a",
"LDAP",
"directory",
"search",
"filter",
"value",
"from",
"the",
"candidate",
"identifier",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L119-L214 | train | 231,859 |
IdentityPython/SATOSA | src/satosa/micro_services/ldap_attribute_store.py | LdapAttributeStore._filter_config | def _filter_config(self, config, fields=None):
"""
Filter sensitive details like passwords from a configuration
dictionary.
"""
filter_fields_default = [
'bind_password',
'connection'
]
filter_fields = fields or filter_fields_default
return dict(
map(
lambda key: (key, '<hidden>' if key in filter_fields else config[key]),
config.keys()
)
) | python | def _filter_config(self, config, fields=None):
"""
Filter sensitive details like passwords from a configuration
dictionary.
"""
filter_fields_default = [
'bind_password',
'connection'
]
filter_fields = fields or filter_fields_default
return dict(
map(
lambda key: (key, '<hidden>' if key in filter_fields else config[key]),
config.keys()
)
) | [
"def",
"_filter_config",
"(",
"self",
",",
"config",
",",
"fields",
"=",
"None",
")",
":",
"filter_fields_default",
"=",
"[",
"'bind_password'",
",",
"'connection'",
"]",
"filter_fields",
"=",
"fields",
"or",
"filter_fields_default",
"return",
"dict",
"(",
"map",
"(",
"lambda",
"key",
":",
"(",
"key",
",",
"'<hidden>'",
"if",
"key",
"in",
"filter_fields",
"else",
"config",
"[",
"key",
"]",
")",
",",
"config",
".",
"keys",
"(",
")",
")",
")"
] | Filter sensitive details like passwords from a configuration
dictionary. | [
"Filter",
"sensitive",
"details",
"like",
"passwords",
"from",
"a",
"configuration",
"dictionary",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L216-L232 | train | 231,860 |
IdentityPython/SATOSA | src/satosa/micro_services/ldap_attribute_store.py | LdapAttributeStore._ldap_connection_factory | def _ldap_connection_factory(self, config):
"""
Use the input configuration to instantiate and return
a ldap3 Connection object.
"""
ldap_url = config['ldap_url']
bind_dn = config['bind_dn']
bind_password = config['bind_password']
if not ldap_url:
raise LdapAttributeStoreError("ldap_url is not configured")
if not bind_dn:
raise LdapAttributeStoreError("bind_dn is not configured")
if not bind_password:
raise LdapAttributeStoreError("bind_password is not configured")
pool_size = config['pool_size']
pool_keepalive = config['pool_keepalive']
server = ldap3.Server(config['ldap_url'])
satosa_logging(logger, logging.DEBUG, "Creating a new LDAP connection", None)
satosa_logging(logger, logging.DEBUG, "Using LDAP URL {}".format(ldap_url), None)
satosa_logging(logger, logging.DEBUG, "Using bind DN {}".format(bind_dn), None)
satosa_logging(logger, logging.DEBUG, "Using pool size {}".format(pool_size), None)
satosa_logging(logger, logging.DEBUG, "Using pool keep alive {}".format(pool_keepalive), None)
try:
connection = ldap3.Connection(
server,
bind_dn,
bind_password,
auto_bind=True,
client_strategy=ldap3.REUSABLE,
pool_size=pool_size,
pool_keepalive=pool_keepalive
)
except LDAPException as e:
msg = "Caught exception when connecting to LDAP server: {}".format(e)
satosa_logging(logger, logging.ERROR, msg, None)
raise LdapAttributeStoreError(msg)
satosa_logging(logger, logging.DEBUG, "Successfully connected to LDAP server", None)
return connection | python | def _ldap_connection_factory(self, config):
"""
Use the input configuration to instantiate and return
a ldap3 Connection object.
"""
ldap_url = config['ldap_url']
bind_dn = config['bind_dn']
bind_password = config['bind_password']
if not ldap_url:
raise LdapAttributeStoreError("ldap_url is not configured")
if not bind_dn:
raise LdapAttributeStoreError("bind_dn is not configured")
if not bind_password:
raise LdapAttributeStoreError("bind_password is not configured")
pool_size = config['pool_size']
pool_keepalive = config['pool_keepalive']
server = ldap3.Server(config['ldap_url'])
satosa_logging(logger, logging.DEBUG, "Creating a new LDAP connection", None)
satosa_logging(logger, logging.DEBUG, "Using LDAP URL {}".format(ldap_url), None)
satosa_logging(logger, logging.DEBUG, "Using bind DN {}".format(bind_dn), None)
satosa_logging(logger, logging.DEBUG, "Using pool size {}".format(pool_size), None)
satosa_logging(logger, logging.DEBUG, "Using pool keep alive {}".format(pool_keepalive), None)
try:
connection = ldap3.Connection(
server,
bind_dn,
bind_password,
auto_bind=True,
client_strategy=ldap3.REUSABLE,
pool_size=pool_size,
pool_keepalive=pool_keepalive
)
except LDAPException as e:
msg = "Caught exception when connecting to LDAP server: {}".format(e)
satosa_logging(logger, logging.ERROR, msg, None)
raise LdapAttributeStoreError(msg)
satosa_logging(logger, logging.DEBUG, "Successfully connected to LDAP server", None)
return connection | [
"def",
"_ldap_connection_factory",
"(",
"self",
",",
"config",
")",
":",
"ldap_url",
"=",
"config",
"[",
"'ldap_url'",
"]",
"bind_dn",
"=",
"config",
"[",
"'bind_dn'",
"]",
"bind_password",
"=",
"config",
"[",
"'bind_password'",
"]",
"if",
"not",
"ldap_url",
":",
"raise",
"LdapAttributeStoreError",
"(",
"\"ldap_url is not configured\"",
")",
"if",
"not",
"bind_dn",
":",
"raise",
"LdapAttributeStoreError",
"(",
"\"bind_dn is not configured\"",
")",
"if",
"not",
"bind_password",
":",
"raise",
"LdapAttributeStoreError",
"(",
"\"bind_password is not configured\"",
")",
"pool_size",
"=",
"config",
"[",
"'pool_size'",
"]",
"pool_keepalive",
"=",
"config",
"[",
"'pool_keepalive'",
"]",
"server",
"=",
"ldap3",
".",
"Server",
"(",
"config",
"[",
"'ldap_url'",
"]",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Creating a new LDAP connection\"",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using LDAP URL {}\"",
".",
"format",
"(",
"ldap_url",
")",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using bind DN {}\"",
".",
"format",
"(",
"bind_dn",
")",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using pool size {}\"",
".",
"format",
"(",
"pool_size",
")",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using pool keep alive {}\"",
".",
"format",
"(",
"pool_keepalive",
")",
",",
"None",
")",
"try",
":",
"connection",
"=",
"ldap3",
".",
"Connection",
"(",
"server",
",",
"bind_dn",
",",
"bind_password",
",",
"auto_bind",
"=",
"True",
",",
"client_strategy",
"=",
"ldap3",
".",
"REUSABLE",
",",
"pool_size",
"=",
"pool_size",
",",
"pool_keepalive",
"=",
"pool_keepalive",
")",
"except",
"LDAPException",
"as",
"e",
":",
"msg",
"=",
"\"Caught exception when connecting to LDAP server: {}\"",
".",
"format",
"(",
"e",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"msg",
",",
"None",
")",
"raise",
"LdapAttributeStoreError",
"(",
"msg",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Successfully connected to LDAP server\"",
",",
"None",
")",
"return",
"connection"
] | Use the input configuration to instantiate and return
a ldap3 Connection object. | [
"Use",
"the",
"input",
"configuration",
"to",
"instantiate",
"and",
"return",
"a",
"ldap3",
"Connection",
"object",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L234-L279 | train | 231,861 |
IdentityPython/SATOSA | src/satosa/micro_services/ldap_attribute_store.py | LdapAttributeStore._populate_attributes | def _populate_attributes(self, config, record, context, data):
"""
Use a record found in LDAP to populate attributes.
"""
search_return_attributes = config['search_return_attributes']
for attr in search_return_attributes.keys():
if attr in record["attributes"]:
if record["attributes"][attr]:
data.attributes[search_return_attributes[attr]] = record["attributes"][attr]
satosa_logging(
logger,
logging.DEBUG,
"Setting internal attribute {} with values {}".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
)
else:
satosa_logging(
logger,
logging.DEBUG,
"Not setting internal attribute {} because value {} is null or empty".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
) | python | def _populate_attributes(self, config, record, context, data):
"""
Use a record found in LDAP to populate attributes.
"""
search_return_attributes = config['search_return_attributes']
for attr in search_return_attributes.keys():
if attr in record["attributes"]:
if record["attributes"][attr]:
data.attributes[search_return_attributes[attr]] = record["attributes"][attr]
satosa_logging(
logger,
logging.DEBUG,
"Setting internal attribute {} with values {}".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
)
else:
satosa_logging(
logger,
logging.DEBUG,
"Not setting internal attribute {} because value {} is null or empty".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
) | [
"def",
"_populate_attributes",
"(",
"self",
",",
"config",
",",
"record",
",",
"context",
",",
"data",
")",
":",
"search_return_attributes",
"=",
"config",
"[",
"'search_return_attributes'",
"]",
"for",
"attr",
"in",
"search_return_attributes",
".",
"keys",
"(",
")",
":",
"if",
"attr",
"in",
"record",
"[",
"\"attributes\"",
"]",
":",
"if",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
":",
"data",
".",
"attributes",
"[",
"search_return_attributes",
"[",
"attr",
"]",
"]",
"=",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Setting internal attribute {} with values {}\"",
".",
"format",
"(",
"search_return_attributes",
"[",
"attr",
"]",
",",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
")",
",",
"context",
".",
"state",
")",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Not setting internal attribute {} because value {} is null or empty\"",
".",
"format",
"(",
"search_return_attributes",
"[",
"attr",
"]",
",",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
")",
",",
"context",
".",
"state",
")"
] | Use a record found in LDAP to populate attributes. | [
"Use",
"a",
"record",
"found",
"in",
"LDAP",
"to",
"populate",
"attributes",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L281-L308 | train | 231,862 |
IdentityPython/SATOSA | src/satosa/micro_services/ldap_attribute_store.py | LdapAttributeStore._populate_input_for_name_id | def _populate_input_for_name_id(self, config, record, context, data):
"""
Use a record found in LDAP to populate input for
NameID generation.
"""
user_id = ""
user_id_from_attrs = config['user_id_from_attrs']
for attr in user_id_from_attrs:
if attr in record["attributes"]:
value = record["attributes"][attr]
if isinstance(value, list):
# Use a default sort to ensure some predictability since the
# LDAP directory server may return multi-valued attributes
# in any order.
value.sort()
user_id += "".join(value)
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with values {} to input for NameID".format(attr, value),
context.state
)
else:
user_id += value
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with value {} to input for NameID".format(attr, value),
context.state
)
if not user_id:
satosa_logging(
logger,
logging.WARNING,
"Input for NameID is empty so not overriding default",
context.state
)
else:
data.subject_id = user_id
satosa_logging(
logger,
logging.DEBUG,
"Input for NameID is {}".format(data.subject_id),
context.state
) | python | def _populate_input_for_name_id(self, config, record, context, data):
"""
Use a record found in LDAP to populate input for
NameID generation.
"""
user_id = ""
user_id_from_attrs = config['user_id_from_attrs']
for attr in user_id_from_attrs:
if attr in record["attributes"]:
value = record["attributes"][attr]
if isinstance(value, list):
# Use a default sort to ensure some predictability since the
# LDAP directory server may return multi-valued attributes
# in any order.
value.sort()
user_id += "".join(value)
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with values {} to input for NameID".format(attr, value),
context.state
)
else:
user_id += value
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with value {} to input for NameID".format(attr, value),
context.state
)
if not user_id:
satosa_logging(
logger,
logging.WARNING,
"Input for NameID is empty so not overriding default",
context.state
)
else:
data.subject_id = user_id
satosa_logging(
logger,
logging.DEBUG,
"Input for NameID is {}".format(data.subject_id),
context.state
) | [
"def",
"_populate_input_for_name_id",
"(",
"self",
",",
"config",
",",
"record",
",",
"context",
",",
"data",
")",
":",
"user_id",
"=",
"\"\"",
"user_id_from_attrs",
"=",
"config",
"[",
"'user_id_from_attrs'",
"]",
"for",
"attr",
"in",
"user_id_from_attrs",
":",
"if",
"attr",
"in",
"record",
"[",
"\"attributes\"",
"]",
":",
"value",
"=",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"# Use a default sort to ensure some predictability since the",
"# LDAP directory server may return multi-valued attributes",
"# in any order.",
"value",
".",
"sort",
"(",
")",
"user_id",
"+=",
"\"\"",
".",
"join",
"(",
"value",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added attribute {} with values {} to input for NameID\"",
".",
"format",
"(",
"attr",
",",
"value",
")",
",",
"context",
".",
"state",
")",
"else",
":",
"user_id",
"+=",
"value",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added attribute {} with value {} to input for NameID\"",
".",
"format",
"(",
"attr",
",",
"value",
")",
",",
"context",
".",
"state",
")",
"if",
"not",
"user_id",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARNING",
",",
"\"Input for NameID is empty so not overriding default\"",
",",
"context",
".",
"state",
")",
"else",
":",
"data",
".",
"subject_id",
"=",
"user_id",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Input for NameID is {}\"",
".",
"format",
"(",
"data",
".",
"subject_id",
")",
",",
"context",
".",
"state",
")"
] | Use a record found in LDAP to populate input for
NameID generation. | [
"Use",
"a",
"record",
"found",
"in",
"LDAP",
"to",
"populate",
"input",
"for",
"NameID",
"generation",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L310-L354 | train | 231,863 |
IdentityPython/SATOSA | src/satosa/satosa_config.py | SATOSAConfig._verify_dict | def _verify_dict(self, conf):
"""
Check that the configuration contains all necessary keys.
:type conf: dict
:rtype: None
:raise SATOSAConfigurationError: if the configuration is incorrect
:param conf: config to verify
:return: None
"""
if not conf:
raise SATOSAConfigurationError("Missing configuration or unknown format")
for key in SATOSAConfig.mandatory_dict_keys:
if key not in conf:
raise SATOSAConfigurationError("Missing key '%s' in config" % key)
for key in SATOSAConfig.sensitive_dict_keys:
if key not in conf and "SATOSA_{key}".format(key=key) not in os.environ:
raise SATOSAConfigurationError("Missing key '%s' from config and ENVIRONMENT" % key) | python | def _verify_dict(self, conf):
"""
Check that the configuration contains all necessary keys.
:type conf: dict
:rtype: None
:raise SATOSAConfigurationError: if the configuration is incorrect
:param conf: config to verify
:return: None
"""
if not conf:
raise SATOSAConfigurationError("Missing configuration or unknown format")
for key in SATOSAConfig.mandatory_dict_keys:
if key not in conf:
raise SATOSAConfigurationError("Missing key '%s' in config" % key)
for key in SATOSAConfig.sensitive_dict_keys:
if key not in conf and "SATOSA_{key}".format(key=key) not in os.environ:
raise SATOSAConfigurationError("Missing key '%s' from config and ENVIRONMENT" % key) | [
"def",
"_verify_dict",
"(",
"self",
",",
"conf",
")",
":",
"if",
"not",
"conf",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Missing configuration or unknown format\"",
")",
"for",
"key",
"in",
"SATOSAConfig",
".",
"mandatory_dict_keys",
":",
"if",
"key",
"not",
"in",
"conf",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Missing key '%s' in config\"",
"%",
"key",
")",
"for",
"key",
"in",
"SATOSAConfig",
".",
"sensitive_dict_keys",
":",
"if",
"key",
"not",
"in",
"conf",
"and",
"\"SATOSA_{key}\"",
".",
"format",
"(",
"key",
"=",
"key",
")",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Missing key '%s' from config and ENVIRONMENT\"",
"%",
"key",
")"
] | Check that the configuration contains all necessary keys.
:type conf: dict
:rtype: None
:raise SATOSAConfigurationError: if the configuration is incorrect
:param conf: config to verify
:return: None | [
"Check",
"that",
"the",
"configuration",
"contains",
"all",
"necessary",
"keys",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/satosa_config.py#L68-L88 | train | 231,864 |
IdentityPython/SATOSA | src/satosa/satosa_config.py | SATOSAConfig._load_yaml | def _load_yaml(self, config_file):
"""
Load config from yaml file or string
:type config_file: str
:rtype: dict
:param config_file: config to load. Can be file path or yaml string
:return: Loaded config
"""
try:
with open(config_file) as f:
return yaml.safe_load(f.read())
except yaml.YAMLError as exc:
logger.error("Could not parse config as YAML: {}", str(exc))
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
logger.error("Error position: (%s:%s)" % (mark.line + 1, mark.column + 1))
except IOError as e:
logger.debug("Could not open config file: {}", str(e))
return None | python | def _load_yaml(self, config_file):
"""
Load config from yaml file or string
:type config_file: str
:rtype: dict
:param config_file: config to load. Can be file path or yaml string
:return: Loaded config
"""
try:
with open(config_file) as f:
return yaml.safe_load(f.read())
except yaml.YAMLError as exc:
logger.error("Could not parse config as YAML: {}", str(exc))
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
logger.error("Error position: (%s:%s)" % (mark.line + 1, mark.column + 1))
except IOError as e:
logger.debug("Could not open config file: {}", str(e))
return None | [
"def",
"_load_yaml",
"(",
"self",
",",
"config_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"config_file",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"f",
".",
"read",
"(",
")",
")",
"except",
"yaml",
".",
"YAMLError",
"as",
"exc",
":",
"logger",
".",
"error",
"(",
"\"Could not parse config as YAML: {}\"",
",",
"str",
"(",
"exc",
")",
")",
"if",
"hasattr",
"(",
"exc",
",",
"'problem_mark'",
")",
":",
"mark",
"=",
"exc",
".",
"problem_mark",
"logger",
".",
"error",
"(",
"\"Error position: (%s:%s)\"",
"%",
"(",
"mark",
".",
"line",
"+",
"1",
",",
"mark",
".",
"column",
"+",
"1",
")",
")",
"except",
"IOError",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"\"Could not open config file: {}\"",
",",
"str",
"(",
"e",
")",
")",
"return",
"None"
] | Load config from yaml file or string
:type config_file: str
:rtype: dict
:param config_file: config to load. Can be file path or yaml string
:return: Loaded config | [
"Load",
"config",
"from",
"yaml",
"file",
"or",
"string"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/satosa_config.py#L136-L157 | train | 231,865 |
IdentityPython/SATOSA | src/satosa/logging_util.py | satosa_logging | def satosa_logging(logger, level, message, state, **kwargs):
"""
Adds a session ID to the message.
:type logger: logging
:type level: int
:type message: str
:type state: satosa.state.State
:param logger: Logger to use
:param level: Logger level (ex: logging.DEBUG/logging.WARN/...)
:param message: Message
:param state: The current state
:param kwargs: set exc_info=True to get an exception stack trace in the log
"""
if state is None:
session_id = "UNKNOWN"
else:
try:
session_id = state[LOGGER_STATE_KEY]
except KeyError:
session_id = uuid4().urn
state[LOGGER_STATE_KEY] = session_id
logger.log(level, "[{id}] {msg}".format(id=session_id, msg=message), **kwargs) | python | def satosa_logging(logger, level, message, state, **kwargs):
"""
Adds a session ID to the message.
:type logger: logging
:type level: int
:type message: str
:type state: satosa.state.State
:param logger: Logger to use
:param level: Logger level (ex: logging.DEBUG/logging.WARN/...)
:param message: Message
:param state: The current state
:param kwargs: set exc_info=True to get an exception stack trace in the log
"""
if state is None:
session_id = "UNKNOWN"
else:
try:
session_id = state[LOGGER_STATE_KEY]
except KeyError:
session_id = uuid4().urn
state[LOGGER_STATE_KEY] = session_id
logger.log(level, "[{id}] {msg}".format(id=session_id, msg=message), **kwargs) | [
"def",
"satosa_logging",
"(",
"logger",
",",
"level",
",",
"message",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"state",
"is",
"None",
":",
"session_id",
"=",
"\"UNKNOWN\"",
"else",
":",
"try",
":",
"session_id",
"=",
"state",
"[",
"LOGGER_STATE_KEY",
"]",
"except",
"KeyError",
":",
"session_id",
"=",
"uuid4",
"(",
")",
".",
"urn",
"state",
"[",
"LOGGER_STATE_KEY",
"]",
"=",
"session_id",
"logger",
".",
"log",
"(",
"level",
",",
"\"[{id}] {msg}\"",
".",
"format",
"(",
"id",
"=",
"session_id",
",",
"msg",
"=",
"message",
")",
",",
"*",
"*",
"kwargs",
")"
] | Adds a session ID to the message.
:type logger: logging
:type level: int
:type message: str
:type state: satosa.state.State
:param logger: Logger to use
:param level: Logger level (ex: logging.DEBUG/logging.WARN/...)
:param message: Message
:param state: The current state
:param kwargs: set exc_info=True to get an exception stack trace in the log | [
"Adds",
"a",
"session",
"ID",
"to",
"the",
"message",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/logging_util.py#L10-L33 | train | 231,866 |
IdentityPython/SATOSA | src/satosa/micro_services/consent.py | Consent.process | def process(self, context, internal_response):
"""
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
consent_state = context.state[STATE_KEY]
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_state["filter"])
id_hash = self._get_consent_id(internal_response.requester, internal_response.subject_id,
internal_response.attributes)
try:
# Check if consent is already given
consent_attributes = self._verify_consent(id_hash)
except requests.exceptions.ConnectionError as e:
satosa_logging(logger, logging.ERROR,
"Consent service is not reachable, no consent given.", context.state)
# Send an internal_response without any attributes
internal_response.attributes = {}
return self._end_consent(context, internal_response)
# Previous consent was given
if consent_attributes is not None:
satosa_logging(logger, logging.DEBUG, "Previous consent was given", context.state)
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_attributes)
return self._end_consent(context, internal_response)
# No previous consent, request consent by user
return self._approve_new_consent(context, internal_response, id_hash) | python | def process(self, context, internal_response):
"""
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
consent_state = context.state[STATE_KEY]
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_state["filter"])
id_hash = self._get_consent_id(internal_response.requester, internal_response.subject_id,
internal_response.attributes)
try:
# Check if consent is already given
consent_attributes = self._verify_consent(id_hash)
except requests.exceptions.ConnectionError as e:
satosa_logging(logger, logging.ERROR,
"Consent service is not reachable, no consent given.", context.state)
# Send an internal_response without any attributes
internal_response.attributes = {}
return self._end_consent(context, internal_response)
# Previous consent was given
if consent_attributes is not None:
satosa_logging(logger, logging.DEBUG, "Previous consent was given", context.state)
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_attributes)
return self._end_consent(context, internal_response)
# No previous consent, request consent by user
return self._approve_new_consent(context, internal_response, id_hash) | [
"def",
"process",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"consent_state",
"=",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"internal_response",
".",
"attributes",
"=",
"self",
".",
"_filter_attributes",
"(",
"internal_response",
".",
"attributes",
",",
"consent_state",
"[",
"\"filter\"",
"]",
")",
"id_hash",
"=",
"self",
".",
"_get_consent_id",
"(",
"internal_response",
".",
"requester",
",",
"internal_response",
".",
"subject_id",
",",
"internal_response",
".",
"attributes",
")",
"try",
":",
"# Check if consent is already given",
"consent_attributes",
"=",
"self",
".",
"_verify_consent",
"(",
"id_hash",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"e",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"Consent service is not reachable, no consent given.\"",
",",
"context",
".",
"state",
")",
"# Send an internal_response without any attributes",
"internal_response",
".",
"attributes",
"=",
"{",
"}",
"return",
"self",
".",
"_end_consent",
"(",
"context",
",",
"internal_response",
")",
"# Previous consent was given",
"if",
"consent_attributes",
"is",
"not",
"None",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Previous consent was given\"",
",",
"context",
".",
"state",
")",
"internal_response",
".",
"attributes",
"=",
"self",
".",
"_filter_attributes",
"(",
"internal_response",
".",
"attributes",
",",
"consent_attributes",
")",
"return",
"self",
".",
"_end_consent",
"(",
"context",
",",
"internal_response",
")",
"# No previous consent, request consent by user",
"return",
"self",
".",
"_approve_new_consent",
"(",
"context",
",",
"internal_response",
",",
"id_hash",
")"
] | Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response | [
"Manage",
"consent",
"and",
"attribute",
"filtering"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L106-L141 | train | 231,867 |
IdentityPython/SATOSA | src/satosa/micro_services/consent.py | Consent._get_consent_id | def _get_consent_id(self, requester, user_id, filtered_attr):
"""
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_id: The authorized user id
:param filtered_attr: a list containing all attributes to be sent
:return: an id
"""
filtered_attr_key_list = sorted(filtered_attr.keys())
hash_str = ""
for key in filtered_attr_key_list:
_hash_value = "".join(sorted(filtered_attr[key]))
hash_str += key + _hash_value
id_string = "%s%s%s" % (requester, user_id, hash_str)
return urlsafe_b64encode(hashlib.sha512(id_string.encode("utf-8")).hexdigest().encode("utf-8")).decode("utf-8") | python | def _get_consent_id(self, requester, user_id, filtered_attr):
"""
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_id: The authorized user id
:param filtered_attr: a list containing all attributes to be sent
:return: an id
"""
filtered_attr_key_list = sorted(filtered_attr.keys())
hash_str = ""
for key in filtered_attr_key_list:
_hash_value = "".join(sorted(filtered_attr[key]))
hash_str += key + _hash_value
id_string = "%s%s%s" % (requester, user_id, hash_str)
return urlsafe_b64encode(hashlib.sha512(id_string.encode("utf-8")).hexdigest().encode("utf-8")).decode("utf-8") | [
"def",
"_get_consent_id",
"(",
"self",
",",
"requester",
",",
"user_id",
",",
"filtered_attr",
")",
":",
"filtered_attr_key_list",
"=",
"sorted",
"(",
"filtered_attr",
".",
"keys",
"(",
")",
")",
"hash_str",
"=",
"\"\"",
"for",
"key",
"in",
"filtered_attr_key_list",
":",
"_hash_value",
"=",
"\"\"",
".",
"join",
"(",
"sorted",
"(",
"filtered_attr",
"[",
"key",
"]",
")",
")",
"hash_str",
"+=",
"key",
"+",
"_hash_value",
"id_string",
"=",
"\"%s%s%s\"",
"%",
"(",
"requester",
",",
"user_id",
",",
"hash_str",
")",
"return",
"urlsafe_b64encode",
"(",
"hashlib",
".",
"sha512",
"(",
"id_string",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_id: The authorized user id
:param filtered_attr: a list containing all attributes to be sent
:return: an id | [
"Get",
"a",
"hashed",
"id",
"based",
"on",
"requester",
"user",
"id",
"and",
"filtered",
"attributes"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L146-L166 | train | 231,868 |
IdentityPython/SATOSA | src/satosa/micro_services/consent.py | Consent._consent_registration | def _consent_registration(self, consent_args):
"""
Register a request at the consent service
:type consent_args: dict
:rtype: str
:param consent_args: All necessary parameters for the consent request
:return: Ticket received from the consent service
"""
jws = JWS(json.dumps(consent_args), alg=self.signing_key.alg).sign_compact([self.signing_key])
request = "{}/creq/{}".format(self.api_url, jws)
res = requests.get(request)
if res.status_code != 200:
raise UnexpectedResponseError("Consent service error: %s %s", res.status_code, res.text)
return res.text | python | def _consent_registration(self, consent_args):
"""
Register a request at the consent service
:type consent_args: dict
:rtype: str
:param consent_args: All necessary parameters for the consent request
:return: Ticket received from the consent service
"""
jws = JWS(json.dumps(consent_args), alg=self.signing_key.alg).sign_compact([self.signing_key])
request = "{}/creq/{}".format(self.api_url, jws)
res = requests.get(request)
if res.status_code != 200:
raise UnexpectedResponseError("Consent service error: %s %s", res.status_code, res.text)
return res.text | [
"def",
"_consent_registration",
"(",
"self",
",",
"consent_args",
")",
":",
"jws",
"=",
"JWS",
"(",
"json",
".",
"dumps",
"(",
"consent_args",
")",
",",
"alg",
"=",
"self",
".",
"signing_key",
".",
"alg",
")",
".",
"sign_compact",
"(",
"[",
"self",
".",
"signing_key",
"]",
")",
"request",
"=",
"\"{}/creq/{}\"",
".",
"format",
"(",
"self",
".",
"api_url",
",",
"jws",
")",
"res",
"=",
"requests",
".",
"get",
"(",
"request",
")",
"if",
"res",
".",
"status_code",
"!=",
"200",
":",
"raise",
"UnexpectedResponseError",
"(",
"\"Consent service error: %s %s\"",
",",
"res",
".",
"status_code",
",",
"res",
".",
"text",
")",
"return",
"res",
".",
"text"
] | Register a request at the consent service
:type consent_args: dict
:rtype: str
:param consent_args: All necessary parameters for the consent request
:return: Ticket received from the consent service | [
"Register",
"a",
"request",
"at",
"the",
"consent",
"service"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L168-L185 | train | 231,869 |
IdentityPython/SATOSA | src/satosa/micro_services/consent.py | Consent._verify_consent | def _verify_consent(self, consent_id):
"""
Connects to the consent service using the REST api and checks if the user has given consent
:type consent_id: str
:rtype: Optional[List[str]]
:param consent_id: An id associated to the authenticated user, the calling requester and
attributes to be sent.
:return: list attributes given which have been approved by user consent
"""
request = "{}/verify/{}".format(self.api_url, consent_id)
res = requests.get(request)
if res.status_code == 200:
return json.loads(res.text)
return None | python | def _verify_consent(self, consent_id):
"""
Connects to the consent service using the REST api and checks if the user has given consent
:type consent_id: str
:rtype: Optional[List[str]]
:param consent_id: An id associated to the authenticated user, the calling requester and
attributes to be sent.
:return: list attributes given which have been approved by user consent
"""
request = "{}/verify/{}".format(self.api_url, consent_id)
res = requests.get(request)
if res.status_code == 200:
return json.loads(res.text)
return None | [
"def",
"_verify_consent",
"(",
"self",
",",
"consent_id",
")",
":",
"request",
"=",
"\"{}/verify/{}\"",
".",
"format",
"(",
"self",
".",
"api_url",
",",
"consent_id",
")",
"res",
"=",
"requests",
".",
"get",
"(",
"request",
")",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"text",
")",
"return",
"None"
] | Connects to the consent service using the REST api and checks if the user has given consent
:type consent_id: str
:rtype: Optional[List[str]]
:param consent_id: An id associated to the authenticated user, the calling requester and
attributes to be sent.
:return: list attributes given which have been approved by user consent | [
"Connects",
"to",
"the",
"consent",
"service",
"using",
"the",
"REST",
"api",
"and",
"checks",
"if",
"the",
"user",
"has",
"given",
"consent"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L187-L204 | train | 231,870 |
IdentityPython/SATOSA | src/satosa/micro_services/consent.py | Consent._end_consent | def _end_consent(self, context, internal_response):
"""
Clear the state for consent and end the consent step
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
del context.state[STATE_KEY]
return super().process(context, internal_response) | python | def _end_consent(self, context, internal_response):
"""
Clear the state for consent and end the consent step
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
del context.state[STATE_KEY]
return super().process(context, internal_response) | [
"def",
"_end_consent",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"del",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"return",
"super",
"(",
")",
".",
"process",
"(",
"context",
",",
"internal_response",
")"
] | Clear the state for consent and end the consent step
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response | [
"Clear",
"the",
"state",
"for",
"consent",
"and",
"end",
"the",
"consent",
"step"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L206-L219 | train | 231,871 |
IdentityPython/SATOSA | src/satosa/micro_services/primary_identifier.py | PrimaryIdentifier.constructPrimaryIdentifier | def constructPrimaryIdentifier(self, data, ordered_identifier_candidates):
"""
Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration.
"""
logprefix = PrimaryIdentifier.logprefix
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "{} Input attributes {}".format(logprefix, attributes), context.state)
value = None
for candidate in ordered_identifier_candidates:
satosa_logging(logger, logging.DEBUG, "{} Considering candidate {}".format(logprefix, candidate), context.state)
# Get the values asserted by the IdP for the configured list of attribute names for this candidate
# and substitute None if the IdP did not assert any value for a configured attribute.
values = [ attributes.get(attribute_name, [None])[0] for attribute_name in candidate['attribute_names'] ]
satosa_logging(logger, logging.DEBUG, "{} Found candidate values {}".format(logprefix, values), context.state)
# If one of the configured attribute names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "{} IdP asserted NameID {}".format(logprefix, name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "{} Added NameID {} to candidate values".format(logprefix, candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "{} NameID {} value also asserted as attribute value".format(logprefix, candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of attribute names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "{} Candidate is missing value so skipping".format(logprefix), context.state)
continue
# All values for the configured list of attribute names are present
# so we can create a primary identifer. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "{} Added scope {} to values".format(logprefix, scope), context.state)
values.append(scope)
# Concatenate all values to create the primary identifier.
value = ''.join(values)
break
return value | python | def constructPrimaryIdentifier(self, data, ordered_identifier_candidates):
"""
Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration.
"""
logprefix = PrimaryIdentifier.logprefix
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "{} Input attributes {}".format(logprefix, attributes), context.state)
value = None
for candidate in ordered_identifier_candidates:
satosa_logging(logger, logging.DEBUG, "{} Considering candidate {}".format(logprefix, candidate), context.state)
# Get the values asserted by the IdP for the configured list of attribute names for this candidate
# and substitute None if the IdP did not assert any value for a configured attribute.
values = [ attributes.get(attribute_name, [None])[0] for attribute_name in candidate['attribute_names'] ]
satosa_logging(logger, logging.DEBUG, "{} Found candidate values {}".format(logprefix, values), context.state)
# If one of the configured attribute names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "{} IdP asserted NameID {}".format(logprefix, name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "{} Added NameID {} to candidate values".format(logprefix, candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "{} NameID {} value also asserted as attribute value".format(logprefix, candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of attribute names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "{} Candidate is missing value so skipping".format(logprefix), context.state)
continue
# All values for the configured list of attribute names are present
# so we can create a primary identifer. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "{} Added scope {} to values".format(logprefix, scope), context.state)
values.append(scope)
# Concatenate all values to create the primary identifier.
value = ''.join(values)
break
return value | [
"def",
"constructPrimaryIdentifier",
"(",
"self",
",",
"data",
",",
"ordered_identifier_candidates",
")",
":",
"logprefix",
"=",
"PrimaryIdentifier",
".",
"logprefix",
"context",
"=",
"self",
".",
"context",
"attributes",
"=",
"data",
".",
"attributes",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Input attributes {}\"",
".",
"format",
"(",
"logprefix",
",",
"attributes",
")",
",",
"context",
".",
"state",
")",
"value",
"=",
"None",
"for",
"candidate",
"in",
"ordered_identifier_candidates",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Considering candidate {}\"",
".",
"format",
"(",
"logprefix",
",",
"candidate",
")",
",",
"context",
".",
"state",
")",
"# Get the values asserted by the IdP for the configured list of attribute names for this candidate",
"# and substitute None if the IdP did not assert any value for a configured attribute.",
"values",
"=",
"[",
"attributes",
".",
"get",
"(",
"attribute_name",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"for",
"attribute_name",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Found candidate values {}\"",
".",
"format",
"(",
"logprefix",
",",
"values",
")",
",",
"context",
".",
"state",
")",
"# If one of the configured attribute names is name_id then if there is also a configured",
"# name_id_format add the value for the NameID of that format if it was asserted by the IdP",
"# or else add the value None.",
"if",
"'name_id'",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
":",
"candidate_nameid_value",
"=",
"None",
"candidate_nameid_value",
"=",
"None",
"candidate_name_id_format",
"=",
"candidate",
".",
"get",
"(",
"'name_id_format'",
")",
"name_id_value",
"=",
"data",
".",
"subject_id",
"name_id_format",
"=",
"data",
".",
"subject_type",
"if",
"(",
"name_id_value",
"and",
"candidate_name_id_format",
"and",
"candidate_name_id_format",
"==",
"name_id_format",
")",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} IdP asserted NameID {}\"",
".",
"format",
"(",
"logprefix",
",",
"name_id_value",
")",
",",
"context",
".",
"state",
")",
"candidate_nameid_value",
"=",
"name_id_value",
"# Only add the NameID value asserted by the IdP if it is not already",
"# in the list of values. This is necessary because some non-compliant IdPs",
"# have been known, for example, to assert the value of eduPersonPrincipalName",
"# in the value for SAML2 persistent NameID as well as asserting",
"# eduPersonPrincipalName.",
"if",
"candidate_nameid_value",
"not",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Added NameID {} to candidate values\"",
".",
"format",
"(",
"logprefix",
",",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"candidate_nameid_value",
")",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARN",
",",
"\"{} NameID {} value also asserted as attribute value\"",
".",
"format",
"(",
"logprefix",
",",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"# If no value was asserted by the IdP for one of the configured list of attribute names",
"# for this candidate then go onto the next candidate.",
"if",
"None",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Candidate is missing value so skipping\"",
".",
"format",
"(",
"logprefix",
")",
",",
"context",
".",
"state",
")",
"continue",
"# All values for the configured list of attribute names are present",
"# so we can create a primary identifer. Add a scope if configured",
"# to do so.",
"if",
"'add_scope'",
"in",
"candidate",
":",
"if",
"candidate",
"[",
"'add_scope'",
"]",
"==",
"'issuer_entityid'",
":",
"scope",
"=",
"data",
".",
"auth_info",
".",
"issuer",
"else",
":",
"scope",
"=",
"candidate",
"[",
"'add_scope'",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Added scope {} to values\"",
".",
"format",
"(",
"logprefix",
",",
"scope",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"scope",
")",
"# Concatenate all values to create the primary identifier.",
"value",
"=",
"''",
".",
"join",
"(",
"values",
")",
"break",
"return",
"value"
] | Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration. | [
"Construct",
"and",
"return",
"a",
"primary",
"identifier",
"value",
"from",
"the",
"data",
"asserted",
"by",
"the",
"IdP",
"using",
"the",
"ordered",
"list",
"of",
"candidates",
"from",
"the",
"configuration",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/primary_identifier.py#L32-L103 | train | 231,872 |
IdentityPython/SATOSA | src/satosa/state.py | state_to_cookie | def state_to_cookie(state, name, path, encryption_key):
"""
Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cookie
:param path: Endpoint path the cookie will be associated to
:param encryption_key: Key to encrypt the state information
:return: A cookie
"""
cookie_data = "" if state.delete else state.urlstate(encryption_key)
max_age = 0 if state.delete else STATE_COOKIE_MAX_AGE
satosa_logging(logger, logging.DEBUG,
"Saving state as cookie, secure: %s, max-age: %s, path: %s" %
(STATE_COOKIE_SECURE, STATE_COOKIE_MAX_AGE, path), state)
cookie = SimpleCookie()
cookie[name] = cookie_data
cookie[name]["secure"] = STATE_COOKIE_SECURE
cookie[name]["path"] = path
cookie[name]["max-age"] = max_age
return cookie | python | def state_to_cookie(state, name, path, encryption_key):
"""
Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cookie
:param path: Endpoint path the cookie will be associated to
:param encryption_key: Key to encrypt the state information
:return: A cookie
"""
cookie_data = "" if state.delete else state.urlstate(encryption_key)
max_age = 0 if state.delete else STATE_COOKIE_MAX_AGE
satosa_logging(logger, logging.DEBUG,
"Saving state as cookie, secure: %s, max-age: %s, path: %s" %
(STATE_COOKIE_SECURE, STATE_COOKIE_MAX_AGE, path), state)
cookie = SimpleCookie()
cookie[name] = cookie_data
cookie[name]["secure"] = STATE_COOKIE_SECURE
cookie[name]["path"] = path
cookie[name]["max-age"] = max_age
return cookie | [
"def",
"state_to_cookie",
"(",
"state",
",",
"name",
",",
"path",
",",
"encryption_key",
")",
":",
"cookie_data",
"=",
"\"\"",
"if",
"state",
".",
"delete",
"else",
"state",
".",
"urlstate",
"(",
"encryption_key",
")",
"max_age",
"=",
"0",
"if",
"state",
".",
"delete",
"else",
"STATE_COOKIE_MAX_AGE",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Saving state as cookie, secure: %s, max-age: %s, path: %s\"",
"%",
"(",
"STATE_COOKIE_SECURE",
",",
"STATE_COOKIE_MAX_AGE",
",",
"path",
")",
",",
"state",
")",
"cookie",
"=",
"SimpleCookie",
"(",
")",
"cookie",
"[",
"name",
"]",
"=",
"cookie_data",
"cookie",
"[",
"name",
"]",
"[",
"\"secure\"",
"]",
"=",
"STATE_COOKIE_SECURE",
"cookie",
"[",
"name",
"]",
"[",
"\"path\"",
"]",
"=",
"path",
"cookie",
"[",
"name",
"]",
"[",
"\"max-age\"",
"]",
"=",
"max_age",
"return",
"cookie"
] | Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cookie
:param path: Endpoint path the cookie will be associated to
:param encryption_key: Key to encrypt the state information
:return: A cookie | [
"Saves",
"a",
"state",
"to",
"a",
"cookie"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L26-L54 | train | 231,873 |
IdentityPython/SATOSA | src/satosa/state.py | cookie_to_state | def cookie_to_state(cookie_str, name, encryption_key):
"""
Loads a state from a cookie
:type cookie_str: str
:type name: str
:type encryption_key: str
:rtype: satosa.state.State
:param cookie_str: string representation of cookie/s
:param name: Name identifier of the cookie
:param encryption_key: Key to encrypt the state information
:return: A state
"""
try:
cookie = SimpleCookie(cookie_str)
state = State(cookie[name].value, encryption_key)
except KeyError as e:
msg_tmpl = 'No cookie named {name} in {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
except ValueError as e:
msg_tmpl = 'Failed to process {name} from {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
else:
msg_tmpl = 'Loading state from cookie {data}'
msg = msg_tmpl.format(data=cookie_str)
satosa_logging(logger, logging.DEBUG, msg, state)
return state | python | def cookie_to_state(cookie_str, name, encryption_key):
"""
Loads a state from a cookie
:type cookie_str: str
:type name: str
:type encryption_key: str
:rtype: satosa.state.State
:param cookie_str: string representation of cookie/s
:param name: Name identifier of the cookie
:param encryption_key: Key to encrypt the state information
:return: A state
"""
try:
cookie = SimpleCookie(cookie_str)
state = State(cookie[name].value, encryption_key)
except KeyError as e:
msg_tmpl = 'No cookie named {name} in {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
except ValueError as e:
msg_tmpl = 'Failed to process {name} from {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
else:
msg_tmpl = 'Loading state from cookie {data}'
msg = msg_tmpl.format(data=cookie_str)
satosa_logging(logger, logging.DEBUG, msg, state)
return state | [
"def",
"cookie_to_state",
"(",
"cookie_str",
",",
"name",
",",
"encryption_key",
")",
":",
"try",
":",
"cookie",
"=",
"SimpleCookie",
"(",
"cookie_str",
")",
"state",
"=",
"State",
"(",
"cookie",
"[",
"name",
"]",
".",
"value",
",",
"encryption_key",
")",
"except",
"KeyError",
"as",
"e",
":",
"msg_tmpl",
"=",
"'No cookie named {name} in {data}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"name",
"=",
"name",
",",
"data",
"=",
"cookie_str",
")",
"logger",
".",
"exception",
"(",
"msg",
")",
"raise",
"SATOSAStateError",
"(",
"msg",
")",
"from",
"e",
"except",
"ValueError",
"as",
"e",
":",
"msg_tmpl",
"=",
"'Failed to process {name} from {data}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"name",
"=",
"name",
",",
"data",
"=",
"cookie_str",
")",
"logger",
".",
"exception",
"(",
"msg",
")",
"raise",
"SATOSAStateError",
"(",
"msg",
")",
"from",
"e",
"else",
":",
"msg_tmpl",
"=",
"'Loading state from cookie {data}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"data",
"=",
"cookie_str",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"msg",
",",
"state",
")",
"return",
"state"
] | Loads a state from a cookie
:type cookie_str: str
:type name: str
:type encryption_key: str
:rtype: satosa.state.State
:param cookie_str: string representation of cookie/s
:param name: Name identifier of the cookie
:param encryption_key: Key to encrypt the state information
:return: A state | [
"Loads",
"a",
"state",
"from",
"a",
"cookie"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L57-L88 | train | 231,874 |
IdentityPython/SATOSA | src/satosa/state.py | _AESCipher.encrypt | def encrypt(self, raw):
"""
Encryptes the parameter raw.
:type raw: bytes
:rtype: str
:param: bytes to be encrypted.
:return: A base 64 encoded string.
"""
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.urlsafe_b64encode(iv + cipher.encrypt(raw)) | python | def encrypt(self, raw):
"""
Encryptes the parameter raw.
:type raw: bytes
:rtype: str
:param: bytes to be encrypted.
:return: A base 64 encoded string.
"""
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.urlsafe_b64encode(iv + cipher.encrypt(raw)) | [
"def",
"encrypt",
"(",
"self",
",",
"raw",
")",
":",
"raw",
"=",
"self",
".",
"_pad",
"(",
"raw",
")",
"iv",
"=",
"Random",
".",
"new",
"(",
")",
".",
"read",
"(",
"AES",
".",
"block_size",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"self",
".",
"key",
",",
"AES",
".",
"MODE_CBC",
",",
"iv",
")",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"iv",
"+",
"cipher",
".",
"encrypt",
"(",
"raw",
")",
")"
] | Encryptes the parameter raw.
:type raw: bytes
:rtype: str
:param: bytes to be encrypted.
:return: A base 64 encoded string. | [
"Encryptes",
"the",
"parameter",
"raw",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L109-L123 | train | 231,875 |
IdentityPython/SATOSA | src/satosa/state.py | _AESCipher._pad | def _pad(self, b):
"""
Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes
"""
return b + (self.bs - len(b) % self.bs) * chr(self.bs - len(b) % self.bs).encode("UTF-8") | python | def _pad(self, b):
"""
Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes
"""
return b + (self.bs - len(b) % self.bs) * chr(self.bs - len(b) % self.bs).encode("UTF-8") | [
"def",
"_pad",
"(",
"self",
",",
"b",
")",
":",
"return",
"b",
"+",
"(",
"self",
".",
"bs",
"-",
"len",
"(",
"b",
")",
"%",
"self",
".",
"bs",
")",
"*",
"chr",
"(",
"self",
".",
"bs",
"-",
"len",
"(",
"b",
")",
"%",
"self",
".",
"bs",
")",
".",
"encode",
"(",
"\"UTF-8\"",
")"
] | Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes | [
"Will",
"padd",
"the",
"param",
"to",
"be",
"of",
"the",
"correct",
"length",
"for",
"the",
"encryption",
"alg",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L140-L147 | train | 231,876 |
IdentityPython/SATOSA | src/satosa/state.py | State.urlstate | def urlstate(self, encryption_key):
"""
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
"""
lzma = LZMACompressor()
urlstate_data = json.dumps(self._state_dict)
urlstate_data = lzma.compress(urlstate_data.encode("UTF-8"))
urlstate_data += lzma.flush()
urlstate_data = _AESCipher(encryption_key).encrypt(urlstate_data)
lzma = LZMACompressor()
urlstate_data = lzma.compress(urlstate_data)
urlstate_data += lzma.flush()
urlstate_data = base64.urlsafe_b64encode(urlstate_data)
return urlstate_data.decode("utf-8") | python | def urlstate(self, encryption_key):
"""
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
"""
lzma = LZMACompressor()
urlstate_data = json.dumps(self._state_dict)
urlstate_data = lzma.compress(urlstate_data.encode("UTF-8"))
urlstate_data += lzma.flush()
urlstate_data = _AESCipher(encryption_key).encrypt(urlstate_data)
lzma = LZMACompressor()
urlstate_data = lzma.compress(urlstate_data)
urlstate_data += lzma.flush()
urlstate_data = base64.urlsafe_b64encode(urlstate_data)
return urlstate_data.decode("utf-8") | [
"def",
"urlstate",
"(",
"self",
",",
"encryption_key",
")",
":",
"lzma",
"=",
"LZMACompressor",
"(",
")",
"urlstate_data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"_state_dict",
")",
"urlstate_data",
"=",
"lzma",
".",
"compress",
"(",
"urlstate_data",
".",
"encode",
"(",
"\"UTF-8\"",
")",
")",
"urlstate_data",
"+=",
"lzma",
".",
"flush",
"(",
")",
"urlstate_data",
"=",
"_AESCipher",
"(",
"encryption_key",
")",
".",
"encrypt",
"(",
"urlstate_data",
")",
"lzma",
"=",
"LZMACompressor",
"(",
")",
"urlstate_data",
"=",
"lzma",
".",
"compress",
"(",
"urlstate_data",
")",
"urlstate_data",
"+=",
"lzma",
".",
"flush",
"(",
")",
"urlstate_data",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"urlstate_data",
")",
"return",
"urlstate_data",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state. | [
"Will",
"return",
"a",
"url",
"safe",
"representation",
"of",
"the",
"state",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L235-L253 | train | 231,877 |
IdentityPython/SATOSA | src/satosa/state.py | State.copy | def copy(self):
"""
Returns a deepcopy of the state
:rtype: satosa.state.State
:return: A copy of the state
"""
state_copy = State()
state_copy._state_dict = copy.deepcopy(self._state_dict)
return state_copy | python | def copy(self):
"""
Returns a deepcopy of the state
:rtype: satosa.state.State
:return: A copy of the state
"""
state_copy = State()
state_copy._state_dict = copy.deepcopy(self._state_dict)
return state_copy | [
"def",
"copy",
"(",
"self",
")",
":",
"state_copy",
"=",
"State",
"(",
")",
"state_copy",
".",
"_state_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_state_dict",
")",
"return",
"state_copy"
] | Returns a deepcopy of the state
:rtype: satosa.state.State
:return: A copy of the state | [
"Returns",
"a",
"deepcopy",
"of",
"the",
"state"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L255-L265 | train | 231,878 |
IdentityPython/SATOSA | src/satosa/deprecated.py | saml_name_id_format_to_hash_type | def saml_name_id_format_to_hash_type(name_format):
"""
Translate pySAML2 name format to satosa format
:type name_format: str
:rtype: satosa.internal_data.UserIdHashType
:param name_format: SAML2 name format
:return: satosa format
"""
msg = "saml_name_id_format_to_hash_type is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
name_id_format_to_hash_type = {
NAMEID_FORMAT_TRANSIENT: UserIdHashType.transient,
NAMEID_FORMAT_PERSISTENT: UserIdHashType.persistent,
NAMEID_FORMAT_EMAILADDRESS: UserIdHashType.emailaddress,
NAMEID_FORMAT_UNSPECIFIED: UserIdHashType.unspecified,
}
return name_id_format_to_hash_type.get(
name_format, UserIdHashType.transient
) | python | def saml_name_id_format_to_hash_type(name_format):
"""
Translate pySAML2 name format to satosa format
:type name_format: str
:rtype: satosa.internal_data.UserIdHashType
:param name_format: SAML2 name format
:return: satosa format
"""
msg = "saml_name_id_format_to_hash_type is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
name_id_format_to_hash_type = {
NAMEID_FORMAT_TRANSIENT: UserIdHashType.transient,
NAMEID_FORMAT_PERSISTENT: UserIdHashType.persistent,
NAMEID_FORMAT_EMAILADDRESS: UserIdHashType.emailaddress,
NAMEID_FORMAT_UNSPECIFIED: UserIdHashType.unspecified,
}
return name_id_format_to_hash_type.get(
name_format, UserIdHashType.transient
) | [
"def",
"saml_name_id_format_to_hash_type",
"(",
"name_format",
")",
":",
"msg",
"=",
"\"saml_name_id_format_to_hash_type is deprecated and will be removed.\"",
"_warnings",
".",
"warn",
"(",
"msg",
",",
"DeprecationWarning",
")",
"name_id_format_to_hash_type",
"=",
"{",
"NAMEID_FORMAT_TRANSIENT",
":",
"UserIdHashType",
".",
"transient",
",",
"NAMEID_FORMAT_PERSISTENT",
":",
"UserIdHashType",
".",
"persistent",
",",
"NAMEID_FORMAT_EMAILADDRESS",
":",
"UserIdHashType",
".",
"emailaddress",
",",
"NAMEID_FORMAT_UNSPECIFIED",
":",
"UserIdHashType",
".",
"unspecified",
",",
"}",
"return",
"name_id_format_to_hash_type",
".",
"get",
"(",
"name_format",
",",
"UserIdHashType",
".",
"transient",
")"
] | Translate pySAML2 name format to satosa format
:type name_format: str
:rtype: satosa.internal_data.UserIdHashType
:param name_format: SAML2 name format
:return: satosa format | [
"Translate",
"pySAML2",
"name",
"format",
"to",
"satosa",
"format"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L204-L225 | train | 231,879 |
IdentityPython/SATOSA | src/satosa/deprecated.py | hash_type_to_saml_name_id_format | def hash_type_to_saml_name_id_format(hash_type):
"""
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
"""
msg = "hash_type_to_saml_name_id_format is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
hash_type_to_name_id_format = {
UserIdHashType.transient: NAMEID_FORMAT_TRANSIENT,
UserIdHashType.persistent: NAMEID_FORMAT_PERSISTENT,
UserIdHashType.emailaddress: NAMEID_FORMAT_EMAILADDRESS,
UserIdHashType.unspecified: NAMEID_FORMAT_UNSPECIFIED,
}
return hash_type_to_name_id_format.get(hash_type, NAMEID_FORMAT_PERSISTENT) | python | def hash_type_to_saml_name_id_format(hash_type):
"""
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
"""
msg = "hash_type_to_saml_name_id_format is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
hash_type_to_name_id_format = {
UserIdHashType.transient: NAMEID_FORMAT_TRANSIENT,
UserIdHashType.persistent: NAMEID_FORMAT_PERSISTENT,
UserIdHashType.emailaddress: NAMEID_FORMAT_EMAILADDRESS,
UserIdHashType.unspecified: NAMEID_FORMAT_UNSPECIFIED,
}
return hash_type_to_name_id_format.get(hash_type, NAMEID_FORMAT_PERSISTENT) | [
"def",
"hash_type_to_saml_name_id_format",
"(",
"hash_type",
")",
":",
"msg",
"=",
"\"hash_type_to_saml_name_id_format is deprecated and will be removed.\"",
"_warnings",
".",
"warn",
"(",
"msg",
",",
"DeprecationWarning",
")",
"hash_type_to_name_id_format",
"=",
"{",
"UserIdHashType",
".",
"transient",
":",
"NAMEID_FORMAT_TRANSIENT",
",",
"UserIdHashType",
".",
"persistent",
":",
"NAMEID_FORMAT_PERSISTENT",
",",
"UserIdHashType",
".",
"emailaddress",
":",
"NAMEID_FORMAT_EMAILADDRESS",
",",
"UserIdHashType",
".",
"unspecified",
":",
"NAMEID_FORMAT_UNSPECIFIED",
",",
"}",
"return",
"hash_type_to_name_id_format",
".",
"get",
"(",
"hash_type",
",",
"NAMEID_FORMAT_PERSISTENT",
")"
] | Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format | [
"Translate",
"satosa",
"format",
"to",
"pySAML2",
"name",
"format"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L228-L247 | train | 231,880 |
IdentityPython/SATOSA | src/satosa/deprecated.py | UserIdHasher.save_state | def save_state(internal_request, state):
"""
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
"""
state_data = {"hash_type": internal_request.user_id_hash_type}
state[UserIdHasher.STATE_KEY] = state_data | python | def save_state(internal_request, state):
"""
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
"""
state_data = {"hash_type": internal_request.user_id_hash_type}
state[UserIdHasher.STATE_KEY] = state_data | [
"def",
"save_state",
"(",
"internal_request",
",",
"state",
")",
":",
"state_data",
"=",
"{",
"\"hash_type\"",
":",
"internal_request",
".",
"user_id_hash_type",
"}",
"state",
"[",
"UserIdHasher",
".",
"STATE_KEY",
"]",
"=",
"state_data"
] | Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state | [
"Saves",
"all",
"necessary",
"information",
"needed",
"by",
"the",
"UserIdHasher"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L122-L132 | train | 231,881 |
IdentityPython/SATOSA | src/satosa/deprecated.py | UserIdHasher.hash_id | def hash_id(salt, user_id, requester, state):
"""
Sets a user id to the internal_response,
in the format specified by the internal response
:type salt: str
:type user_id: str
:type requester: str
:type state: satosa.state.State
:rtype: str
:param salt: A salt string for the ID hashing
:param user_id: the user id
:param user_id_hash_type: Hashing type
:param state: The current state
:return: the internal_response containing the hashed user ID
"""
hash_type_to_format = {
NAMEID_FORMAT_TRANSIENT: "{id}{req}{time}",
NAMEID_FORMAT_PERSISTENT: "{id}{req}",
"pairwise": "{id}{req}",
"public": "{id}",
NAMEID_FORMAT_EMAILADDRESS: "{id}",
NAMEID_FORMAT_UNSPECIFIED: "{id}",
}
format_args = {
"id": user_id,
"req": requester,
"time": datetime.datetime.utcnow().timestamp(),
}
hash_type = UserIdHasher.hash_type(state)
try:
fmt = hash_type_to_format[hash_type]
except KeyError as e:
raise ValueError("Unknown hash type: {}".format(hash_type)) from e
else:
user_id = fmt.format(**format_args)
hasher = (
(lambda salt, value: value)
if hash_type
in [NAMEID_FORMAT_EMAILADDRESS, NAMEID_FORMAT_UNSPECIFIED]
else util.hash_data
)
return hasher(salt, user_id) | python | def hash_id(salt, user_id, requester, state):
"""
Sets a user id to the internal_response,
in the format specified by the internal response
:type salt: str
:type user_id: str
:type requester: str
:type state: satosa.state.State
:rtype: str
:param salt: A salt string for the ID hashing
:param user_id: the user id
:param user_id_hash_type: Hashing type
:param state: The current state
:return: the internal_response containing the hashed user ID
"""
hash_type_to_format = {
NAMEID_FORMAT_TRANSIENT: "{id}{req}{time}",
NAMEID_FORMAT_PERSISTENT: "{id}{req}",
"pairwise": "{id}{req}",
"public": "{id}",
NAMEID_FORMAT_EMAILADDRESS: "{id}",
NAMEID_FORMAT_UNSPECIFIED: "{id}",
}
format_args = {
"id": user_id,
"req": requester,
"time": datetime.datetime.utcnow().timestamp(),
}
hash_type = UserIdHasher.hash_type(state)
try:
fmt = hash_type_to_format[hash_type]
except KeyError as e:
raise ValueError("Unknown hash type: {}".format(hash_type)) from e
else:
user_id = fmt.format(**format_args)
hasher = (
(lambda salt, value: value)
if hash_type
in [NAMEID_FORMAT_EMAILADDRESS, NAMEID_FORMAT_UNSPECIFIED]
else util.hash_data
)
return hasher(salt, user_id) | [
"def",
"hash_id",
"(",
"salt",
",",
"user_id",
",",
"requester",
",",
"state",
")",
":",
"hash_type_to_format",
"=",
"{",
"NAMEID_FORMAT_TRANSIENT",
":",
"\"{id}{req}{time}\"",
",",
"NAMEID_FORMAT_PERSISTENT",
":",
"\"{id}{req}\"",
",",
"\"pairwise\"",
":",
"\"{id}{req}\"",
",",
"\"public\"",
":",
"\"{id}\"",
",",
"NAMEID_FORMAT_EMAILADDRESS",
":",
"\"{id}\"",
",",
"NAMEID_FORMAT_UNSPECIFIED",
":",
"\"{id}\"",
",",
"}",
"format_args",
"=",
"{",
"\"id\"",
":",
"user_id",
",",
"\"req\"",
":",
"requester",
",",
"\"time\"",
":",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timestamp",
"(",
")",
",",
"}",
"hash_type",
"=",
"UserIdHasher",
".",
"hash_type",
"(",
"state",
")",
"try",
":",
"fmt",
"=",
"hash_type_to_format",
"[",
"hash_type",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Unknown hash type: {}\"",
".",
"format",
"(",
"hash_type",
")",
")",
"from",
"e",
"else",
":",
"user_id",
"=",
"fmt",
".",
"format",
"(",
"*",
"*",
"format_args",
")",
"hasher",
"=",
"(",
"(",
"lambda",
"salt",
",",
"value",
":",
"value",
")",
"if",
"hash_type",
"in",
"[",
"NAMEID_FORMAT_EMAILADDRESS",
",",
"NAMEID_FORMAT_UNSPECIFIED",
"]",
"else",
"util",
".",
"hash_data",
")",
"return",
"hasher",
"(",
"salt",
",",
"user_id",
")"
] | Sets a user id to the internal_response,
in the format specified by the internal response
:type salt: str
:type user_id: str
:type requester: str
:type state: satosa.state.State
:rtype: str
:param salt: A salt string for the ID hashing
:param user_id: the user id
:param user_id_hash_type: Hashing type
:param state: The current state
:return: the internal_response containing the hashed user ID | [
"Sets",
"a",
"user",
"id",
"to",
"the",
"internal_response",
"in",
"the",
"format",
"specified",
"by",
"the",
"internal",
"response"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L155-L201 | train | 231,882 |
IdentityPython/SATOSA | src/satosa/plugin_loader.py | load_backends | def load_backends(config, callback, internal_attributes):
"""
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.base.BackendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the backend after the authentication is done.
:return: A list of backend modules
"""
backend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["BACKEND_MODULES"], backend_filter,
config["BASE"], internal_attributes, callback)
logger.info("Setup backends: %s" % [backend.name for backend in backend_modules])
return backend_modules | python | def load_backends(config, callback, internal_attributes):
"""
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.base.BackendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the backend after the authentication is done.
:return: A list of backend modules
"""
backend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["BACKEND_MODULES"], backend_filter,
config["BASE"], internal_attributes, callback)
logger.info("Setup backends: %s" % [backend.name for backend in backend_modules])
return backend_modules | [
"def",
"load_backends",
"(",
"config",
",",
"callback",
",",
"internal_attributes",
")",
":",
"backend_modules",
"=",
"_load_plugins",
"(",
"config",
".",
"get",
"(",
"\"CUSTOM_PLUGIN_MODULE_PATHS\"",
")",
",",
"config",
"[",
"\"BACKEND_MODULES\"",
"]",
",",
"backend_filter",
",",
"config",
"[",
"\"BASE\"",
"]",
",",
"internal_attributes",
",",
"callback",
")",
"logger",
".",
"info",
"(",
"\"Setup backends: %s\"",
"%",
"[",
"backend",
".",
"name",
"for",
"backend",
"in",
"backend_modules",
"]",
")",
"return",
"backend_modules"
] | Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.base.BackendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the backend after the authentication is done.
:return: A list of backend modules | [
"Load",
"all",
"backend",
"modules",
"specified",
"in",
"the",
"config"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L30-L47 | train | 231,883 |
IdentityPython/SATOSA | src/satosa/plugin_loader.py | load_frontends | def load_frontends(config, callback, internal_attributes):
"""
Load all frontend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.frontends.base.FrontendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the frontend after the authentication request
has been processed.
:return: A list of frontend modules
"""
frontend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["FRONTEND_MODULES"],
frontend_filter, config["BASE"], internal_attributes, callback)
logger.info("Setup frontends: %s" % [frontend.name for frontend in frontend_modules])
return frontend_modules | python | def load_frontends(config, callback, internal_attributes):
"""
Load all frontend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.frontends.base.FrontendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the frontend after the authentication request
has been processed.
:return: A list of frontend modules
"""
frontend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["FRONTEND_MODULES"],
frontend_filter, config["BASE"], internal_attributes, callback)
logger.info("Setup frontends: %s" % [frontend.name for frontend in frontend_modules])
return frontend_modules | [
"def",
"load_frontends",
"(",
"config",
",",
"callback",
",",
"internal_attributes",
")",
":",
"frontend_modules",
"=",
"_load_plugins",
"(",
"config",
".",
"get",
"(",
"\"CUSTOM_PLUGIN_MODULE_PATHS\"",
")",
",",
"config",
"[",
"\"FRONTEND_MODULES\"",
"]",
",",
"frontend_filter",
",",
"config",
"[",
"\"BASE\"",
"]",
",",
"internal_attributes",
",",
"callback",
")",
"logger",
".",
"info",
"(",
"\"Setup frontends: %s\"",
"%",
"[",
"frontend",
".",
"name",
"for",
"frontend",
"in",
"frontend_modules",
"]",
")",
"return",
"frontend_modules"
] | Load all frontend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.frontends.base.FrontendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the frontend after the authentication request
has been processed.
:return: A list of frontend modules | [
"Load",
"all",
"frontend",
"modules",
"specified",
"in",
"the",
"config"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L50-L68 | train | 231,884 |
IdentityPython/SATOSA | src/satosa/plugin_loader.py | _micro_service_filter | def _micro_service_filter(cls):
"""
Will only give a find on classes that is a subclass of MicroService, with the exception that
the class is not allowed to be a direct ResponseMicroService or RequestMicroService.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
is_microservice_module = issubclass(cls, MicroService)
is_correct_subclass = cls != MicroService and cls != ResponseMicroService and cls != RequestMicroService
return is_microservice_module and is_correct_subclass | python | def _micro_service_filter(cls):
"""
Will only give a find on classes that is a subclass of MicroService, with the exception that
the class is not allowed to be a direct ResponseMicroService or RequestMicroService.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
is_microservice_module = issubclass(cls, MicroService)
is_correct_subclass = cls != MicroService and cls != ResponseMicroService and cls != RequestMicroService
return is_microservice_module and is_correct_subclass | [
"def",
"_micro_service_filter",
"(",
"cls",
")",
":",
"is_microservice_module",
"=",
"issubclass",
"(",
"cls",
",",
"MicroService",
")",
"is_correct_subclass",
"=",
"cls",
"!=",
"MicroService",
"and",
"cls",
"!=",
"ResponseMicroService",
"and",
"cls",
"!=",
"RequestMicroService",
"return",
"is_microservice_module",
"and",
"is_correct_subclass"
] | Will only give a find on classes that is a subclass of MicroService, with the exception that
the class is not allowed to be a direct ResponseMicroService or RequestMicroService.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false | [
"Will",
"only",
"give",
"a",
"find",
"on",
"classes",
"that",
"is",
"a",
"subclass",
"of",
"MicroService",
"with",
"the",
"exception",
"that",
"the",
"class",
"is",
"not",
"allowed",
"to",
"be",
"a",
"direct",
"ResponseMicroService",
"or",
"RequestMicroService",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L97-L110 | train | 231,885 |
IdentityPython/SATOSA | src/satosa/plugin_loader.py | _load_plugins | def _load_plugins(plugin_paths, plugins, plugin_filter, base_url, internal_attributes, callback):
"""
Loads endpoint plugins
:type plugin_paths: list[str]
:type plugins: list[str]
:type plugin_filter: (type | str) -> bool
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype list[satosa.plugin_base.endpoint.InterfaceModulePlugin]
:param plugin_paths: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param plugin_filter: Filter what to load from the module file
:param args: Arguments to the plugin
:return: A list with all the loaded plugins
"""
loaded_plugin_modules = []
with prepend_to_import_path(plugin_paths):
for plugin_config in plugins:
try:
module_class = _load_endpoint_module(plugin_config, plugin_filter)
except SATOSAConfigurationError as e:
raise SATOSAConfigurationError("Configuration error in {}".format(json.dumps(plugin_config))) from e
if module_class:
module_config = _replace_variables_in_plugin_module_config(plugin_config["config"], base_url,
plugin_config["name"])
instance = module_class(callback, internal_attributes, module_config, base_url,
plugin_config["name"])
loaded_plugin_modules.append(instance)
return loaded_plugin_modules | python | def _load_plugins(plugin_paths, plugins, plugin_filter, base_url, internal_attributes, callback):
"""
Loads endpoint plugins
:type plugin_paths: list[str]
:type plugins: list[str]
:type plugin_filter: (type | str) -> bool
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype list[satosa.plugin_base.endpoint.InterfaceModulePlugin]
:param plugin_paths: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param plugin_filter: Filter what to load from the module file
:param args: Arguments to the plugin
:return: A list with all the loaded plugins
"""
loaded_plugin_modules = []
with prepend_to_import_path(plugin_paths):
for plugin_config in plugins:
try:
module_class = _load_endpoint_module(plugin_config, plugin_filter)
except SATOSAConfigurationError as e:
raise SATOSAConfigurationError("Configuration error in {}".format(json.dumps(plugin_config))) from e
if module_class:
module_config = _replace_variables_in_plugin_module_config(plugin_config["config"], base_url,
plugin_config["name"])
instance = module_class(callback, internal_attributes, module_config, base_url,
plugin_config["name"])
loaded_plugin_modules.append(instance)
return loaded_plugin_modules | [
"def",
"_load_plugins",
"(",
"plugin_paths",
",",
"plugins",
",",
"plugin_filter",
",",
"base_url",
",",
"internal_attributes",
",",
"callback",
")",
":",
"loaded_plugin_modules",
"=",
"[",
"]",
"with",
"prepend_to_import_path",
"(",
"plugin_paths",
")",
":",
"for",
"plugin_config",
"in",
"plugins",
":",
"try",
":",
"module_class",
"=",
"_load_endpoint_module",
"(",
"plugin_config",
",",
"plugin_filter",
")",
"except",
"SATOSAConfigurationError",
"as",
"e",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Configuration error in {}\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"plugin_config",
")",
")",
")",
"from",
"e",
"if",
"module_class",
":",
"module_config",
"=",
"_replace_variables_in_plugin_module_config",
"(",
"plugin_config",
"[",
"\"config\"",
"]",
",",
"base_url",
",",
"plugin_config",
"[",
"\"name\"",
"]",
")",
"instance",
"=",
"module_class",
"(",
"callback",
",",
"internal_attributes",
",",
"module_config",
",",
"base_url",
",",
"plugin_config",
"[",
"\"name\"",
"]",
")",
"loaded_plugin_modules",
".",
"append",
"(",
"instance",
")",
"return",
"loaded_plugin_modules"
] | Loads endpoint plugins
:type plugin_paths: list[str]
:type plugins: list[str]
:type plugin_filter: (type | str) -> bool
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype list[satosa.plugin_base.endpoint.InterfaceModulePlugin]
:param plugin_paths: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param plugin_filter: Filter what to load from the module file
:param args: Arguments to the plugin
:return: A list with all the loaded plugins | [
"Loads",
"endpoint",
"plugins"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L151-L181 | train | 231,886 |
IdentityPython/SATOSA | src/satosa/scripts/satosa_saml_metadata.py | create_and_write_saml_metadata | def create_and_write_saml_metadata(proxy_conf, key, cert, dir, valid, split_frontend_metadata=False,
split_backend_metadata=False):
"""
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT.
"""
satosa_config = SATOSAConfig(proxy_conf)
secc = _get_security_context(key, cert)
frontend_entities, backend_entities = create_entity_descriptors(satosa_config)
output = []
if frontend_entities:
if split_frontend_metadata:
output.extend(_create_split_entity_descriptors(frontend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(frontend_entities, secc, valid, "frontend.xml"))
if backend_entities:
if split_backend_metadata:
output.extend(_create_split_entity_descriptors(backend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(backend_entities, secc, valid, "backend.xml"))
for metadata, filename in output:
path = os.path.join(dir, filename)
print("Writing metadata to '{}'".format(path))
with open(path, "w") as f:
f.write(metadata) | python | def create_and_write_saml_metadata(proxy_conf, key, cert, dir, valid, split_frontend_metadata=False,
split_backend_metadata=False):
"""
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT.
"""
satosa_config = SATOSAConfig(proxy_conf)
secc = _get_security_context(key, cert)
frontend_entities, backend_entities = create_entity_descriptors(satosa_config)
output = []
if frontend_entities:
if split_frontend_metadata:
output.extend(_create_split_entity_descriptors(frontend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(frontend_entities, secc, valid, "frontend.xml"))
if backend_entities:
if split_backend_metadata:
output.extend(_create_split_entity_descriptors(backend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(backend_entities, secc, valid, "backend.xml"))
for metadata, filename in output:
path = os.path.join(dir, filename)
print("Writing metadata to '{}'".format(path))
with open(path, "w") as f:
f.write(metadata) | [
"def",
"create_and_write_saml_metadata",
"(",
"proxy_conf",
",",
"key",
",",
"cert",
",",
"dir",
",",
"valid",
",",
"split_frontend_metadata",
"=",
"False",
",",
"split_backend_metadata",
"=",
"False",
")",
":",
"satosa_config",
"=",
"SATOSAConfig",
"(",
"proxy_conf",
")",
"secc",
"=",
"_get_security_context",
"(",
"key",
",",
"cert",
")",
"frontend_entities",
",",
"backend_entities",
"=",
"create_entity_descriptors",
"(",
"satosa_config",
")",
"output",
"=",
"[",
"]",
"if",
"frontend_entities",
":",
"if",
"split_frontend_metadata",
":",
"output",
".",
"extend",
"(",
"_create_split_entity_descriptors",
"(",
"frontend_entities",
",",
"secc",
",",
"valid",
")",
")",
"else",
":",
"output",
".",
"extend",
"(",
"_create_merged_entities_descriptors",
"(",
"frontend_entities",
",",
"secc",
",",
"valid",
",",
"\"frontend.xml\"",
")",
")",
"if",
"backend_entities",
":",
"if",
"split_backend_metadata",
":",
"output",
".",
"extend",
"(",
"_create_split_entity_descriptors",
"(",
"backend_entities",
",",
"secc",
",",
"valid",
")",
")",
"else",
":",
"output",
".",
"extend",
"(",
"_create_merged_entities_descriptors",
"(",
"backend_entities",
",",
"secc",
",",
"valid",
",",
"\"backend.xml\"",
")",
")",
"for",
"metadata",
",",
"filename",
"in",
"output",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"filename",
")",
"print",
"(",
"\"Writing metadata to '{}'\"",
".",
"format",
"(",
"path",
")",
")",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"metadata",
")"
] | Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT. | [
"Generates",
"SAML",
"metadata",
"for",
"the",
"given",
"PROXY_CONF",
"signed",
"with",
"the",
"given",
"KEY",
"and",
"associated",
"CERT",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/scripts/satosa_saml_metadata.py#L38-L63 | train | 231,887 |
IdentityPython/SATOSA | src/satosa/micro_services/account_linking.py | AccountLinking._handle_al_response | def _handle_al_response(self, context):
"""
Endpoint for handling account linking service response. When getting here
user might have approved or rejected linking their account
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
saved_state = context.state[self.name]
internal_response = InternalData.from_dict(saved_state)
#subject_id here is the linked id , not the facebook one, Figure out what to do
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.attributes['issuer_user_id'])
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
del context.state[self.name]
return super().process(context, internal_response)
else:
# User selected not to link their accounts, so the internal.response.subject_id is based on the
# issuers id/sub which is fine
satosa_logging(logger, logging.INFO, "User selected to not link their identity in AL service",
context.state)
del context.state[self.name]
return super().process(context, internal_response) | python | def _handle_al_response(self, context):
"""
Endpoint for handling account linking service response. When getting here
user might have approved or rejected linking their account
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
saved_state = context.state[self.name]
internal_response = InternalData.from_dict(saved_state)
#subject_id here is the linked id , not the facebook one, Figure out what to do
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.attributes['issuer_user_id'])
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
del context.state[self.name]
return super().process(context, internal_response)
else:
# User selected not to link their accounts, so the internal.response.subject_id is based on the
# issuers id/sub which is fine
satosa_logging(logger, logging.INFO, "User selected to not link their identity in AL service",
context.state)
del context.state[self.name]
return super().process(context, internal_response) | [
"def",
"_handle_al_response",
"(",
"self",
",",
"context",
")",
":",
"saved_state",
"=",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"internal_response",
"=",
"InternalData",
".",
"from_dict",
"(",
"saved_state",
")",
"#subject_id here is the linked id , not the facebook one, Figure out what to do",
"status_code",
",",
"message",
"=",
"self",
".",
"_get_uuid",
"(",
"context",
",",
"internal_response",
".",
"auth_info",
".",
"issuer",
",",
"internal_response",
".",
"attributes",
"[",
"'issuer_user_id'",
"]",
")",
"if",
"status_code",
"==",
"200",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"issuer/id pair is linked in AL service\"",
",",
"context",
".",
"state",
")",
"internal_response",
".",
"subject_id",
"=",
"message",
"if",
"self",
".",
"id_to_attr",
":",
"internal_response",
".",
"attributes",
"[",
"self",
".",
"id_to_attr",
"]",
"=",
"[",
"message",
"]",
"del",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"return",
"super",
"(",
")",
".",
"process",
"(",
"context",
",",
"internal_response",
")",
"else",
":",
"# User selected not to link their accounts, so the internal.response.subject_id is based on the",
"# issuers id/sub which is fine",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"User selected to not link their identity in AL service\"",
",",
"context",
".",
"state",
")",
"del",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"return",
"super",
"(",
")",
".",
"process",
"(",
"context",
",",
"internal_response",
")"
] | Endpoint for handling account linking service response. When getting here
user might have approved or rejected linking their account
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response | [
"Endpoint",
"for",
"handling",
"account",
"linking",
"service",
"response",
".",
"When",
"getting",
"here",
"user",
"might",
"have",
"approved",
"or",
"rejected",
"linking",
"their",
"account"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/account_linking.py#L38-L70 | train | 231,888 |
IdentityPython/SATOSA | src/satosa/micro_services/account_linking.py | AccountLinking.process | def process(self, context, internal_response):
"""
Manage account linking and recovery
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context:
:param internal_response:
:return: response
:
"""
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.subject_id)
data = {
"issuer": internal_response.auth_info.issuer,
"redirect_endpoint": "%s/account_linking%s" % (self.base_url, self.endpoint)
}
# Store the issuer subject_id/sub because we'll need it in handle_al_response
internal_response.attributes['issuer_user_id'] = internal_response.subject_id
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
data['user_id'] = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
else:
satosa_logging(logger, logging.INFO, "issuer/id pair is not linked in AL service. Got a ticket",
context.state)
data['ticket'] = message
jws = JWS(json.dumps(data), alg=self.signing_key.alg).sign_compact([self.signing_key])
context.state[self.name] = internal_response.to_dict()
return Redirect("%s/%s" % (self.redirect_url, jws)) | python | def process(self, context, internal_response):
"""
Manage account linking and recovery
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context:
:param internal_response:
:return: response
:
"""
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.subject_id)
data = {
"issuer": internal_response.auth_info.issuer,
"redirect_endpoint": "%s/account_linking%s" % (self.base_url, self.endpoint)
}
# Store the issuer subject_id/sub because we'll need it in handle_al_response
internal_response.attributes['issuer_user_id'] = internal_response.subject_id
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
data['user_id'] = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
else:
satosa_logging(logger, logging.INFO, "issuer/id pair is not linked in AL service. Got a ticket",
context.state)
data['ticket'] = message
jws = JWS(json.dumps(data), alg=self.signing_key.alg).sign_compact([self.signing_key])
context.state[self.name] = internal_response.to_dict()
return Redirect("%s/%s" % (self.redirect_url, jws)) | [
"def",
"process",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"status_code",
",",
"message",
"=",
"self",
".",
"_get_uuid",
"(",
"context",
",",
"internal_response",
".",
"auth_info",
".",
"issuer",
",",
"internal_response",
".",
"subject_id",
")",
"data",
"=",
"{",
"\"issuer\"",
":",
"internal_response",
".",
"auth_info",
".",
"issuer",
",",
"\"redirect_endpoint\"",
":",
"\"%s/account_linking%s\"",
"%",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"endpoint",
")",
"}",
"# Store the issuer subject_id/sub because we'll need it in handle_al_response",
"internal_response",
".",
"attributes",
"[",
"'issuer_user_id'",
"]",
"=",
"internal_response",
".",
"subject_id",
"if",
"status_code",
"==",
"200",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"issuer/id pair is linked in AL service\"",
",",
"context",
".",
"state",
")",
"internal_response",
".",
"subject_id",
"=",
"message",
"data",
"[",
"'user_id'",
"]",
"=",
"message",
"if",
"self",
".",
"id_to_attr",
":",
"internal_response",
".",
"attributes",
"[",
"self",
".",
"id_to_attr",
"]",
"=",
"[",
"message",
"]",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"issuer/id pair is not linked in AL service. Got a ticket\"",
",",
"context",
".",
"state",
")",
"data",
"[",
"'ticket'",
"]",
"=",
"message",
"jws",
"=",
"JWS",
"(",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"alg",
"=",
"self",
".",
"signing_key",
".",
"alg",
")",
".",
"sign_compact",
"(",
"[",
"self",
".",
"signing_key",
"]",
")",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"=",
"internal_response",
".",
"to_dict",
"(",
")",
"return",
"Redirect",
"(",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"redirect_url",
",",
"jws",
")",
")"
] | Manage account linking and recovery
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context:
:param internal_response:
:return: response
: | [
"Manage",
"account",
"linking",
"and",
"recovery"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/account_linking.py#L73-L109 | train | 231,889 |
IdentityPython/SATOSA | src/satosa/routing.py | ModuleRouter.backend_routing | def backend_routing(self, context):
"""
Returns the targeted backend and an updated state
:type context: satosa.context.Context
:rtype satosa.backends.base.BackendModule
:param context: The request context
:return: backend
"""
satosa_logging(logger, logging.DEBUG, "Routing to backend: %s " % context.target_backend, context.state)
backend = self.backends[context.target_backend]["instance"]
context.state[STATE_KEY] = context.target_frontend
return backend | python | def backend_routing(self, context):
"""
Returns the targeted backend and an updated state
:type context: satosa.context.Context
:rtype satosa.backends.base.BackendModule
:param context: The request context
:return: backend
"""
satosa_logging(logger, logging.DEBUG, "Routing to backend: %s " % context.target_backend, context.state)
backend = self.backends[context.target_backend]["instance"]
context.state[STATE_KEY] = context.target_frontend
return backend | [
"def",
"backend_routing",
"(",
"self",
",",
"context",
")",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Routing to backend: %s \"",
"%",
"context",
".",
"target_backend",
",",
"context",
".",
"state",
")",
"backend",
"=",
"self",
".",
"backends",
"[",
"context",
".",
"target_backend",
"]",
"[",
"\"instance\"",
"]",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"=",
"context",
".",
"target_frontend",
"return",
"backend"
] | Returns the targeted backend and an updated state
:type context: satosa.context.Context
:rtype satosa.backends.base.BackendModule
:param context: The request context
:return: backend | [
"Returns",
"the",
"targeted",
"backend",
"and",
"an",
"updated",
"state"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/routing.py#L73-L86 | train | 231,890 |
IdentityPython/SATOSA | src/satosa/routing.py | ModuleRouter.frontend_routing | def frontend_routing(self, context):
"""
Returns the targeted frontend and original state
:type context: satosa.context.Context
:rtype satosa.frontends.base.FrontendModule
:param context: The response context
:return: frontend
"""
target_frontend = context.state[STATE_KEY]
satosa_logging(logger, logging.DEBUG, "Routing to frontend: %s " % target_frontend, context.state)
context.target_frontend = target_frontend
frontend = self.frontends[context.target_frontend]["instance"]
return frontend | python | def frontend_routing(self, context):
"""
Returns the targeted frontend and original state
:type context: satosa.context.Context
:rtype satosa.frontends.base.FrontendModule
:param context: The response context
:return: frontend
"""
target_frontend = context.state[STATE_KEY]
satosa_logging(logger, logging.DEBUG, "Routing to frontend: %s " % target_frontend, context.state)
context.target_frontend = target_frontend
frontend = self.frontends[context.target_frontend]["instance"]
return frontend | [
"def",
"frontend_routing",
"(",
"self",
",",
"context",
")",
":",
"target_frontend",
"=",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Routing to frontend: %s \"",
"%",
"target_frontend",
",",
"context",
".",
"state",
")",
"context",
".",
"target_frontend",
"=",
"target_frontend",
"frontend",
"=",
"self",
".",
"frontends",
"[",
"context",
".",
"target_frontend",
"]",
"[",
"\"instance\"",
"]",
"return",
"frontend"
] | Returns the targeted frontend and original state
:type context: satosa.context.Context
:rtype satosa.frontends.base.FrontendModule
:param context: The response context
:return: frontend | [
"Returns",
"the",
"targeted",
"frontend",
"and",
"original",
"state"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/routing.py#L88-L103 | train | 231,891 |
IdentityPython/SATOSA | src/satosa/routing.py | ModuleRouter.endpoint_routing | def endpoint_routing(self, context):
"""
Finds and returns the endpoint function bound to the path
:type context: satosa.context.Context
:rtype: ((satosa.context.Context, Any) -> Any, Any)
:param context: The request context
:return: registered endpoint and bound parameters
"""
if context.path is None:
satosa_logging(logger, logging.DEBUG, "Context did not contain a path!", context.state)
raise SATOSABadContextError("Context did not contain any path")
satosa_logging(logger, logging.DEBUG, "Routing path: %s" % context.path, context.state)
path_split = context.path.split("/")
backend = path_split[0]
if backend in self.backends:
context.target_backend = backend
else:
satosa_logging(logger, logging.DEBUG, "Unknown backend %s" % backend, context.state)
try:
name, frontend_endpoint = self._find_registered_endpoint(context, self.frontends)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_frontend = name
return frontend_endpoint
try:
name, micro_service_endpoint = self._find_registered_endpoint(context, self.micro_services)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_micro_service = name
return micro_service_endpoint
if backend in self.backends:
backend_endpoint = self._find_registered_backend_endpoint(context)
if backend_endpoint:
return backend_endpoint
raise SATOSANoBoundEndpointError("'{}' not bound to any function".format(context.path)) | python | def endpoint_routing(self, context):
"""
Finds and returns the endpoint function bound to the path
:type context: satosa.context.Context
:rtype: ((satosa.context.Context, Any) -> Any, Any)
:param context: The request context
:return: registered endpoint and bound parameters
"""
if context.path is None:
satosa_logging(logger, logging.DEBUG, "Context did not contain a path!", context.state)
raise SATOSABadContextError("Context did not contain any path")
satosa_logging(logger, logging.DEBUG, "Routing path: %s" % context.path, context.state)
path_split = context.path.split("/")
backend = path_split[0]
if backend in self.backends:
context.target_backend = backend
else:
satosa_logging(logger, logging.DEBUG, "Unknown backend %s" % backend, context.state)
try:
name, frontend_endpoint = self._find_registered_endpoint(context, self.frontends)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_frontend = name
return frontend_endpoint
try:
name, micro_service_endpoint = self._find_registered_endpoint(context, self.micro_services)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_micro_service = name
return micro_service_endpoint
if backend in self.backends:
backend_endpoint = self._find_registered_backend_endpoint(context)
if backend_endpoint:
return backend_endpoint
raise SATOSANoBoundEndpointError("'{}' not bound to any function".format(context.path)) | [
"def",
"endpoint_routing",
"(",
"self",
",",
"context",
")",
":",
"if",
"context",
".",
"path",
"is",
"None",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Context did not contain a path!\"",
",",
"context",
".",
"state",
")",
"raise",
"SATOSABadContextError",
"(",
"\"Context did not contain any path\"",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Routing path: %s\"",
"%",
"context",
".",
"path",
",",
"context",
".",
"state",
")",
"path_split",
"=",
"context",
".",
"path",
".",
"split",
"(",
"\"/\"",
")",
"backend",
"=",
"path_split",
"[",
"0",
"]",
"if",
"backend",
"in",
"self",
".",
"backends",
":",
"context",
".",
"target_backend",
"=",
"backend",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Unknown backend %s\"",
"%",
"backend",
",",
"context",
".",
"state",
")",
"try",
":",
"name",
",",
"frontend_endpoint",
"=",
"self",
".",
"_find_registered_endpoint",
"(",
"context",
",",
"self",
".",
"frontends",
")",
"except",
"ModuleRouter",
".",
"UnknownEndpoint",
"as",
"e",
":",
"pass",
"else",
":",
"context",
".",
"target_frontend",
"=",
"name",
"return",
"frontend_endpoint",
"try",
":",
"name",
",",
"micro_service_endpoint",
"=",
"self",
".",
"_find_registered_endpoint",
"(",
"context",
",",
"self",
".",
"micro_services",
")",
"except",
"ModuleRouter",
".",
"UnknownEndpoint",
"as",
"e",
":",
"pass",
"else",
":",
"context",
".",
"target_micro_service",
"=",
"name",
"return",
"micro_service_endpoint",
"if",
"backend",
"in",
"self",
".",
"backends",
":",
"backend_endpoint",
"=",
"self",
".",
"_find_registered_backend_endpoint",
"(",
"context",
")",
"if",
"backend_endpoint",
":",
"return",
"backend_endpoint",
"raise",
"SATOSANoBoundEndpointError",
"(",
"\"'{}' not bound to any function\"",
".",
"format",
"(",
"context",
".",
"path",
")",
")"
] | Finds and returns the endpoint function bound to the path
:type context: satosa.context.Context
:rtype: ((satosa.context.Context, Any) -> Any, Any)
:param context: The request context
:return: registered endpoint and bound parameters | [
"Finds",
"and",
"returns",
"the",
"endpoint",
"function",
"bound",
"to",
"the",
"path"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/routing.py#L128-L172 | train | 231,892 |
IdentityPython/SATOSA | src/satosa/base.py | SATOSABase._auth_req_callback_func | def _auth_req_callback_func(self, context, internal_request):
"""
This function is called by a frontend module when an authorization request has been
processed.
:type context: satosa.context.Context
:type internal_request: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_request: request processed by the frontend
:return: response
"""
state = context.state
state[STATE_KEY] = {"requester": internal_request.requester}
# TODO consent module should manage any state it needs by itself
try:
state_dict = context.state[consent.STATE_KEY]
except KeyError:
state_dict = context.state[consent.STATE_KEY] = {}
finally:
state_dict.update({
"filter": internal_request.attributes or [],
"requester_name": internal_request.requester_name,
})
satosa_logging(logger, logging.INFO,
"Requesting provider: {}".format(internal_request.requester), state)
if self.request_micro_services:
return self.request_micro_services[0].process(context, internal_request)
return self._auth_req_finish(context, internal_request) | python | def _auth_req_callback_func(self, context, internal_request):
"""
This function is called by a frontend module when an authorization request has been
processed.
:type context: satosa.context.Context
:type internal_request: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_request: request processed by the frontend
:return: response
"""
state = context.state
state[STATE_KEY] = {"requester": internal_request.requester}
# TODO consent module should manage any state it needs by itself
try:
state_dict = context.state[consent.STATE_KEY]
except KeyError:
state_dict = context.state[consent.STATE_KEY] = {}
finally:
state_dict.update({
"filter": internal_request.attributes or [],
"requester_name": internal_request.requester_name,
})
satosa_logging(logger, logging.INFO,
"Requesting provider: {}".format(internal_request.requester), state)
if self.request_micro_services:
return self.request_micro_services[0].process(context, internal_request)
return self._auth_req_finish(context, internal_request) | [
"def",
"_auth_req_callback_func",
"(",
"self",
",",
"context",
",",
"internal_request",
")",
":",
"state",
"=",
"context",
".",
"state",
"state",
"[",
"STATE_KEY",
"]",
"=",
"{",
"\"requester\"",
":",
"internal_request",
".",
"requester",
"}",
"# TODO consent module should manage any state it needs by itself",
"try",
":",
"state_dict",
"=",
"context",
".",
"state",
"[",
"consent",
".",
"STATE_KEY",
"]",
"except",
"KeyError",
":",
"state_dict",
"=",
"context",
".",
"state",
"[",
"consent",
".",
"STATE_KEY",
"]",
"=",
"{",
"}",
"finally",
":",
"state_dict",
".",
"update",
"(",
"{",
"\"filter\"",
":",
"internal_request",
".",
"attributes",
"or",
"[",
"]",
",",
"\"requester_name\"",
":",
"internal_request",
".",
"requester_name",
",",
"}",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"Requesting provider: {}\"",
".",
"format",
"(",
"internal_request",
".",
"requester",
")",
",",
"state",
")",
"if",
"self",
".",
"request_micro_services",
":",
"return",
"self",
".",
"request_micro_services",
"[",
"0",
"]",
".",
"process",
"(",
"context",
",",
"internal_request",
")",
"return",
"self",
".",
"_auth_req_finish",
"(",
"context",
",",
"internal_request",
")"
] | This function is called by a frontend module when an authorization request has been
processed.
:type context: satosa.context.Context
:type internal_request: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_request: request processed by the frontend
:return: response | [
"This",
"function",
"is",
"called",
"by",
"a",
"frontend",
"module",
"when",
"an",
"authorization",
"request",
"has",
"been",
"processed",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L114-L146 | train | 231,893 |
IdentityPython/SATOSA | src/satosa/base.py | SATOSABase._auth_resp_callback_func | def _auth_resp_callback_func(self, context, internal_response):
"""
This function is called by a backend module when the authorization is
complete.
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_response: The authentication response
:return: response
"""
context.request = None
internal_response.requester = context.state[STATE_KEY]["requester"]
# If configured construct the user id from attribute values.
if "user_id_from_attrs" in self.config["INTERNAL_ATTRIBUTES"]:
subject_id = [
"".join(internal_response.attributes[attr]) for attr in
self.config["INTERNAL_ATTRIBUTES"]["user_id_from_attrs"]
]
internal_response.subject_id = "".join(subject_id)
if self.response_micro_services:
return self.response_micro_services[0].process(
context, internal_response)
return self._auth_resp_finish(context, internal_response) | python | def _auth_resp_callback_func(self, context, internal_response):
"""
This function is called by a backend module when the authorization is
complete.
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_response: The authentication response
:return: response
"""
context.request = None
internal_response.requester = context.state[STATE_KEY]["requester"]
# If configured construct the user id from attribute values.
if "user_id_from_attrs" in self.config["INTERNAL_ATTRIBUTES"]:
subject_id = [
"".join(internal_response.attributes[attr]) for attr in
self.config["INTERNAL_ATTRIBUTES"]["user_id_from_attrs"]
]
internal_response.subject_id = "".join(subject_id)
if self.response_micro_services:
return self.response_micro_services[0].process(
context, internal_response)
return self._auth_resp_finish(context, internal_response) | [
"def",
"_auth_resp_callback_func",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"context",
".",
"request",
"=",
"None",
"internal_response",
".",
"requester",
"=",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"[",
"\"requester\"",
"]",
"# If configured construct the user id from attribute values.",
"if",
"\"user_id_from_attrs\"",
"in",
"self",
".",
"config",
"[",
"\"INTERNAL_ATTRIBUTES\"",
"]",
":",
"subject_id",
"=",
"[",
"\"\"",
".",
"join",
"(",
"internal_response",
".",
"attributes",
"[",
"attr",
"]",
")",
"for",
"attr",
"in",
"self",
".",
"config",
"[",
"\"INTERNAL_ATTRIBUTES\"",
"]",
"[",
"\"user_id_from_attrs\"",
"]",
"]",
"internal_response",
".",
"subject_id",
"=",
"\"\"",
".",
"join",
"(",
"subject_id",
")",
"if",
"self",
".",
"response_micro_services",
":",
"return",
"self",
".",
"response_micro_services",
"[",
"0",
"]",
".",
"process",
"(",
"context",
",",
"internal_response",
")",
"return",
"self",
".",
"_auth_resp_finish",
"(",
"context",
",",
"internal_response",
")"
] | This function is called by a backend module when the authorization is
complete.
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_response: The authentication response
:return: response | [
"This",
"function",
"is",
"called",
"by",
"a",
"backend",
"module",
"when",
"the",
"authorization",
"is",
"complete",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L170-L199 | train | 231,894 |
IdentityPython/SATOSA | src/satosa/base.py | SATOSABase._handle_satosa_authentication_error | def _handle_satosa_authentication_error(self, error):
"""
Sends a response to the requester about the error
:type error: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
:param error: The exception
:return: response
"""
context = Context()
context.state = error.state
frontend = self.module_router.frontend_routing(context)
return frontend.handle_backend_error(error) | python | def _handle_satosa_authentication_error(self, error):
"""
Sends a response to the requester about the error
:type error: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
:param error: The exception
:return: response
"""
context = Context()
context.state = error.state
frontend = self.module_router.frontend_routing(context)
return frontend.handle_backend_error(error) | [
"def",
"_handle_satosa_authentication_error",
"(",
"self",
",",
"error",
")",
":",
"context",
"=",
"Context",
"(",
")",
"context",
".",
"state",
"=",
"error",
".",
"state",
"frontend",
"=",
"self",
".",
"module_router",
".",
"frontend_routing",
"(",
"context",
")",
"return",
"frontend",
".",
"handle_backend_error",
"(",
"error",
")"
] | Sends a response to the requester about the error
:type error: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
:param error: The exception
:return: response | [
"Sends",
"a",
"response",
"to",
"the",
"requester",
"about",
"the",
"error"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L201-L214 | train | 231,895 |
IdentityPython/SATOSA | src/satosa/base.py | SATOSABase._load_state | def _load_state(self, context):
"""
Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context
"""
try:
state = cookie_to_state(
context.cookie,
self.config["COOKIE_STATE_NAME"],
self.config["STATE_ENCRYPTION_KEY"])
except SATOSAStateError as e:
msg_tmpl = 'Failed to decrypt state {state} with {error}'
msg = msg_tmpl.format(state=context.cookie, error=str(e))
satosa_logging(logger, logging.WARNING, msg, None)
state = State()
finally:
context.state = state | python | def _load_state(self, context):
"""
Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context
"""
try:
state = cookie_to_state(
context.cookie,
self.config["COOKIE_STATE_NAME"],
self.config["STATE_ENCRYPTION_KEY"])
except SATOSAStateError as e:
msg_tmpl = 'Failed to decrypt state {state} with {error}'
msg = msg_tmpl.format(state=context.cookie, error=str(e))
satosa_logging(logger, logging.WARNING, msg, None)
state = State()
finally:
context.state = state | [
"def",
"_load_state",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"state",
"=",
"cookie_to_state",
"(",
"context",
".",
"cookie",
",",
"self",
".",
"config",
"[",
"\"COOKIE_STATE_NAME\"",
"]",
",",
"self",
".",
"config",
"[",
"\"STATE_ENCRYPTION_KEY\"",
"]",
")",
"except",
"SATOSAStateError",
"as",
"e",
":",
"msg_tmpl",
"=",
"'Failed to decrypt state {state} with {error}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"state",
"=",
"context",
".",
"cookie",
",",
"error",
"=",
"str",
"(",
"e",
")",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARNING",
",",
"msg",
",",
"None",
")",
"state",
"=",
"State",
"(",
")",
"finally",
":",
"context",
".",
"state",
"=",
"state"
] | Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context | [
"Load",
"state",
"from",
"cookie",
"to",
"the",
"context"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L238-L256 | train | 231,896 |
IdentityPython/SATOSA | src/satosa/base.py | SATOSABase._save_state | def _save_state(self, resp, context):
"""
Saves a state from context to cookie
:type resp: satosa.response.Response
:type context: satosa.context.Context
:param resp: The response
:param context: Session context
"""
cookie = state_to_cookie(context.state, self.config["COOKIE_STATE_NAME"], "/",
self.config["STATE_ENCRYPTION_KEY"])
resp.headers.append(tuple(cookie.output().split(": ", 1))) | python | def _save_state(self, resp, context):
"""
Saves a state from context to cookie
:type resp: satosa.response.Response
:type context: satosa.context.Context
:param resp: The response
:param context: Session context
"""
cookie = state_to_cookie(context.state, self.config["COOKIE_STATE_NAME"], "/",
self.config["STATE_ENCRYPTION_KEY"])
resp.headers.append(tuple(cookie.output().split(": ", 1))) | [
"def",
"_save_state",
"(",
"self",
",",
"resp",
",",
"context",
")",
":",
"cookie",
"=",
"state_to_cookie",
"(",
"context",
".",
"state",
",",
"self",
".",
"config",
"[",
"\"COOKIE_STATE_NAME\"",
"]",
",",
"\"/\"",
",",
"self",
".",
"config",
"[",
"\"STATE_ENCRYPTION_KEY\"",
"]",
")",
"resp",
".",
"headers",
".",
"append",
"(",
"tuple",
"(",
"cookie",
".",
"output",
"(",
")",
".",
"split",
"(",
"\": \"",
",",
"1",
")",
")",
")"
] | Saves a state from context to cookie
:type resp: satosa.response.Response
:type context: satosa.context.Context
:param resp: The response
:param context: Session context | [
"Saves",
"a",
"state",
"from",
"context",
"to",
"cookie"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L258-L271 | train | 231,897 |
IdentityPython/SATOSA | src/satosa/base.py | SATOSABase.run | def run(self, context):
"""
Runs the satosa proxy with the given context.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The request context
:return: response
"""
try:
self._load_state(context)
spec = self.module_router.endpoint_routing(context)
resp = self._run_bound_endpoint(context, spec)
self._save_state(resp, context)
except SATOSANoBoundEndpointError:
raise
except SATOSAError:
satosa_logging(logger, logging.ERROR, "Uncaught SATOSA error ", context.state,
exc_info=True)
raise
except UnknownSystemEntity as err:
satosa_logging(logger, logging.ERROR,
"configuration error: unknown system entity " + str(err),
context.state, exc_info=False)
raise
except Exception as err:
satosa_logging(logger, logging.ERROR, "Uncaught exception", context.state,
exc_info=True)
raise SATOSAUnknownError("Unknown error") from err
return resp | python | def run(self, context):
"""
Runs the satosa proxy with the given context.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The request context
:return: response
"""
try:
self._load_state(context)
spec = self.module_router.endpoint_routing(context)
resp = self._run_bound_endpoint(context, spec)
self._save_state(resp, context)
except SATOSANoBoundEndpointError:
raise
except SATOSAError:
satosa_logging(logger, logging.ERROR, "Uncaught SATOSA error ", context.state,
exc_info=True)
raise
except UnknownSystemEntity as err:
satosa_logging(logger, logging.ERROR,
"configuration error: unknown system entity " + str(err),
context.state, exc_info=False)
raise
except Exception as err:
satosa_logging(logger, logging.ERROR, "Uncaught exception", context.state,
exc_info=True)
raise SATOSAUnknownError("Unknown error") from err
return resp | [
"def",
"run",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"self",
".",
"_load_state",
"(",
"context",
")",
"spec",
"=",
"self",
".",
"module_router",
".",
"endpoint_routing",
"(",
"context",
")",
"resp",
"=",
"self",
".",
"_run_bound_endpoint",
"(",
"context",
",",
"spec",
")",
"self",
".",
"_save_state",
"(",
"resp",
",",
"context",
")",
"except",
"SATOSANoBoundEndpointError",
":",
"raise",
"except",
"SATOSAError",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"Uncaught SATOSA error \"",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"except",
"UnknownSystemEntity",
"as",
"err",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"configuration error: unknown system entity \"",
"+",
"str",
"(",
"err",
")",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"False",
")",
"raise",
"except",
"Exception",
"as",
"err",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"Uncaught exception\"",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"SATOSAUnknownError",
"(",
"\"Unknown error\"",
")",
"from",
"err",
"return",
"resp"
] | Runs the satosa proxy with the given context.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The request context
:return: response | [
"Runs",
"the",
"satosa",
"proxy",
"with",
"the",
"given",
"context",
"."
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L273-L303 | train | 231,898 |
IdentityPython/SATOSA | src/satosa/backends/saml2.py | SAMLBackend.disco_query | def disco_query(self):
"""
Makes a request to the discovery server
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.SeeOther
:param context: The current context
:param internal_req: The request
:return: Response
"""
return_url = self.sp.config.getattr("endpoints", "sp")["discovery_response"][0][0]
loc = self.sp.create_discovery_service_request(self.discosrv, self.sp.config.entityid, **{"return": return_url})
return SeeOther(loc) | python | def disco_query(self):
"""
Makes a request to the discovery server
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.SeeOther
:param context: The current context
:param internal_req: The request
:return: Response
"""
return_url = self.sp.config.getattr("endpoints", "sp")["discovery_response"][0][0]
loc = self.sp.create_discovery_service_request(self.discosrv, self.sp.config.entityid, **{"return": return_url})
return SeeOther(loc) | [
"def",
"disco_query",
"(",
"self",
")",
":",
"return_url",
"=",
"self",
".",
"sp",
".",
"config",
".",
"getattr",
"(",
"\"endpoints\"",
",",
"\"sp\"",
")",
"[",
"\"discovery_response\"",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
"loc",
"=",
"self",
".",
"sp",
".",
"create_discovery_service_request",
"(",
"self",
".",
"discosrv",
",",
"self",
".",
"sp",
".",
"config",
".",
"entityid",
",",
"*",
"*",
"{",
"\"return\"",
":",
"return_url",
"}",
")",
"return",
"SeeOther",
"(",
"loc",
")"
] | Makes a request to the discovery server
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.SeeOther
:param context: The current context
:param internal_req: The request
:return: Response | [
"Makes",
"a",
"request",
"to",
"the",
"discovery",
"server"
] | 49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L107-L121 | train | 231,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.