partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
SSHKey._unpack_by_int
|
Returns a tuple with (location of next data field, contents of requested data field).
|
sshpubkeys/keys.py
|
def _unpack_by_int(self, data, current_position):
"""Returns a tuple with (location of next data field, contents of requested data field)."""
# Unpack length of data field
try:
requested_data_length = struct.unpack('>I', data[current_position:current_position + self.INT_LEN])[0]
except struct.error:
raise MalformedDataError("Unable to unpack %s bytes from the data" % self.INT_LEN)
# Move pointer to the beginning of the data field
current_position += self.INT_LEN
remaining_data_length = len(data[current_position:])
if remaining_data_length < requested_data_length:
raise MalformedDataError(
"Requested %s bytes, but only %s bytes available." % (requested_data_length, remaining_data_length)
)
next_data = data[current_position:current_position + requested_data_length]
# Move pointer to the end of the data field
current_position += requested_data_length
return current_position, next_data
|
def _unpack_by_int(self, data, current_position):
"""Returns a tuple with (location of next data field, contents of requested data field)."""
# Unpack length of data field
try:
requested_data_length = struct.unpack('>I', data[current_position:current_position + self.INT_LEN])[0]
except struct.error:
raise MalformedDataError("Unable to unpack %s bytes from the data" % self.INT_LEN)
# Move pointer to the beginning of the data field
current_position += self.INT_LEN
remaining_data_length = len(data[current_position:])
if remaining_data_length < requested_data_length:
raise MalformedDataError(
"Requested %s bytes, but only %s bytes available." % (requested_data_length, remaining_data_length)
)
next_data = data[current_position:current_position + requested_data_length]
# Move pointer to the end of the data field
current_position += requested_data_length
return current_position, next_data
|
[
"Returns",
"a",
"tuple",
"with",
"(",
"location",
"of",
"next",
"data",
"field",
"contents",
"of",
"requested",
"data",
"field",
")",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L168-L188
|
[
"def",
"_unpack_by_int",
"(",
"self",
",",
"data",
",",
"current_position",
")",
":",
"# Unpack length of data field",
"try",
":",
"requested_data_length",
"=",
"struct",
".",
"unpack",
"(",
"'>I'",
",",
"data",
"[",
"current_position",
":",
"current_position",
"+",
"self",
".",
"INT_LEN",
"]",
")",
"[",
"0",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
"MalformedDataError",
"(",
"\"Unable to unpack %s bytes from the data\"",
"%",
"self",
".",
"INT_LEN",
")",
"# Move pointer to the beginning of the data field",
"current_position",
"+=",
"self",
".",
"INT_LEN",
"remaining_data_length",
"=",
"len",
"(",
"data",
"[",
"current_position",
":",
"]",
")",
"if",
"remaining_data_length",
"<",
"requested_data_length",
":",
"raise",
"MalformedDataError",
"(",
"\"Requested %s bytes, but only %s bytes available.\"",
"%",
"(",
"requested_data_length",
",",
"remaining_data_length",
")",
")",
"next_data",
"=",
"data",
"[",
"current_position",
":",
"current_position",
"+",
"requested_data_length",
"]",
"# Move pointer to the end of the data field",
"current_position",
"+=",
"requested_data_length",
"return",
"current_position",
",",
"next_data"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey._parse_long
|
Calculate two's complement.
|
sshpubkeys/keys.py
|
def _parse_long(cls, data):
"""Calculate two's complement."""
if sys.version < '3':
# this does not exist in python 3 - undefined-variable disabled to make pylint happier.
ret = long(0) # pylint:disable=undefined-variable
for byte in data:
ret = (ret << 8) + ord(byte)
else:
ret = 0
for byte in data:
ret = (ret << 8) + byte
return ret
|
def _parse_long(cls, data):
"""Calculate two's complement."""
if sys.version < '3':
# this does not exist in python 3 - undefined-variable disabled to make pylint happier.
ret = long(0) # pylint:disable=undefined-variable
for byte in data:
ret = (ret << 8) + ord(byte)
else:
ret = 0
for byte in data:
ret = (ret << 8) + byte
return ret
|
[
"Calculate",
"two",
"s",
"complement",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L191-L202
|
[
"def",
"_parse_long",
"(",
"cls",
",",
"data",
")",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"# this does not exist in python 3 - undefined-variable disabled to make pylint happier.",
"ret",
"=",
"long",
"(",
"0",
")",
"# pylint:disable=undefined-variable",
"for",
"byte",
"in",
"data",
":",
"ret",
"=",
"(",
"ret",
"<<",
"8",
")",
"+",
"ord",
"(",
"byte",
")",
"else",
":",
"ret",
"=",
"0",
"for",
"byte",
"in",
"data",
":",
"ret",
"=",
"(",
"ret",
"<<",
"8",
")",
"+",
"byte",
"return",
"ret"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey.decode_key
|
Decode base64 coded part of the key.
|
sshpubkeys/keys.py
|
def decode_key(cls, pubkey_content):
"""Decode base64 coded part of the key."""
try:
decoded_key = base64.b64decode(pubkey_content.encode("ascii"))
except (TypeError, binascii.Error):
raise MalformedDataError("Unable to decode the key")
return decoded_key
|
def decode_key(cls, pubkey_content):
"""Decode base64 coded part of the key."""
try:
decoded_key = base64.b64decode(pubkey_content.encode("ascii"))
except (TypeError, binascii.Error):
raise MalformedDataError("Unable to decode the key")
return decoded_key
|
[
"Decode",
"base64",
"coded",
"part",
"of",
"the",
"key",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L239-L245
|
[
"def",
"decode_key",
"(",
"cls",
",",
"pubkey_content",
")",
":",
"try",
":",
"decoded_key",
"=",
"base64",
".",
"b64decode",
"(",
"pubkey_content",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"except",
"(",
"TypeError",
",",
"binascii",
".",
"Error",
")",
":",
"raise",
"MalformedDataError",
"(",
"\"Unable to decode the key\"",
")",
"return",
"decoded_key"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey.parse_options
|
Parses ssh options string.
|
sshpubkeys/keys.py
|
def parse_options(self, options):
"""Parses ssh options string."""
quote_open = False
parsed_options = {}
def parse_add_single_option(opt):
"""Parses and validates a single option, and adds it to parsed_options field."""
if "=" in opt:
opt_name, opt_value = opt.split("=", 1)
opt_value = opt_value.replace('"', '')
else:
opt_name = opt
opt_value = True
if " " in opt_name or not self.OPTION_NAME_RE.match(opt_name):
raise InvalidOptionNameError("%s is not valid option name." % opt_name)
if self.strict_mode:
for valid_opt_name, value_required in self.OPTIONS_SPEC:
if opt_name.lower() == valid_opt_name:
if value_required and opt_value is True:
raise MissingMandatoryOptionValueError("%s is missing mandatory value." % opt_name)
break
else:
raise UnknownOptionNameError("%s is unrecognized option name." % opt_name)
if opt_name not in parsed_options:
parsed_options[opt_name] = []
parsed_options[opt_name].append(opt_value)
start_of_current_opt = 0
i = 1 # Need to be set for empty options strings
for i, character in enumerate(options):
if character == '"': # only double quotes are allowed, no need to care about single quotes
quote_open = not quote_open
if quote_open:
continue
if character == ",":
opt = options[start_of_current_opt:i]
parse_add_single_option(opt)
start_of_current_opt = i + 1
# Data begins after the first space
if start_of_current_opt + 1 != i:
opt = options[start_of_current_opt:]
parse_add_single_option(opt)
if quote_open:
raise InvalidOptionsError("Unbalanced quotes.")
return parsed_options
|
def parse_options(self, options):
"""Parses ssh options string."""
quote_open = False
parsed_options = {}
def parse_add_single_option(opt):
"""Parses and validates a single option, and adds it to parsed_options field."""
if "=" in opt:
opt_name, opt_value = opt.split("=", 1)
opt_value = opt_value.replace('"', '')
else:
opt_name = opt
opt_value = True
if " " in opt_name or not self.OPTION_NAME_RE.match(opt_name):
raise InvalidOptionNameError("%s is not valid option name." % opt_name)
if self.strict_mode:
for valid_opt_name, value_required in self.OPTIONS_SPEC:
if opt_name.lower() == valid_opt_name:
if value_required and opt_value is True:
raise MissingMandatoryOptionValueError("%s is missing mandatory value." % opt_name)
break
else:
raise UnknownOptionNameError("%s is unrecognized option name." % opt_name)
if opt_name not in parsed_options:
parsed_options[opt_name] = []
parsed_options[opt_name].append(opt_value)
start_of_current_opt = 0
i = 1 # Need to be set for empty options strings
for i, character in enumerate(options):
if character == '"': # only double quotes are allowed, no need to care about single quotes
quote_open = not quote_open
if quote_open:
continue
if character == ",":
opt = options[start_of_current_opt:i]
parse_add_single_option(opt)
start_of_current_opt = i + 1
# Data begins after the first space
if start_of_current_opt + 1 != i:
opt = options[start_of_current_opt:]
parse_add_single_option(opt)
if quote_open:
raise InvalidOptionsError("Unbalanced quotes.")
return parsed_options
|
[
"Parses",
"ssh",
"options",
"string",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L251-L295
|
[
"def",
"parse_options",
"(",
"self",
",",
"options",
")",
":",
"quote_open",
"=",
"False",
"parsed_options",
"=",
"{",
"}",
"def",
"parse_add_single_option",
"(",
"opt",
")",
":",
"\"\"\"Parses and validates a single option, and adds it to parsed_options field.\"\"\"",
"if",
"\"=\"",
"in",
"opt",
":",
"opt_name",
",",
"opt_value",
"=",
"opt",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"opt_value",
"=",
"opt_value",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
"else",
":",
"opt_name",
"=",
"opt",
"opt_value",
"=",
"True",
"if",
"\" \"",
"in",
"opt_name",
"or",
"not",
"self",
".",
"OPTION_NAME_RE",
".",
"match",
"(",
"opt_name",
")",
":",
"raise",
"InvalidOptionNameError",
"(",
"\"%s is not valid option name.\"",
"%",
"opt_name",
")",
"if",
"self",
".",
"strict_mode",
":",
"for",
"valid_opt_name",
",",
"value_required",
"in",
"self",
".",
"OPTIONS_SPEC",
":",
"if",
"opt_name",
".",
"lower",
"(",
")",
"==",
"valid_opt_name",
":",
"if",
"value_required",
"and",
"opt_value",
"is",
"True",
":",
"raise",
"MissingMandatoryOptionValueError",
"(",
"\"%s is missing mandatory value.\"",
"%",
"opt_name",
")",
"break",
"else",
":",
"raise",
"UnknownOptionNameError",
"(",
"\"%s is unrecognized option name.\"",
"%",
"opt_name",
")",
"if",
"opt_name",
"not",
"in",
"parsed_options",
":",
"parsed_options",
"[",
"opt_name",
"]",
"=",
"[",
"]",
"parsed_options",
"[",
"opt_name",
"]",
".",
"append",
"(",
"opt_value",
")",
"start_of_current_opt",
"=",
"0",
"i",
"=",
"1",
"# Need to be set for empty options strings",
"for",
"i",
",",
"character",
"in",
"enumerate",
"(",
"options",
")",
":",
"if",
"character",
"==",
"'\"'",
":",
"# only double quotes are allowed, no need to care about single quotes",
"quote_open",
"=",
"not",
"quote_open",
"if",
"quote_open",
":",
"continue",
"if",
"character",
"==",
"\",\"",
":",
"opt",
"=",
"options",
"[",
"start_of_current_opt",
":",
"i",
"]",
"parse_add_single_option",
"(",
"opt",
")",
"start_of_current_opt",
"=",
"i",
"+",
"1",
"# Data begins after the first space",
"if",
"start_of_current_opt",
"+",
"1",
"!=",
"i",
":",
"opt",
"=",
"options",
"[",
"start_of_current_opt",
":",
"]",
"parse_add_single_option",
"(",
"opt",
")",
"if",
"quote_open",
":",
"raise",
"InvalidOptionsError",
"(",
"\"Unbalanced quotes.\"",
")",
"return",
"parsed_options"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey._process_ssh_rsa
|
Parses ssh-rsa public keys.
|
sshpubkeys/keys.py
|
def _process_ssh_rsa(self, data):
"""Parses ssh-rsa public keys."""
current_position, raw_e = self._unpack_by_int(data, 0)
current_position, raw_n = self._unpack_by_int(data, current_position)
unpacked_e = self._parse_long(raw_e)
unpacked_n = self._parse_long(raw_n)
self.rsa = RSAPublicNumbers(unpacked_e, unpacked_n).public_key(default_backend())
self.bits = self.rsa.key_size
if self.strict_mode:
min_length = self.RSA_MIN_LENGTH_STRICT
max_length = self.RSA_MAX_LENGTH_STRICT
else:
min_length = self.RSA_MIN_LENGTH_LOOSE
max_length = self.RSA_MAX_LENGTH_LOOSE
if self.bits < min_length:
raise TooShortKeyError(
"%s key data can not be shorter than %s bits (was %s)" % (self.key_type, min_length, self.bits)
)
if self.bits > max_length:
raise TooLongKeyError(
"%s key data can not be longer than %s bits (was %s)" % (self.key_type, max_length, self.bits)
)
return current_position
|
def _process_ssh_rsa(self, data):
"""Parses ssh-rsa public keys."""
current_position, raw_e = self._unpack_by_int(data, 0)
current_position, raw_n = self._unpack_by_int(data, current_position)
unpacked_e = self._parse_long(raw_e)
unpacked_n = self._parse_long(raw_n)
self.rsa = RSAPublicNumbers(unpacked_e, unpacked_n).public_key(default_backend())
self.bits = self.rsa.key_size
if self.strict_mode:
min_length = self.RSA_MIN_LENGTH_STRICT
max_length = self.RSA_MAX_LENGTH_STRICT
else:
min_length = self.RSA_MIN_LENGTH_LOOSE
max_length = self.RSA_MAX_LENGTH_LOOSE
if self.bits < min_length:
raise TooShortKeyError(
"%s key data can not be shorter than %s bits (was %s)" % (self.key_type, min_length, self.bits)
)
if self.bits > max_length:
raise TooLongKeyError(
"%s key data can not be longer than %s bits (was %s)" % (self.key_type, max_length, self.bits)
)
return current_position
|
[
"Parses",
"ssh",
"-",
"rsa",
"public",
"keys",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L297-L322
|
[
"def",
"_process_ssh_rsa",
"(",
"self",
",",
"data",
")",
":",
"current_position",
",",
"raw_e",
"=",
"self",
".",
"_unpack_by_int",
"(",
"data",
",",
"0",
")",
"current_position",
",",
"raw_n",
"=",
"self",
".",
"_unpack_by_int",
"(",
"data",
",",
"current_position",
")",
"unpacked_e",
"=",
"self",
".",
"_parse_long",
"(",
"raw_e",
")",
"unpacked_n",
"=",
"self",
".",
"_parse_long",
"(",
"raw_n",
")",
"self",
".",
"rsa",
"=",
"RSAPublicNumbers",
"(",
"unpacked_e",
",",
"unpacked_n",
")",
".",
"public_key",
"(",
"default_backend",
"(",
")",
")",
"self",
".",
"bits",
"=",
"self",
".",
"rsa",
".",
"key_size",
"if",
"self",
".",
"strict_mode",
":",
"min_length",
"=",
"self",
".",
"RSA_MIN_LENGTH_STRICT",
"max_length",
"=",
"self",
".",
"RSA_MAX_LENGTH_STRICT",
"else",
":",
"min_length",
"=",
"self",
".",
"RSA_MIN_LENGTH_LOOSE",
"max_length",
"=",
"self",
".",
"RSA_MAX_LENGTH_LOOSE",
"if",
"self",
".",
"bits",
"<",
"min_length",
":",
"raise",
"TooShortKeyError",
"(",
"\"%s key data can not be shorter than %s bits (was %s)\"",
"%",
"(",
"self",
".",
"key_type",
",",
"min_length",
",",
"self",
".",
"bits",
")",
")",
"if",
"self",
".",
"bits",
">",
"max_length",
":",
"raise",
"TooLongKeyError",
"(",
"\"%s key data can not be longer than %s bits (was %s)\"",
"%",
"(",
"self",
".",
"key_type",
",",
"max_length",
",",
"self",
".",
"bits",
")",
")",
"return",
"current_position"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey._process_ssh_dss
|
Parses ssh-dsa public keys.
|
sshpubkeys/keys.py
|
def _process_ssh_dss(self, data):
"""Parses ssh-dsa public keys."""
data_fields = {}
current_position = 0
for item in ("p", "q", "g", "y"):
current_position, value = self._unpack_by_int(data, current_position)
data_fields[item] = self._parse_long(value)
q_bits = self._bits_in_number(data_fields["q"])
p_bits = self._bits_in_number(data_fields["p"])
if q_bits != self.DSA_N_LENGTH:
raise InvalidKeyError("Incorrect DSA key parameters: bits(p)=%s, q=%s" % (self.bits, q_bits))
if self.strict_mode:
min_length = self.DSA_MIN_LENGTH_STRICT
max_length = self.DSA_MAX_LENGTH_STRICT
else:
min_length = self.DSA_MIN_LENGTH_LOOSE
max_length = self.DSA_MAX_LENGTH_LOOSE
if p_bits < min_length:
raise TooShortKeyError("%s key can not be shorter than %s bits (was %s)" % (self.key_type, min_length, p_bits))
if p_bits > max_length:
raise TooLongKeyError(
"%s key data can not be longer than %s bits (was %s)" % (self.key_type, max_length, p_bits)
)
dsa_parameters = DSAParameterNumbers(data_fields["p"], data_fields["q"], data_fields["g"])
self.dsa = DSAPublicNumbers(data_fields["y"], dsa_parameters).public_key(default_backend())
self.bits = self.dsa.key_size
return current_position
|
def _process_ssh_dss(self, data):
"""Parses ssh-dsa public keys."""
data_fields = {}
current_position = 0
for item in ("p", "q", "g", "y"):
current_position, value = self._unpack_by_int(data, current_position)
data_fields[item] = self._parse_long(value)
q_bits = self._bits_in_number(data_fields["q"])
p_bits = self._bits_in_number(data_fields["p"])
if q_bits != self.DSA_N_LENGTH:
raise InvalidKeyError("Incorrect DSA key parameters: bits(p)=%s, q=%s" % (self.bits, q_bits))
if self.strict_mode:
min_length = self.DSA_MIN_LENGTH_STRICT
max_length = self.DSA_MAX_LENGTH_STRICT
else:
min_length = self.DSA_MIN_LENGTH_LOOSE
max_length = self.DSA_MAX_LENGTH_LOOSE
if p_bits < min_length:
raise TooShortKeyError("%s key can not be shorter than %s bits (was %s)" % (self.key_type, min_length, p_bits))
if p_bits > max_length:
raise TooLongKeyError(
"%s key data can not be longer than %s bits (was %s)" % (self.key_type, max_length, p_bits)
)
dsa_parameters = DSAParameterNumbers(data_fields["p"], data_fields["q"], data_fields["g"])
self.dsa = DSAPublicNumbers(data_fields["y"], dsa_parameters).public_key(default_backend())
self.bits = self.dsa.key_size
return current_position
|
[
"Parses",
"ssh",
"-",
"dsa",
"public",
"keys",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L324-L353
|
[
"def",
"_process_ssh_dss",
"(",
"self",
",",
"data",
")",
":",
"data_fields",
"=",
"{",
"}",
"current_position",
"=",
"0",
"for",
"item",
"in",
"(",
"\"p\"",
",",
"\"q\"",
",",
"\"g\"",
",",
"\"y\"",
")",
":",
"current_position",
",",
"value",
"=",
"self",
".",
"_unpack_by_int",
"(",
"data",
",",
"current_position",
")",
"data_fields",
"[",
"item",
"]",
"=",
"self",
".",
"_parse_long",
"(",
"value",
")",
"q_bits",
"=",
"self",
".",
"_bits_in_number",
"(",
"data_fields",
"[",
"\"q\"",
"]",
")",
"p_bits",
"=",
"self",
".",
"_bits_in_number",
"(",
"data_fields",
"[",
"\"p\"",
"]",
")",
"if",
"q_bits",
"!=",
"self",
".",
"DSA_N_LENGTH",
":",
"raise",
"InvalidKeyError",
"(",
"\"Incorrect DSA key parameters: bits(p)=%s, q=%s\"",
"%",
"(",
"self",
".",
"bits",
",",
"q_bits",
")",
")",
"if",
"self",
".",
"strict_mode",
":",
"min_length",
"=",
"self",
".",
"DSA_MIN_LENGTH_STRICT",
"max_length",
"=",
"self",
".",
"DSA_MAX_LENGTH_STRICT",
"else",
":",
"min_length",
"=",
"self",
".",
"DSA_MIN_LENGTH_LOOSE",
"max_length",
"=",
"self",
".",
"DSA_MAX_LENGTH_LOOSE",
"if",
"p_bits",
"<",
"min_length",
":",
"raise",
"TooShortKeyError",
"(",
"\"%s key can not be shorter than %s bits (was %s)\"",
"%",
"(",
"self",
".",
"key_type",
",",
"min_length",
",",
"p_bits",
")",
")",
"if",
"p_bits",
">",
"max_length",
":",
"raise",
"TooLongKeyError",
"(",
"\"%s key data can not be longer than %s bits (was %s)\"",
"%",
"(",
"self",
".",
"key_type",
",",
"max_length",
",",
"p_bits",
")",
")",
"dsa_parameters",
"=",
"DSAParameterNumbers",
"(",
"data_fields",
"[",
"\"p\"",
"]",
",",
"data_fields",
"[",
"\"q\"",
"]",
",",
"data_fields",
"[",
"\"g\"",
"]",
")",
"self",
".",
"dsa",
"=",
"DSAPublicNumbers",
"(",
"data_fields",
"[",
"\"y\"",
"]",
",",
"dsa_parameters",
")",
".",
"public_key",
"(",
"default_backend",
"(",
")",
")",
"self",
".",
"bits",
"=",
"self",
".",
"dsa",
".",
"key_size",
"return",
"current_position"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey._process_ecdsa_sha
|
Parses ecdsa-sha public keys.
|
sshpubkeys/keys.py
|
def _process_ecdsa_sha(self, data):
"""Parses ecdsa-sha public keys."""
current_position, curve_information = self._unpack_by_int(data, 0)
if curve_information not in self.ECDSA_CURVE_DATA:
raise NotImplementedError("Invalid curve type: %s" % curve_information)
curve, hash_algorithm = self.ECDSA_CURVE_DATA[curve_information]
current_position, key_data = self._unpack_by_int(data, current_position)
try:
# data starts with \x04, which should be discarded.
ecdsa_key = ecdsa.VerifyingKey.from_string(key_data[1:], curve, hash_algorithm)
except AssertionError:
raise InvalidKeyError("Invalid ecdsa key")
self.bits = int(curve_information.replace(b"nistp", b""))
self.ecdsa = ecdsa_key
return current_position
|
def _process_ecdsa_sha(self, data):
"""Parses ecdsa-sha public keys."""
current_position, curve_information = self._unpack_by_int(data, 0)
if curve_information not in self.ECDSA_CURVE_DATA:
raise NotImplementedError("Invalid curve type: %s" % curve_information)
curve, hash_algorithm = self.ECDSA_CURVE_DATA[curve_information]
current_position, key_data = self._unpack_by_int(data, current_position)
try:
# data starts with \x04, which should be discarded.
ecdsa_key = ecdsa.VerifyingKey.from_string(key_data[1:], curve, hash_algorithm)
except AssertionError:
raise InvalidKeyError("Invalid ecdsa key")
self.bits = int(curve_information.replace(b"nistp", b""))
self.ecdsa = ecdsa_key
return current_position
|
[
"Parses",
"ecdsa",
"-",
"sha",
"public",
"keys",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L355-L370
|
[
"def",
"_process_ecdsa_sha",
"(",
"self",
",",
"data",
")",
":",
"current_position",
",",
"curve_information",
"=",
"self",
".",
"_unpack_by_int",
"(",
"data",
",",
"0",
")",
"if",
"curve_information",
"not",
"in",
"self",
".",
"ECDSA_CURVE_DATA",
":",
"raise",
"NotImplementedError",
"(",
"\"Invalid curve type: %s\"",
"%",
"curve_information",
")",
"curve",
",",
"hash_algorithm",
"=",
"self",
".",
"ECDSA_CURVE_DATA",
"[",
"curve_information",
"]",
"current_position",
",",
"key_data",
"=",
"self",
".",
"_unpack_by_int",
"(",
"data",
",",
"current_position",
")",
"try",
":",
"# data starts with \\x04, which should be discarded.",
"ecdsa_key",
"=",
"ecdsa",
".",
"VerifyingKey",
".",
"from_string",
"(",
"key_data",
"[",
"1",
":",
"]",
",",
"curve",
",",
"hash_algorithm",
")",
"except",
"AssertionError",
":",
"raise",
"InvalidKeyError",
"(",
"\"Invalid ecdsa key\"",
")",
"self",
".",
"bits",
"=",
"int",
"(",
"curve_information",
".",
"replace",
"(",
"b\"nistp\"",
",",
"b\"\"",
")",
")",
"self",
".",
"ecdsa",
"=",
"ecdsa_key",
"return",
"current_position"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey._process_ed25516
|
Parses ed25516 keys.
There is no (apparent) way to validate ed25519 keys. This only
checks data length (256 bits), but does not try to validate
the key in any way.
|
sshpubkeys/keys.py
|
def _process_ed25516(self, data):
"""Parses ed25516 keys.
There is no (apparent) way to validate ed25519 keys. This only
checks data length (256 bits), but does not try to validate
the key in any way."""
current_position, verifying_key = self._unpack_by_int(data, 0)
verifying_key_length = len(verifying_key) * 8
verifying_key = self._parse_long(verifying_key)
if verifying_key < 0:
raise InvalidKeyError("ed25519 verifying key must be >0.")
self.bits = verifying_key_length
if self.bits != 256:
raise InvalidKeyLengthError("ed25519 keys must be 256 bits (was %s bits)" % self.bits)
return current_position
|
def _process_ed25516(self, data):
"""Parses ed25516 keys.
There is no (apparent) way to validate ed25519 keys. This only
checks data length (256 bits), but does not try to validate
the key in any way."""
current_position, verifying_key = self._unpack_by_int(data, 0)
verifying_key_length = len(verifying_key) * 8
verifying_key = self._parse_long(verifying_key)
if verifying_key < 0:
raise InvalidKeyError("ed25519 verifying key must be >0.")
self.bits = verifying_key_length
if self.bits != 256:
raise InvalidKeyLengthError("ed25519 keys must be 256 bits (was %s bits)" % self.bits)
return current_position
|
[
"Parses",
"ed25516",
"keys",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L372-L389
|
[
"def",
"_process_ed25516",
"(",
"self",
",",
"data",
")",
":",
"current_position",
",",
"verifying_key",
"=",
"self",
".",
"_unpack_by_int",
"(",
"data",
",",
"0",
")",
"verifying_key_length",
"=",
"len",
"(",
"verifying_key",
")",
"*",
"8",
"verifying_key",
"=",
"self",
".",
"_parse_long",
"(",
"verifying_key",
")",
"if",
"verifying_key",
"<",
"0",
":",
"raise",
"InvalidKeyError",
"(",
"\"ed25519 verifying key must be >0.\"",
")",
"self",
".",
"bits",
"=",
"verifying_key_length",
"if",
"self",
".",
"bits",
"!=",
"256",
":",
"raise",
"InvalidKeyLengthError",
"(",
"\"ed25519 keys must be 256 bits (was %s bits)\"",
"%",
"self",
".",
"bits",
")",
"return",
"current_position"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
SSHKey.parse
|
Validates SSH public key.
Throws exception for invalid keys. Otherwise returns None.
Populates key_type, bits and bits fields.
For rsa keys, see field "rsa" for raw public key data.
For dsa keys, see field "dsa".
For ecdsa keys, see field "ecdsa".
|
sshpubkeys/keys.py
|
def parse(self, keydata=None):
"""Validates SSH public key.
Throws exception for invalid keys. Otherwise returns None.
Populates key_type, bits and bits fields.
For rsa keys, see field "rsa" for raw public key data.
For dsa keys, see field "dsa".
For ecdsa keys, see field "ecdsa"."""
if keydata is None:
if self.keydata is None:
raise ValueError("Key data must be supplied either in constructor or to parse()")
keydata = self.keydata
else:
self.reset()
self.keydata = keydata
if keydata.startswith("---- BEGIN SSH2 PUBLIC KEY ----"):
# SSH2 key format
key_type = None # There is no redundant key-type field - skip comparing plain-text and encoded data.
pubkey_content = "".join([line for line in keydata.split("\n") if ":" not in line and "----" not in line])
else:
key_parts = self._split_key(keydata)
key_type = key_parts[0]
pubkey_content = key_parts[1]
self._decoded_key = self.decode_key(pubkey_content)
# Check key type
current_position, unpacked_key_type = self._unpack_by_int(self._decoded_key, 0)
if key_type is not None and key_type != unpacked_key_type.decode():
raise InvalidTypeError("Keytype mismatch: %s != %s" % (key_type, unpacked_key_type))
self.key_type = unpacked_key_type
key_data_length = self._process_key(self._decoded_key[current_position:])
current_position = current_position + key_data_length
if current_position != len(self._decoded_key):
raise MalformedDataError("Leftover data: %s bytes" % (len(self._decoded_key) - current_position))
if self.disallow_options and self.options:
raise InvalidOptionsError("Options are disallowed.")
|
def parse(self, keydata=None):
"""Validates SSH public key.
Throws exception for invalid keys. Otherwise returns None.
Populates key_type, bits and bits fields.
For rsa keys, see field "rsa" for raw public key data.
For dsa keys, see field "dsa".
For ecdsa keys, see field "ecdsa"."""
if keydata is None:
if self.keydata is None:
raise ValueError("Key data must be supplied either in constructor or to parse()")
keydata = self.keydata
else:
self.reset()
self.keydata = keydata
if keydata.startswith("---- BEGIN SSH2 PUBLIC KEY ----"):
# SSH2 key format
key_type = None # There is no redundant key-type field - skip comparing plain-text and encoded data.
pubkey_content = "".join([line for line in keydata.split("\n") if ":" not in line and "----" not in line])
else:
key_parts = self._split_key(keydata)
key_type = key_parts[0]
pubkey_content = key_parts[1]
self._decoded_key = self.decode_key(pubkey_content)
# Check key type
current_position, unpacked_key_type = self._unpack_by_int(self._decoded_key, 0)
if key_type is not None and key_type != unpacked_key_type.decode():
raise InvalidTypeError("Keytype mismatch: %s != %s" % (key_type, unpacked_key_type))
self.key_type = unpacked_key_type
key_data_length = self._process_key(self._decoded_key[current_position:])
current_position = current_position + key_data_length
if current_position != len(self._decoded_key):
raise MalformedDataError("Leftover data: %s bytes" % (len(self._decoded_key) - current_position))
if self.disallow_options and self.options:
raise InvalidOptionsError("Options are disallowed.")
|
[
"Validates",
"SSH",
"public",
"key",
"."
] |
ojarva/python-sshpubkeys
|
python
|
https://github.com/ojarva/python-sshpubkeys/blob/86dc1ab27ce82dcc091ce127416cc3ee219e9bec/sshpubkeys/keys.py#L403-L446
|
[
"def",
"parse",
"(",
"self",
",",
"keydata",
"=",
"None",
")",
":",
"if",
"keydata",
"is",
"None",
":",
"if",
"self",
".",
"keydata",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Key data must be supplied either in constructor or to parse()\"",
")",
"keydata",
"=",
"self",
".",
"keydata",
"else",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"keydata",
"=",
"keydata",
"if",
"keydata",
".",
"startswith",
"(",
"\"---- BEGIN SSH2 PUBLIC KEY ----\"",
")",
":",
"# SSH2 key format",
"key_type",
"=",
"None",
"# There is no redundant key-type field - skip comparing plain-text and encoded data.",
"pubkey_content",
"=",
"\"\"",
".",
"join",
"(",
"[",
"line",
"for",
"line",
"in",
"keydata",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"\":\"",
"not",
"in",
"line",
"and",
"\"----\"",
"not",
"in",
"line",
"]",
")",
"else",
":",
"key_parts",
"=",
"self",
".",
"_split_key",
"(",
"keydata",
")",
"key_type",
"=",
"key_parts",
"[",
"0",
"]",
"pubkey_content",
"=",
"key_parts",
"[",
"1",
"]",
"self",
".",
"_decoded_key",
"=",
"self",
".",
"decode_key",
"(",
"pubkey_content",
")",
"# Check key type",
"current_position",
",",
"unpacked_key_type",
"=",
"self",
".",
"_unpack_by_int",
"(",
"self",
".",
"_decoded_key",
",",
"0",
")",
"if",
"key_type",
"is",
"not",
"None",
"and",
"key_type",
"!=",
"unpacked_key_type",
".",
"decode",
"(",
")",
":",
"raise",
"InvalidTypeError",
"(",
"\"Keytype mismatch: %s != %s\"",
"%",
"(",
"key_type",
",",
"unpacked_key_type",
")",
")",
"self",
".",
"key_type",
"=",
"unpacked_key_type",
"key_data_length",
"=",
"self",
".",
"_process_key",
"(",
"self",
".",
"_decoded_key",
"[",
"current_position",
":",
"]",
")",
"current_position",
"=",
"current_position",
"+",
"key_data_length",
"if",
"current_position",
"!=",
"len",
"(",
"self",
".",
"_decoded_key",
")",
":",
"raise",
"MalformedDataError",
"(",
"\"Leftover data: %s bytes\"",
"%",
"(",
"len",
"(",
"self",
".",
"_decoded_key",
")",
"-",
"current_position",
")",
")",
"if",
"self",
".",
"disallow_options",
"and",
"self",
".",
"options",
":",
"raise",
"InvalidOptionsError",
"(",
"\"Options are disallowed.\"",
")"
] |
86dc1ab27ce82dcc091ce127416cc3ee219e9bec
|
test
|
status_list
|
Creates a "friendly" error message from a GSS status code. This is used to create the
:attr:`GSSCException.message` of a :class:`GSSCException`.
:param maj_status: The major status reported by the C GSSAPI.
:type maj_status: int
:param min_status: The minor status reported by the C GSSAPI.
:type min_status: int
:param status_type: Whether the status is a general GSSAPI status or a mechanism status.
:type status_type: ``GSS_C_GSS_CODE`` or ``GSS_C_MECH_CODE``
:param mech_type: Optional mechanism type, if the status is a mechanism status.
:type mech_type: :class:`~gssapi.oids.OID`
:returns: a list of strings describing the error.
:rtype: list of strings
|
gssapi/error.py
|
def status_list(maj_status, min_status, status_type=C.GSS_C_GSS_CODE, mech_type=C.GSS_C_NO_OID):
"""
Creates a "friendly" error message from a GSS status code. This is used to create the
:attr:`GSSCException.message` of a :class:`GSSCException`.
:param maj_status: The major status reported by the C GSSAPI.
:type maj_status: int
:param min_status: The minor status reported by the C GSSAPI.
:type min_status: int
:param status_type: Whether the status is a general GSSAPI status or a mechanism status.
:type status_type: ``GSS_C_GSS_CODE`` or ``GSS_C_MECH_CODE``
:param mech_type: Optional mechanism type, if the status is a mechanism status.
:type mech_type: :class:`~gssapi.oids.OID`
:returns: a list of strings describing the error.
:rtype: list of strings
"""
from .oids import OID
statuses = []
message_context = ffi.new('OM_uint32[1]')
minor_status = ffi.new('OM_uint32[1]')
if isinstance(mech_type, OID):
mech_type = ffi.addressof(mech_type._oid) # OID._oid is type "struct gss_OID_desc"
elif mech_type == C.GSS_C_NO_OID:
mech_type = ffi.cast('gss_OID', C.GSS_C_NO_OID)
elif not isinstance(mech_type, ffi.CData) or ffi.typeof(mech_type) != ffi.typeof('gss_OID'):
raise TypeError(
"Expected mech_type to be a gssapi.oids.OID or gss_OID, got {0}".format(type(mech_type))
)
while True:
status_buf = ffi.new('gss_buffer_desc[1]')
try:
retval = C.gss_display_status(
minor_status,
maj_status,
status_type,
mech_type,
message_context,
status_buf
)
if retval == C.GSS_S_COMPLETE:
statuses.append("({0}) {1}.".format(
maj_status,
_buf_to_str(status_buf[0]).decode("utf-8", errors="replace")
))
elif retval == C.GSS_S_BAD_MECH:
statuses.append("Unsupported mechanism type passed to GSSException")
break
elif retval == C.GSS_S_BAD_STATUS:
statuses.append("Unrecognized status value passed to GSSException")
break
finally:
C.gss_release_buffer(minor_status, status_buf)
if message_context[0] == 0:
break
if min_status:
minor_status_msgs = status_list(min_status, 0, C.GSS_C_MECH_CODE, mech_type)
if minor_status_msgs:
statuses.append("Minor code:")
statuses.extend(minor_status_msgs)
return statuses
|
def status_list(maj_status, min_status, status_type=C.GSS_C_GSS_CODE, mech_type=C.GSS_C_NO_OID):
"""
Creates a "friendly" error message from a GSS status code. This is used to create the
:attr:`GSSCException.message` of a :class:`GSSCException`.
:param maj_status: The major status reported by the C GSSAPI.
:type maj_status: int
:param min_status: The minor status reported by the C GSSAPI.
:type min_status: int
:param status_type: Whether the status is a general GSSAPI status or a mechanism status.
:type status_type: ``GSS_C_GSS_CODE`` or ``GSS_C_MECH_CODE``
:param mech_type: Optional mechanism type, if the status is a mechanism status.
:type mech_type: :class:`~gssapi.oids.OID`
:returns: a list of strings describing the error.
:rtype: list of strings
"""
from .oids import OID
statuses = []
message_context = ffi.new('OM_uint32[1]')
minor_status = ffi.new('OM_uint32[1]')
if isinstance(mech_type, OID):
mech_type = ffi.addressof(mech_type._oid) # OID._oid is type "struct gss_OID_desc"
elif mech_type == C.GSS_C_NO_OID:
mech_type = ffi.cast('gss_OID', C.GSS_C_NO_OID)
elif not isinstance(mech_type, ffi.CData) or ffi.typeof(mech_type) != ffi.typeof('gss_OID'):
raise TypeError(
"Expected mech_type to be a gssapi.oids.OID or gss_OID, got {0}".format(type(mech_type))
)
while True:
status_buf = ffi.new('gss_buffer_desc[1]')
try:
retval = C.gss_display_status(
minor_status,
maj_status,
status_type,
mech_type,
message_context,
status_buf
)
if retval == C.GSS_S_COMPLETE:
statuses.append("({0}) {1}.".format(
maj_status,
_buf_to_str(status_buf[0]).decode("utf-8", errors="replace")
))
elif retval == C.GSS_S_BAD_MECH:
statuses.append("Unsupported mechanism type passed to GSSException")
break
elif retval == C.GSS_S_BAD_STATUS:
statuses.append("Unrecognized status value passed to GSSException")
break
finally:
C.gss_release_buffer(minor_status, status_buf)
if message_context[0] == 0:
break
if min_status:
minor_status_msgs = status_list(min_status, 0, C.GSS_C_MECH_CODE, mech_type)
if minor_status_msgs:
statuses.append("Minor code:")
statuses.extend(minor_status_msgs)
return statuses
|
[
"Creates",
"a",
"friendly",
"error",
"message",
"from",
"a",
"GSS",
"status",
"code",
".",
"This",
"is",
"used",
"to",
"create",
"the",
":",
"attr",
":",
"GSSCException",
".",
"message",
"of",
"a",
":",
"class",
":",
"GSSCException",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/error.py#L19-L84
|
[
"def",
"status_list",
"(",
"maj_status",
",",
"min_status",
",",
"status_type",
"=",
"C",
".",
"GSS_C_GSS_CODE",
",",
"mech_type",
"=",
"C",
".",
"GSS_C_NO_OID",
")",
":",
"from",
".",
"oids",
"import",
"OID",
"statuses",
"=",
"[",
"]",
"message_context",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"if",
"isinstance",
"(",
"mech_type",
",",
"OID",
")",
":",
"mech_type",
"=",
"ffi",
".",
"addressof",
"(",
"mech_type",
".",
"_oid",
")",
"# OID._oid is type \"struct gss_OID_desc\"",
"elif",
"mech_type",
"==",
"C",
".",
"GSS_C_NO_OID",
":",
"mech_type",
"=",
"ffi",
".",
"cast",
"(",
"'gss_OID'",
",",
"C",
".",
"GSS_C_NO_OID",
")",
"elif",
"not",
"isinstance",
"(",
"mech_type",
",",
"ffi",
".",
"CData",
")",
"or",
"ffi",
".",
"typeof",
"(",
"mech_type",
")",
"!=",
"ffi",
".",
"typeof",
"(",
"'gss_OID'",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected mech_type to be a gssapi.oids.OID or gss_OID, got {0}\"",
".",
"format",
"(",
"type",
"(",
"mech_type",
")",
")",
")",
"while",
"True",
":",
"status_buf",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"try",
":",
"retval",
"=",
"C",
".",
"gss_display_status",
"(",
"minor_status",
",",
"maj_status",
",",
"status_type",
",",
"mech_type",
",",
"message_context",
",",
"status_buf",
")",
"if",
"retval",
"==",
"C",
".",
"GSS_S_COMPLETE",
":",
"statuses",
".",
"append",
"(",
"\"({0}) {1}.\"",
".",
"format",
"(",
"maj_status",
",",
"_buf_to_str",
"(",
"status_buf",
"[",
"0",
"]",
")",
".",
"decode",
"(",
"\"utf-8\"",
",",
"errors",
"=",
"\"replace\"",
")",
")",
")",
"elif",
"retval",
"==",
"C",
".",
"GSS_S_BAD_MECH",
":",
"statuses",
".",
"append",
"(",
"\"Unsupported mechanism type passed to GSSException\"",
")",
"break",
"elif",
"retval",
"==",
"C",
".",
"GSS_S_BAD_STATUS",
":",
"statuses",
".",
"append",
"(",
"\"Unrecognized status value passed to GSSException\"",
")",
"break",
"finally",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"status_buf",
")",
"if",
"message_context",
"[",
"0",
"]",
"==",
"0",
":",
"break",
"if",
"min_status",
":",
"minor_status_msgs",
"=",
"status_list",
"(",
"min_status",
",",
"0",
",",
"C",
".",
"GSS_C_MECH_CODE",
",",
"mech_type",
")",
"if",
"minor_status_msgs",
":",
"statuses",
".",
"append",
"(",
"\"Minor code:\"",
")",
"statuses",
".",
"extend",
"(",
"minor_status_msgs",
")",
"return",
"statuses"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Name.canonicalize
|
Create a canonical mechanism name (MechName) from an arbitrary internal name. The canonical
MechName would be set as the :attr:`~gssapi.ctx.AcceptContext.peer_name` property on an
acceptor's :class:`~gssapi.ctx.AcceptContext` if an initiator performed a successful
authentication to the acceptor using the given mechanism, using a
:class:`~gssapi.creds.Credential` obtained using this :class:`Name`.
:param mech: The mechanism to canonicalize this name for
:type mech: :class:`~gssapi.oids.OID`
:returns: a canonical mechanism name based on this internal name.
:rtype: :class:`MechName`
|
gssapi/names.py
|
def canonicalize(self, mech):
"""
Create a canonical mechanism name (MechName) from an arbitrary internal name. The canonical
MechName would be set as the :attr:`~gssapi.ctx.AcceptContext.peer_name` property on an
acceptor's :class:`~gssapi.ctx.AcceptContext` if an initiator performed a successful
authentication to the acceptor using the given mechanism, using a
:class:`~gssapi.creds.Credential` obtained using this :class:`Name`.
:param mech: The mechanism to canonicalize this name for
:type mech: :class:`~gssapi.oids.OID`
:returns: a canonical mechanism name based on this internal name.
:rtype: :class:`MechName`
"""
if isinstance(mech, OID):
oid = mech._oid
else:
raise TypeError("Expected an OID, got " + str(type(mech)))
minor_status = ffi.new('OM_uint32[1]')
out_name = ffi.new('gss_name_t[1]')
try:
retval = C.gss_canonicalize_name(
minor_status, self._name[0], ffi.addressof(oid), out_name
)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return MechName(out_name, mech)
except:
C.gss_release_name(minor_status, out_name)
|
def canonicalize(self, mech):
"""
Create a canonical mechanism name (MechName) from an arbitrary internal name. The canonical
MechName would be set as the :attr:`~gssapi.ctx.AcceptContext.peer_name` property on an
acceptor's :class:`~gssapi.ctx.AcceptContext` if an initiator performed a successful
authentication to the acceptor using the given mechanism, using a
:class:`~gssapi.creds.Credential` obtained using this :class:`Name`.
:param mech: The mechanism to canonicalize this name for
:type mech: :class:`~gssapi.oids.OID`
:returns: a canonical mechanism name based on this internal name.
:rtype: :class:`MechName`
"""
if isinstance(mech, OID):
oid = mech._oid
else:
raise TypeError("Expected an OID, got " + str(type(mech)))
minor_status = ffi.new('OM_uint32[1]')
out_name = ffi.new('gss_name_t[1]')
try:
retval = C.gss_canonicalize_name(
minor_status, self._name[0], ffi.addressof(oid), out_name
)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return MechName(out_name, mech)
except:
C.gss_release_name(minor_status, out_name)
|
[
"Create",
"a",
"canonical",
"mechanism",
"name",
"(",
"MechName",
")",
"from",
"an",
"arbitrary",
"internal",
"name",
".",
"The",
"canonical",
"MechName",
"would",
"be",
"set",
"as",
"the",
":",
"attr",
":",
"~gssapi",
".",
"ctx",
".",
"AcceptContext",
".",
"peer_name",
"property",
"on",
"an",
"acceptor",
"s",
":",
"class",
":",
"~gssapi",
".",
"ctx",
".",
"AcceptContext",
"if",
"an",
"initiator",
"performed",
"a",
"successful",
"authentication",
"to",
"the",
"acceptor",
"using",
"the",
"given",
"mechanism",
"using",
"a",
":",
"class",
":",
"~gssapi",
".",
"creds",
".",
"Credential",
"obtained",
"using",
"this",
":",
"class",
":",
"Name",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/names.py#L142-L170
|
[
"def",
"canonicalize",
"(",
"self",
",",
"mech",
")",
":",
"if",
"isinstance",
"(",
"mech",
",",
"OID",
")",
":",
"oid",
"=",
"mech",
".",
"_oid",
"else",
":",
"raise",
"TypeError",
"(",
"\"Expected an OID, got \"",
"+",
"str",
"(",
"type",
"(",
"mech",
")",
")",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"out_name",
"=",
"ffi",
".",
"new",
"(",
"'gss_name_t[1]'",
")",
"try",
":",
"retval",
"=",
"C",
".",
"gss_canonicalize_name",
"(",
"minor_status",
",",
"self",
".",
"_name",
"[",
"0",
"]",
",",
"ffi",
".",
"addressof",
"(",
"oid",
")",
",",
"out_name",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"MechName",
"(",
"out_name",
",",
"mech",
")",
"except",
":",
"C",
".",
"gss_release_name",
"(",
"minor_status",
",",
"out_name",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
MechName.export
|
Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
the `name_type` param set to :const:`gssapi.C_NT_EXPORT_NAME`.
:returns: an exported bytestring representation of this mechanism name
:rtype: bytes
|
gssapi/names.py
|
def export(self):
"""
Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
the `name_type` param set to :const:`gssapi.C_NT_EXPORT_NAME`.
:returns: an exported bytestring representation of this mechanism name
:rtype: bytes
"""
minor_status = ffi.new('OM_uint32[1]')
output_buffer = ffi.new('gss_buffer_desc[1]')
retval = C.gss_export_name(
minor_status,
self._name[0],
output_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self._mech_type:
raise _exception_for_status(retval, minor_status[0], self._mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return _buf_to_str(output_buffer[0])
finally:
if output_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_buffer)
|
def export(self):
"""
Returns a representation of the Mechanism Name which is suitable for direct string
comparison against other exported Mechanism Names. Its form is defined in the GSSAPI
specification (RFC 2743). It can also be re-imported by constructing a :class:`Name` with
the `name_type` param set to :const:`gssapi.C_NT_EXPORT_NAME`.
:returns: an exported bytestring representation of this mechanism name
:rtype: bytes
"""
minor_status = ffi.new('OM_uint32[1]')
output_buffer = ffi.new('gss_buffer_desc[1]')
retval = C.gss_export_name(
minor_status,
self._name[0],
output_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self._mech_type:
raise _exception_for_status(retval, minor_status[0], self._mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return _buf_to_str(output_buffer[0])
finally:
if output_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_buffer)
|
[
"Returns",
"a",
"representation",
"of",
"the",
"Mechanism",
"Name",
"which",
"is",
"suitable",
"for",
"direct",
"string",
"comparison",
"against",
"other",
"exported",
"Mechanism",
"Names",
".",
"Its",
"form",
"is",
"defined",
"in",
"the",
"GSSAPI",
"specification",
"(",
"RFC",
"2743",
")",
".",
"It",
"can",
"also",
"be",
"re",
"-",
"imported",
"by",
"constructing",
"a",
":",
"class",
":",
"Name",
"with",
"the",
"name_type",
"param",
"set",
"to",
":",
"const",
":",
"gssapi",
".",
"C_NT_EXPORT_NAME",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/names.py#L198-L225
|
[
"def",
"export",
"(",
"self",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"output_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"retval",
"=",
"C",
".",
"gss_export_name",
"(",
"minor_status",
",",
"self",
".",
"_name",
"[",
"0",
"]",
",",
"output_buffer",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"_mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"_mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"_buf_to_str",
"(",
"output_buffer",
"[",
"0",
"]",
")",
"finally",
":",
"if",
"output_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.integrity_negotiated
|
After :meth:`step` has been called, this property will be set to
True if integrity protection (signing) has been negotiated in this context, False
otherwise. If this property is True, you can use :meth:`get_mic` to sign messages with a
message integrity code (MIC), which the peer application can verify.
|
gssapi/ctx.py
|
def integrity_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if integrity protection (signing) has been negotiated in this context, False
otherwise. If this property is True, you can use :meth:`get_mic` to sign messages with a
message integrity code (MIC), which the peer application can verify.
"""
return (
self.flags & C.GSS_C_INTEG_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
def integrity_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if integrity protection (signing) has been negotiated in this context, False
otherwise. If this property is True, you can use :meth:`get_mic` to sign messages with a
message integrity code (MIC), which the peer application can verify.
"""
return (
self.flags & C.GSS_C_INTEG_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
[
"After",
":",
"meth",
":",
"step",
"has",
"been",
"called",
"this",
"property",
"will",
"be",
"set",
"to",
"True",
"if",
"integrity",
"protection",
"(",
"signing",
")",
"has",
"been",
"negotiated",
"in",
"this",
"context",
"False",
"otherwise",
".",
"If",
"this",
"property",
"is",
"True",
"you",
"can",
"use",
":",
"meth",
":",
"get_mic",
"to",
"sign",
"messages",
"with",
"a",
"message",
"integrity",
"code",
"(",
"MIC",
")",
"which",
"the",
"peer",
"application",
"can",
"verify",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L73-L84
|
[
"def",
"integrity_negotiated",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_INTEG_FLAG",
")",
"and",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.confidentiality_negotiated
|
After :meth:`step` has been called, this property will be set to
True if confidentiality (encryption) has been negotiated in this context, False otherwise.
If this property is True, you can use :meth:`wrap` with the `conf_req` param set to True to
encrypt messages sent to the peer application.
|
gssapi/ctx.py
|
def confidentiality_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if confidentiality (encryption) has been negotiated in this context, False otherwise.
If this property is True, you can use :meth:`wrap` with the `conf_req` param set to True to
encrypt messages sent to the peer application.
"""
return (
self.flags & C.GSS_C_CONF_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
def confidentiality_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if confidentiality (encryption) has been negotiated in this context, False otherwise.
If this property is True, you can use :meth:`wrap` with the `conf_req` param set to True to
encrypt messages sent to the peer application.
"""
return (
self.flags & C.GSS_C_CONF_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
[
"After",
":",
"meth",
":",
"step",
"has",
"been",
"called",
"this",
"property",
"will",
"be",
"set",
"to",
"True",
"if",
"confidentiality",
"(",
"encryption",
")",
"has",
"been",
"negotiated",
"in",
"this",
"context",
"False",
"otherwise",
".",
"If",
"this",
"property",
"is",
"True",
"you",
"can",
"use",
":",
"meth",
":",
"wrap",
"with",
"the",
"conf_req",
"param",
"set",
"to",
"True",
"to",
"encrypt",
"messages",
"sent",
"to",
"the",
"peer",
"application",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L87-L98
|
[
"def",
"confidentiality_negotiated",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_CONF_FLAG",
")",
"and",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.replay_detection_negotiated
|
After :meth:`step` has been called, this property will be set to
True if the security context can use replay detection for messages protected by
:meth:`get_mic` and :meth:`wrap`. False if replay detection cannot be used.
|
gssapi/ctx.py
|
def replay_detection_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if the security context can use replay detection for messages protected by
:meth:`get_mic` and :meth:`wrap`. False if replay detection cannot be used.
"""
return (
self.flags & C.GSS_C_REPLAY_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
def replay_detection_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if the security context can use replay detection for messages protected by
:meth:`get_mic` and :meth:`wrap`. False if replay detection cannot be used.
"""
return (
self.flags & C.GSS_C_REPLAY_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
[
"After",
":",
"meth",
":",
"step",
"has",
"been",
"called",
"this",
"property",
"will",
"be",
"set",
"to",
"True",
"if",
"the",
"security",
"context",
"can",
"use",
"replay",
"detection",
"for",
"messages",
"protected",
"by",
":",
"meth",
":",
"get_mic",
"and",
":",
"meth",
":",
"wrap",
".",
"False",
"if",
"replay",
"detection",
"cannot",
"be",
"used",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L101-L111
|
[
"def",
"replay_detection_negotiated",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_REPLAY_FLAG",
")",
"and",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.sequence_detection_negotiated
|
After :meth:`step` has been called, this property will be set to
True if the security context can use out-of-sequence message detection for messages
protected by :meth:`get_mic` and :meth:`wrap`. False if OOS detection cannot be used.
|
gssapi/ctx.py
|
def sequence_detection_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if the security context can use out-of-sequence message detection for messages
protected by :meth:`get_mic` and :meth:`wrap`. False if OOS detection cannot be used.
"""
return (
self.flags & C.GSS_C_SEQUENCE_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
def sequence_detection_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if the security context can use out-of-sequence message detection for messages
protected by :meth:`get_mic` and :meth:`wrap`. False if OOS detection cannot be used.
"""
return (
self.flags & C.GSS_C_SEQUENCE_FLAG
) and (
self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)
)
|
[
"After",
":",
"meth",
":",
"step",
"has",
"been",
"called",
"this",
"property",
"will",
"be",
"set",
"to",
"True",
"if",
"the",
"security",
"context",
"can",
"use",
"out",
"-",
"of",
"-",
"sequence",
"message",
"detection",
"for",
"messages",
"protected",
"by",
":",
"meth",
":",
"get_mic",
"and",
":",
"meth",
":",
"wrap",
".",
"False",
"if",
"OOS",
"detection",
"cannot",
"be",
"used",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L114-L124
|
[
"def",
"sequence_detection_negotiated",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_SEQUENCE_FLAG",
")",
"and",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.get_mic
|
Calculates a cryptographic message integrity code (MIC) over an application message, and
returns that MIC in a token. This is in contrast to :meth:`wrap` which calculates a MIC
over a message, optionally encrypts it and returns the original message and the MIC packed
into a single token. The peer application can then verify the MIC to ensure the associated
message has not been changed in transit.
:param message: The message to calculate a MIC for
:type message: bytes
:param qop_req: The quality of protection required. It is recommended to not change this
from the default as most GSSAPI implementations do not support it.
:returns: A MIC for the message calculated using this security context's cryptographic keys
:rtype: bytes
|
gssapi/ctx.py
|
def get_mic(self, message, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Calculates a cryptographic message integrity code (MIC) over an application message, and
returns that MIC in a token. This is in contrast to :meth:`wrap` which calculates a MIC
over a message, optionally encrypts it and returns the original message and the MIC packed
into a single token. The peer application can then verify the MIC to ensure the associated
message has not been changed in transit.
:param message: The message to calculate a MIC for
:type message: bytes
:param qop_req: The quality of protection required. It is recommended to not change this
from the default as most GSSAPI implementations do not support it.
:returns: A MIC for the message calculated using this security context's cryptographic keys
:rtype: bytes
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
retval = C.gss_get_mic(
minor_status,
self._ctx[0],
ffi.cast('gss_qop_t', qop_req),
message_buffer,
output_token_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
output_token = _buf_to_str(output_token_buffer[0])
return output_token
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
def get_mic(self, message, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Calculates a cryptographic message integrity code (MIC) over an application message, and
returns that MIC in a token. This is in contrast to :meth:`wrap` which calculates a MIC
over a message, optionally encrypts it and returns the original message and the MIC packed
into a single token. The peer application can then verify the MIC to ensure the associated
message has not been changed in transit.
:param message: The message to calculate a MIC for
:type message: bytes
:param qop_req: The quality of protection required. It is recommended to not change this
from the default as most GSSAPI implementations do not support it.
:returns: A MIC for the message calculated using this security context's cryptographic keys
:rtype: bytes
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
retval = C.gss_get_mic(
minor_status,
self._ctx[0],
ffi.cast('gss_qop_t', qop_req),
message_buffer,
output_token_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
output_token = _buf_to_str(output_token_buffer[0])
return output_token
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
[
"Calculates",
"a",
"cryptographic",
"message",
"integrity",
"code",
"(",
"MIC",
")",
"over",
"an",
"application",
"message",
"and",
"returns",
"that",
"MIC",
"in",
"a",
"token",
".",
"This",
"is",
"in",
"contrast",
"to",
":",
"meth",
":",
"wrap",
"which",
"calculates",
"a",
"MIC",
"over",
"a",
"message",
"optionally",
"encrypts",
"it",
"and",
"returns",
"the",
"original",
"message",
"and",
"the",
"MIC",
"packed",
"into",
"a",
"single",
"token",
".",
"The",
"peer",
"application",
"can",
"then",
"verify",
"the",
"MIC",
"to",
"ensure",
"the",
"associated",
"message",
"has",
"not",
"been",
"changed",
"in",
"transit",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L153-L197
|
[
"def",
"get_mic",
"(",
"self",
",",
"message",
",",
"qop_req",
"=",
"C",
".",
"GSS_C_QOP_DEFAULT",
")",
":",
"if",
"not",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_INTEG_FLAG",
")",
":",
"raise",
"GSSException",
"(",
"\"No integrity protection negotiated.\"",
")",
"if",
"not",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")",
":",
"raise",
"GSSException",
"(",
"\"Protection not yet ready.\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"output_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"message_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"message_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"message",
")",
"c_str_message",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"message",
")",
"message_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_message",
"retval",
"=",
"C",
".",
"gss_get_mic",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
"[",
"0",
"]",
",",
"ffi",
".",
"cast",
"(",
"'gss_qop_t'",
",",
"qop_req",
")",
",",
"message_buffer",
",",
"output_token_buffer",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"output_token",
"=",
"_buf_to_str",
"(",
"output_token_buffer",
"[",
"0",
"]",
")",
"return",
"output_token",
"finally",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_token_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.verify_mic
|
Takes a message integrity code (MIC) that has been generated by the peer application for a
given message, and verifies it against a message, using this security context's
cryptographic keys.
The `supplementary` parameter determines how this method deals with replayed, unsequential,
too-old or missing tokens, as follows:
If the `supplementary` parameter is False (the default), and if a replayed or otherwise
out-of-sequence token is detected, this method raises a :exc:`~gssapi.error.GSSCException`.
If no replay or out-of-sequence token is detected, this method does not raise an exception
and returns the ``qop_state`` only.
If `supplementary` is True, instead of raising an exception when a replayed or
out-of-sequence token is detected, this method returns a tuple
``(qop_state, supplementary_info)`` where ``supplementary_info`` is a tuple containing zero
or more of the constants :const:`~gssapi.S_DUPLICATE_TOKEN`, :const:`~gssapi.S_OLD_TOKEN`,
:const:`~gssapi.S_UNSEQ_TOKEN` and :const:`~gssapi.S_GAP_TOKEN`. The supplementary info
tells the caller whether a replayed or out-of-sequence message was detected. The caller
must check this and decide how to handle the message if any of the flags are set. For a
reference to the meaning of the flags, check
`RFC 2744 Section 3.9.1 <http://tools.ietf.org/html/rfc2744#section-3.9.1>` for the
corresponding GSS_S_OLD_TOKEN, etc, constants.
:param message: The message the MIC was calculated for
:type message: bytes
:param mic: The MIC calculated by the peer
:type mic: bytes
:param supplementary: Whether to also return supplementary info.
:type supplementary: bool
:returns: ``qop_state`` if `supplementary` is False, or ``(qop_state,
supplementary_info)`` if `supplementary` is True.
:raises: :exc:`~gssapi.error.GSSException` if :attr:`integrity_negotiated` is false, or
:exc:`~gssapi.error.GSSCException` if the verification fails indicating the message was
modified, replayed or out-of-sequence.
|
gssapi/ctx.py
|
def verify_mic(self, message, mic, supplementary=False):
"""
Takes a message integrity code (MIC) that has been generated by the peer application for a
given message, and verifies it against a message, using this security context's
cryptographic keys.
The `supplementary` parameter determines how this method deals with replayed, unsequential,
too-old or missing tokens, as follows:
If the `supplementary` parameter is False (the default), and if a replayed or otherwise
out-of-sequence token is detected, this method raises a :exc:`~gssapi.error.GSSCException`.
If no replay or out-of-sequence token is detected, this method does not raise an exception
and returns the ``qop_state`` only.
If `supplementary` is True, instead of raising an exception when a replayed or
out-of-sequence token is detected, this method returns a tuple
``(qop_state, supplementary_info)`` where ``supplementary_info`` is a tuple containing zero
or more of the constants :const:`~gssapi.S_DUPLICATE_TOKEN`, :const:`~gssapi.S_OLD_TOKEN`,
:const:`~gssapi.S_UNSEQ_TOKEN` and :const:`~gssapi.S_GAP_TOKEN`. The supplementary info
tells the caller whether a replayed or out-of-sequence message was detected. The caller
must check this and decide how to handle the message if any of the flags are set. For a
reference to the meaning of the flags, check
`RFC 2744 Section 3.9.1 <http://tools.ietf.org/html/rfc2744#section-3.9.1>` for the
corresponding GSS_S_OLD_TOKEN, etc, constants.
:param message: The message the MIC was calculated for
:type message: bytes
:param mic: The MIC calculated by the peer
:type mic: bytes
:param supplementary: Whether to also return supplementary info.
:type supplementary: bool
:returns: ``qop_state`` if `supplementary` is False, or ``(qop_state,
supplementary_info)`` if `supplementary` is True.
:raises: :exc:`~gssapi.error.GSSException` if :attr:`integrity_negotiated` is false, or
:exc:`~gssapi.error.GSSCException` if the verification fails indicating the message was
modified, replayed or out-of-sequence.
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
mic_buffer = ffi.new('gss_buffer_desc[1]')
mic_buffer[0].length = len(mic)
c_str_mic = ffi.new('char[]', mic)
mic_buffer[0].value = c_str_mic
qop_state = ffi.new('gss_qop_t[1]')
retval = C.gss_verify_mic(
minor_status,
self._ctx[0],
message_buffer,
mic_buffer,
qop_state
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
supp_bits = _status_bits(retval)
if supplementary:
return qop_state[0], supp_bits
elif len(supp_bits) > 0:
# Raise if unseq/replayed token detected
raise _exception_for_status(retval, minor_status[0])
else:
return qop_state[0]
|
def verify_mic(self, message, mic, supplementary=False):
"""
Takes a message integrity code (MIC) that has been generated by the peer application for a
given message, and verifies it against a message, using this security context's
cryptographic keys.
The `supplementary` parameter determines how this method deals with replayed, unsequential,
too-old or missing tokens, as follows:
If the `supplementary` parameter is False (the default), and if a replayed or otherwise
out-of-sequence token is detected, this method raises a :exc:`~gssapi.error.GSSCException`.
If no replay or out-of-sequence token is detected, this method does not raise an exception
and returns the ``qop_state`` only.
If `supplementary` is True, instead of raising an exception when a replayed or
out-of-sequence token is detected, this method returns a tuple
``(qop_state, supplementary_info)`` where ``supplementary_info`` is a tuple containing zero
or more of the constants :const:`~gssapi.S_DUPLICATE_TOKEN`, :const:`~gssapi.S_OLD_TOKEN`,
:const:`~gssapi.S_UNSEQ_TOKEN` and :const:`~gssapi.S_GAP_TOKEN`. The supplementary info
tells the caller whether a replayed or out-of-sequence message was detected. The caller
must check this and decide how to handle the message if any of the flags are set. For a
reference to the meaning of the flags, check
`RFC 2744 Section 3.9.1 <http://tools.ietf.org/html/rfc2744#section-3.9.1>` for the
corresponding GSS_S_OLD_TOKEN, etc, constants.
:param message: The message the MIC was calculated for
:type message: bytes
:param mic: The MIC calculated by the peer
:type mic: bytes
:param supplementary: Whether to also return supplementary info.
:type supplementary: bool
:returns: ``qop_state`` if `supplementary` is False, or ``(qop_state,
supplementary_info)`` if `supplementary` is True.
:raises: :exc:`~gssapi.error.GSSException` if :attr:`integrity_negotiated` is false, or
:exc:`~gssapi.error.GSSCException` if the verification fails indicating the message was
modified, replayed or out-of-sequence.
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
mic_buffer = ffi.new('gss_buffer_desc[1]')
mic_buffer[0].length = len(mic)
c_str_mic = ffi.new('char[]', mic)
mic_buffer[0].value = c_str_mic
qop_state = ffi.new('gss_qop_t[1]')
retval = C.gss_verify_mic(
minor_status,
self._ctx[0],
message_buffer,
mic_buffer,
qop_state
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
supp_bits = _status_bits(retval)
if supplementary:
return qop_state[0], supp_bits
elif len(supp_bits) > 0:
# Raise if unseq/replayed token detected
raise _exception_for_status(retval, minor_status[0])
else:
return qop_state[0]
|
[
"Takes",
"a",
"message",
"integrity",
"code",
"(",
"MIC",
")",
"that",
"has",
"been",
"generated",
"by",
"the",
"peer",
"application",
"for",
"a",
"given",
"message",
"and",
"verifies",
"it",
"against",
"a",
"message",
"using",
"this",
"security",
"context",
"s",
"cryptographic",
"keys",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L199-L271
|
[
"def",
"verify_mic",
"(",
"self",
",",
"message",
",",
"mic",
",",
"supplementary",
"=",
"False",
")",
":",
"if",
"not",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_INTEG_FLAG",
")",
":",
"raise",
"GSSException",
"(",
"\"No integrity protection negotiated.\"",
")",
"if",
"not",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")",
":",
"raise",
"GSSException",
"(",
"\"Protection not yet ready.\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"message_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"message_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"message",
")",
"c_str_message",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"message",
")",
"message_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_message",
"mic_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"mic_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"mic",
")",
"c_str_mic",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"mic",
")",
"mic_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_mic",
"qop_state",
"=",
"ffi",
".",
"new",
"(",
"'gss_qop_t[1]'",
")",
"retval",
"=",
"C",
".",
"gss_verify_mic",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
"[",
"0",
"]",
",",
"message_buffer",
",",
"mic_buffer",
",",
"qop_state",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"supp_bits",
"=",
"_status_bits",
"(",
"retval",
")",
"if",
"supplementary",
":",
"return",
"qop_state",
"[",
"0",
"]",
",",
"supp_bits",
"elif",
"len",
"(",
"supp_bits",
")",
">",
"0",
":",
"# Raise if unseq/replayed token detected",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"else",
":",
"return",
"qop_state",
"[",
"0",
"]"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.wrap
|
Wraps a message with a message integrity code, and if `conf_req` is True, encrypts the
message. The message can be decrypted and the MIC verified by the peer by passing the
token returned from this method to :meth:`unwrap` on the peer's side.
:param message: The message to wrap
:type message: bytes
:param conf_req: Whether to require confidentiality (encryption)
:type conf_req: bool
:param qop_req: The quality of protection required. It is recommended to not change this
from the default as most GSSAPI implementations do not support it.
:returns: the wrapped message in a token suitable for passing to :meth:`unwrap`
:rtype: bytes
:raises: GSSException if integrity protection is not available
(:attr:`integrity_negotiated` is False), or if the `conf_req` parameter is True and
confidentiality protection is not available
(:attr:`confidentiality_negotiated` is False)
|
gssapi/ctx.py
|
def wrap(self, message, conf_req=True, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Wraps a message with a message integrity code, and if `conf_req` is True, encrypts the
message. The message can be decrypted and the MIC verified by the peer by passing the
token returned from this method to :meth:`unwrap` on the peer's side.
:param message: The message to wrap
:type message: bytes
:param conf_req: Whether to require confidentiality (encryption)
:type conf_req: bool
:param qop_req: The quality of protection required. It is recommended to not change this
from the default as most GSSAPI implementations do not support it.
:returns: the wrapped message in a token suitable for passing to :meth:`unwrap`
:rtype: bytes
:raises: GSSException if integrity protection is not available
(:attr:`integrity_negotiated` is False), or if the `conf_req` parameter is True and
confidentiality protection is not available
(:attr:`confidentiality_negotiated` is False)
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if (conf_req and not (self.flags & C.GSS_C_CONF_FLAG)):
raise GSSException("No confidentiality protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
conf_state = ffi.new('int[1]')
retval = C.gss_wrap(
minor_status,
self._ctx[0],
ffi.cast('int', conf_req),
ffi.cast('gss_qop_t', qop_req),
message_buffer,
conf_state,
output_token_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
output_token = _buf_to_str(output_token_buffer[0])
if conf_req and not conf_state[0]:
raise GSSException("No confidentiality protection.")
return output_token
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
def wrap(self, message, conf_req=True, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Wraps a message with a message integrity code, and if `conf_req` is True, encrypts the
message. The message can be decrypted and the MIC verified by the peer by passing the
token returned from this method to :meth:`unwrap` on the peer's side.
:param message: The message to wrap
:type message: bytes
:param conf_req: Whether to require confidentiality (encryption)
:type conf_req: bool
:param qop_req: The quality of protection required. It is recommended to not change this
from the default as most GSSAPI implementations do not support it.
:returns: the wrapped message in a token suitable for passing to :meth:`unwrap`
:rtype: bytes
:raises: GSSException if integrity protection is not available
(:attr:`integrity_negotiated` is False), or if the `conf_req` parameter is True and
confidentiality protection is not available
(:attr:`confidentiality_negotiated` is False)
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if (conf_req and not (self.flags & C.GSS_C_CONF_FLAG)):
raise GSSException("No confidentiality protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
conf_state = ffi.new('int[1]')
retval = C.gss_wrap(
minor_status,
self._ctx[0],
ffi.cast('int', conf_req),
ffi.cast('gss_qop_t', qop_req),
message_buffer,
conf_state,
output_token_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
output_token = _buf_to_str(output_token_buffer[0])
if conf_req and not conf_state[0]:
raise GSSException("No confidentiality protection.")
return output_token
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
[
"Wraps",
"a",
"message",
"with",
"a",
"message",
"integrity",
"code",
"and",
"if",
"conf_req",
"is",
"True",
"encrypts",
"the",
"message",
".",
"The",
"message",
"can",
"be",
"decrypted",
"and",
"the",
"MIC",
"verified",
"by",
"the",
"peer",
"by",
"passing",
"the",
"token",
"returned",
"from",
"this",
"method",
"to",
":",
"meth",
":",
"unwrap",
"on",
"the",
"peer",
"s",
"side",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L273-L329
|
[
"def",
"wrap",
"(",
"self",
",",
"message",
",",
"conf_req",
"=",
"True",
",",
"qop_req",
"=",
"C",
".",
"GSS_C_QOP_DEFAULT",
")",
":",
"if",
"not",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_INTEG_FLAG",
")",
":",
"raise",
"GSSException",
"(",
"\"No integrity protection negotiated.\"",
")",
"if",
"(",
"conf_req",
"and",
"not",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_CONF_FLAG",
")",
")",
":",
"raise",
"GSSException",
"(",
"\"No confidentiality protection negotiated.\"",
")",
"if",
"not",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")",
":",
"raise",
"GSSException",
"(",
"\"Protection not yet ready.\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"output_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"message_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"message_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"message",
")",
"c_str_message",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"message",
")",
"message_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_message",
"conf_state",
"=",
"ffi",
".",
"new",
"(",
"'int[1]'",
")",
"retval",
"=",
"C",
".",
"gss_wrap",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
"[",
"0",
"]",
",",
"ffi",
".",
"cast",
"(",
"'int'",
",",
"conf_req",
")",
",",
"ffi",
".",
"cast",
"(",
"'gss_qop_t'",
",",
"qop_req",
")",
",",
"message_buffer",
",",
"conf_state",
",",
"output_token_buffer",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"output_token",
"=",
"_buf_to_str",
"(",
"output_token_buffer",
"[",
"0",
"]",
")",
"if",
"conf_req",
"and",
"not",
"conf_state",
"[",
"0",
"]",
":",
"raise",
"GSSException",
"(",
"\"No confidentiality protection.\"",
")",
"return",
"output_token",
"finally",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_token_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.unwrap
|
Takes a token that has been generated by the peer application with :meth:`wrap`, verifies
and optionally decrypts it, using this security context's cryptographic keys.
The `supplementary` parameter determines how this method deals with replayed, unsequential,
too-old or missing tokens, as follows:
If the `supplementary` parameter is False (the default), and if a replayed or otherwise
out-of-sequence token is detected, this method raises a :exc:`~gssapi.error.GSSCException`.
If no replay or out-of-sequence token is detected, this method returns the unwrapped
message only.
If `supplementary` is True, instead of raising an exception when a replayed or
out-of-sequence token is detected, this method returns a tuple
``(unwrapped_message, supplementary_info)`` where ``supplementary_info`` is a tuple
containing zero or more of the constants :const:`~gssapi.S_DUPLICATE_TOKEN`,
:const:`~gssapi.S_OLD_TOKEN`, :const:`~gssapi.S_UNSEQ_TOKEN` and
:const:`~gssapi.S_GAP_TOKEN`. The supplementary info tells the caller whether a replayed or
out-of-sequence message was detected. The caller must check this and decide how to handle
the message if any of the flags are set. For a reference to the meaning of the flags, check
`RFC 2744 Section 3.9.1 <http://tools.ietf.org/html/rfc2744#section-3.9.1>` for the
corresponding GSS_S_OLD_TOKEN, etc, constants.
:param message: The wrapped message token
:type message: bytes
:param conf_req: Whether to require confidentiality (encryption)
:type conf_req: bool
:param qop_req: The quality of protection required. It is recommended to not change this
from the default None as most GSSAPI implementations do not support it.
:param supplementary: Whether to also return supplementary info.
:type supplementary: bool
:returns: the verified and decrypted message if `supplementary` is False, or a tuple
``(unwrapped_message, supplementary_info)`` if `supplementary` is True.
:raises: :exc:`~gssapi.error.GSSException` if :attr:`integrity_negotiated` is false, or if
the verification or decryption fails, if the message was modified, or if
confidentiality was required (`conf_req` was True) but the message did not have
confidentiality protection applied (was not encrypted), or if the `qop_req`
parameter was set and it did not match the QOP applied to the message, or if a
replayed or out-of-sequence message was detected.
|
gssapi/ctx.py
|
def unwrap(self, message, conf_req=True, qop_req=None, supplementary=False):
"""
Takes a token that has been generated by the peer application with :meth:`wrap`, verifies
and optionally decrypts it, using this security context's cryptographic keys.
The `supplementary` parameter determines how this method deals with replayed, unsequential,
too-old or missing tokens, as follows:
If the `supplementary` parameter is False (the default), and if a replayed or otherwise
out-of-sequence token is detected, this method raises a :exc:`~gssapi.error.GSSCException`.
If no replay or out-of-sequence token is detected, this method returns the unwrapped
message only.
If `supplementary` is True, instead of raising an exception when a replayed or
out-of-sequence token is detected, this method returns a tuple
``(unwrapped_message, supplementary_info)`` where ``supplementary_info`` is a tuple
containing zero or more of the constants :const:`~gssapi.S_DUPLICATE_TOKEN`,
:const:`~gssapi.S_OLD_TOKEN`, :const:`~gssapi.S_UNSEQ_TOKEN` and
:const:`~gssapi.S_GAP_TOKEN`. The supplementary info tells the caller whether a replayed or
out-of-sequence message was detected. The caller must check this and decide how to handle
the message if any of the flags are set. For a reference to the meaning of the flags, check
`RFC 2744 Section 3.9.1 <http://tools.ietf.org/html/rfc2744#section-3.9.1>` for the
corresponding GSS_S_OLD_TOKEN, etc, constants.
:param message: The wrapped message token
:type message: bytes
:param conf_req: Whether to require confidentiality (encryption)
:type conf_req: bool
:param qop_req: The quality of protection required. It is recommended to not change this
from the default None as most GSSAPI implementations do not support it.
:param supplementary: Whether to also return supplementary info.
:type supplementary: bool
:returns: the verified and decrypted message if `supplementary` is False, or a tuple
``(unwrapped_message, supplementary_info)`` if `supplementary` is True.
:raises: :exc:`~gssapi.error.GSSException` if :attr:`integrity_negotiated` is false, or if
the verification or decryption fails, if the message was modified, or if
confidentiality was required (`conf_req` was True) but the message did not have
confidentiality protection applied (was not encrypted), or if the `qop_req`
parameter was set and it did not match the QOP applied to the message, or if a
replayed or out-of-sequence message was detected.
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
output_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
conf_state = ffi.new('int[1]')
qop_state = ffi.new('gss_qop_t[1]')
retval = C.gss_unwrap(
minor_status,
self._ctx[0],
message_buffer,
output_buffer,
conf_state,
qop_state
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
output = _buf_to_str(output_buffer[0])
if conf_req and not conf_state[0]:
raise GSSException("No confidentiality protection.")
if qop_req is not None and qop_req != qop_state[0]:
raise GSSException("QOP {0} does not match required value {1}.".format(qop_state[0], qop_req))
supp_bits = _status_bits(retval)
if supplementary:
return output, supp_bits
elif len(supp_bits) > 0:
# Raise if unseq/replayed token detected
raise _exception_for_status(retval, minor_status[0], token=output)
else:
return output
finally:
if output_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_buffer)
|
def unwrap(self, message, conf_req=True, qop_req=None, supplementary=False):
"""
Takes a token that has been generated by the peer application with :meth:`wrap`, verifies
and optionally decrypts it, using this security context's cryptographic keys.
The `supplementary` parameter determines how this method deals with replayed, unsequential,
too-old or missing tokens, as follows:
If the `supplementary` parameter is False (the default), and if a replayed or otherwise
out-of-sequence token is detected, this method raises a :exc:`~gssapi.error.GSSCException`.
If no replay or out-of-sequence token is detected, this method returns the unwrapped
message only.
If `supplementary` is True, instead of raising an exception when a replayed or
out-of-sequence token is detected, this method returns a tuple
``(unwrapped_message, supplementary_info)`` where ``supplementary_info`` is a tuple
containing zero or more of the constants :const:`~gssapi.S_DUPLICATE_TOKEN`,
:const:`~gssapi.S_OLD_TOKEN`, :const:`~gssapi.S_UNSEQ_TOKEN` and
:const:`~gssapi.S_GAP_TOKEN`. The supplementary info tells the caller whether a replayed or
out-of-sequence message was detected. The caller must check this and decide how to handle
the message if any of the flags are set. For a reference to the meaning of the flags, check
`RFC 2744 Section 3.9.1 <http://tools.ietf.org/html/rfc2744#section-3.9.1>` for the
corresponding GSS_S_OLD_TOKEN, etc, constants.
:param message: The wrapped message token
:type message: bytes
:param conf_req: Whether to require confidentiality (encryption)
:type conf_req: bool
:param qop_req: The quality of protection required. It is recommended to not change this
from the default None as most GSSAPI implementations do not support it.
:param supplementary: Whether to also return supplementary info.
:type supplementary: bool
:returns: the verified and decrypted message if `supplementary` is False, or a tuple
``(unwrapped_message, supplementary_info)`` if `supplementary` is True.
:raises: :exc:`~gssapi.error.GSSException` if :attr:`integrity_negotiated` is false, or if
the verification or decryption fails, if the message was modified, or if
confidentiality was required (`conf_req` was True) but the message did not have
confidentiality protection applied (was not encrypted), or if the `qop_req`
parameter was set and it did not match the QOP applied to the message, or if a
replayed or out-of-sequence message was detected.
"""
if not (self.flags & C.GSS_C_INTEG_FLAG):
raise GSSException("No integrity protection negotiated.")
if not (self.established or (self.flags & C.GSS_C_PROT_READY_FLAG)):
raise GSSException("Protection not yet ready.")
minor_status = ffi.new('OM_uint32[1]')
output_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer = ffi.new('gss_buffer_desc[1]')
message_buffer[0].length = len(message)
c_str_message = ffi.new('char[]', message)
message_buffer[0].value = c_str_message
conf_state = ffi.new('int[1]')
qop_state = ffi.new('gss_qop_t[1]')
retval = C.gss_unwrap(
minor_status,
self._ctx[0],
message_buffer,
output_buffer,
conf_state,
qop_state
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
output = _buf_to_str(output_buffer[0])
if conf_req and not conf_state[0]:
raise GSSException("No confidentiality protection.")
if qop_req is not None and qop_req != qop_state[0]:
raise GSSException("QOP {0} does not match required value {1}.".format(qop_state[0], qop_req))
supp_bits = _status_bits(retval)
if supplementary:
return output, supp_bits
elif len(supp_bits) > 0:
# Raise if unseq/replayed token detected
raise _exception_for_status(retval, minor_status[0], token=output)
else:
return output
finally:
if output_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_buffer)
|
[
"Takes",
"a",
"token",
"that",
"has",
"been",
"generated",
"by",
"the",
"peer",
"application",
"with",
":",
"meth",
":",
"wrap",
"verifies",
"and",
"optionally",
"decrypts",
"it",
"using",
"this",
"security",
"context",
"s",
"cryptographic",
"keys",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L331-L416
|
[
"def",
"unwrap",
"(",
"self",
",",
"message",
",",
"conf_req",
"=",
"True",
",",
"qop_req",
"=",
"None",
",",
"supplementary",
"=",
"False",
")",
":",
"if",
"not",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_INTEG_FLAG",
")",
":",
"raise",
"GSSException",
"(",
"\"No integrity protection negotiated.\"",
")",
"if",
"not",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",
")",
":",
"raise",
"GSSException",
"(",
"\"Protection not yet ready.\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"output_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"message_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"message_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"message",
")",
"c_str_message",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"message",
")",
"message_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_message",
"conf_state",
"=",
"ffi",
".",
"new",
"(",
"'int[1]'",
")",
"qop_state",
"=",
"ffi",
".",
"new",
"(",
"'gss_qop_t[1]'",
")",
"retval",
"=",
"C",
".",
"gss_unwrap",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
"[",
"0",
"]",
",",
"message_buffer",
",",
"output_buffer",
",",
"conf_state",
",",
"qop_state",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"output",
"=",
"_buf_to_str",
"(",
"output_buffer",
"[",
"0",
"]",
")",
"if",
"conf_req",
"and",
"not",
"conf_state",
"[",
"0",
"]",
":",
"raise",
"GSSException",
"(",
"\"No confidentiality protection.\"",
")",
"if",
"qop_req",
"is",
"not",
"None",
"and",
"qop_req",
"!=",
"qop_state",
"[",
"0",
"]",
":",
"raise",
"GSSException",
"(",
"\"QOP {0} does not match required value {1}.\"",
".",
"format",
"(",
"qop_state",
"[",
"0",
"]",
",",
"qop_req",
")",
")",
"supp_bits",
"=",
"_status_bits",
"(",
"retval",
")",
"if",
"supplementary",
":",
"return",
"output",
",",
"supp_bits",
"elif",
"len",
"(",
"supp_bits",
")",
">",
"0",
":",
"# Raise if unseq/replayed token detected",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"token",
"=",
"output",
")",
"else",
":",
"return",
"output",
"finally",
":",
"if",
"output_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.get_wrap_size_limit
|
Calculates the maximum size of message that can be fed to :meth:`wrap` so that the size of
the resulting wrapped token (message plus wrapping overhead) is no more than a given
maximum output size.
:param output_size: The maximum output size (in bytes) of a wrapped token
:type output_size: int
:param conf_req: Whether to calculate the wrapping overhead for confidentiality protection
(if True) or just integrity protection (if False).
:type conf_req: bool
:returns: The maximum input size (in bytes) of message that can be passed to :meth:`wrap`
:rtype: int
|
gssapi/ctx.py
|
def get_wrap_size_limit(self, output_size, conf_req=True, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Calculates the maximum size of message that can be fed to :meth:`wrap` so that the size of
the resulting wrapped token (message plus wrapping overhead) is no more than a given
maximum output size.
:param output_size: The maximum output size (in bytes) of a wrapped token
:type output_size: int
:param conf_req: Whether to calculate the wrapping overhead for confidentiality protection
(if True) or just integrity protection (if False).
:type conf_req: bool
:returns: The maximum input size (in bytes) of message that can be passed to :meth:`wrap`
:rtype: int
"""
minor_status = ffi.new('OM_uint32[1]')
max_input_size = ffi.new('OM_uint32[1]')
retval = C.gss_wrap_size_limit(
minor_status,
self._ctx[0],
ffi.cast('int', conf_req),
ffi.cast('gss_qop_t', qop_req),
ffi.cast('OM_uint32', output_size),
max_input_size
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return max_input_size[0]
|
def get_wrap_size_limit(self, output_size, conf_req=True, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Calculates the maximum size of message that can be fed to :meth:`wrap` so that the size of
the resulting wrapped token (message plus wrapping overhead) is no more than a given
maximum output size.
:param output_size: The maximum output size (in bytes) of a wrapped token
:type output_size: int
:param conf_req: Whether to calculate the wrapping overhead for confidentiality protection
(if True) or just integrity protection (if False).
:type conf_req: bool
:returns: The maximum input size (in bytes) of message that can be passed to :meth:`wrap`
:rtype: int
"""
minor_status = ffi.new('OM_uint32[1]')
max_input_size = ffi.new('OM_uint32[1]')
retval = C.gss_wrap_size_limit(
minor_status,
self._ctx[0],
ffi.cast('int', conf_req),
ffi.cast('gss_qop_t', qop_req),
ffi.cast('OM_uint32', output_size),
max_input_size
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return max_input_size[0]
|
[
"Calculates",
"the",
"maximum",
"size",
"of",
"message",
"that",
"can",
"be",
"fed",
"to",
":",
"meth",
":",
"wrap",
"so",
"that",
"the",
"size",
"of",
"the",
"resulting",
"wrapped",
"token",
"(",
"message",
"plus",
"wrapping",
"overhead",
")",
"is",
"no",
"more",
"than",
"a",
"given",
"maximum",
"output",
"size",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L418-L449
|
[
"def",
"get_wrap_size_limit",
"(",
"self",
",",
"output_size",
",",
"conf_req",
"=",
"True",
",",
"qop_req",
"=",
"C",
".",
"GSS_C_QOP_DEFAULT",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"max_input_size",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"retval",
"=",
"C",
".",
"gss_wrap_size_limit",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
"[",
"0",
"]",
",",
"ffi",
".",
"cast",
"(",
"'int'",
",",
"conf_req",
")",
",",
"ffi",
".",
"cast",
"(",
"'gss_qop_t'",
",",
"qop_req",
")",
",",
"ffi",
".",
"cast",
"(",
"'OM_uint32'",
",",
"output_size",
")",
",",
"max_input_size",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"max_input_size",
"[",
"0",
"]"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.process_context_token
|
Provides a way to pass an asynchronous token to the security context, outside of the normal
context-establishment token passing flow. This method is not normally used, but some
example uses are:
* when the initiator's context is established successfully but the acceptor's context isn't
and the acceptor needs to signal to the initiator that the context shouldn't be used.
* if :meth:`delete` on one peer's context returns a final token that can be passed to the
other peer to indicate the other peer's context should be torn down as well (though it's
recommended that :meth:`delete` should return nothing, i.e. this method should not be
used by GSSAPI mechanisms).
:param context_token: The context token to pass to the security context
:type context_token: bytes
:raises: :exc:`~gssapi.error.DefectiveToken` if consistency checks on the token failed.
:exc:`~gssapi.error.NoContext` if this context is invalid.
:exc:`~gssapi.error.GSSException` for any other GSSAPI errors.
|
gssapi/ctx.py
|
def process_context_token(self, context_token):
"""
Provides a way to pass an asynchronous token to the security context, outside of the normal
context-establishment token passing flow. This method is not normally used, but some
example uses are:
* when the initiator's context is established successfully but the acceptor's context isn't
and the acceptor needs to signal to the initiator that the context shouldn't be used.
* if :meth:`delete` on one peer's context returns a final token that can be passed to the
other peer to indicate the other peer's context should be torn down as well (though it's
recommended that :meth:`delete` should return nothing, i.e. this method should not be
used by GSSAPI mechanisms).
:param context_token: The context token to pass to the security context
:type context_token: bytes
:raises: :exc:`~gssapi.error.DefectiveToken` if consistency checks on the token failed.
:exc:`~gssapi.error.NoContext` if this context is invalid.
:exc:`~gssapi.error.GSSException` for any other GSSAPI errors.
"""
minor_status = ffi.new('OM_uint32[1]')
context_token_buffer = ffi.new('gss_buffer_desc[1]')
context_token_buffer[0].length = len(context_token)
c_str_context_token = ffi.new('char[]', context_token)
context_token_buffer[0].value = c_str_context_token
retval = C.gss_process_context_token(
minor_status,
self._ctx[0],
context_token_buffer
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
|
def process_context_token(self, context_token):
"""
Provides a way to pass an asynchronous token to the security context, outside of the normal
context-establishment token passing flow. This method is not normally used, but some
example uses are:
* when the initiator's context is established successfully but the acceptor's context isn't
and the acceptor needs to signal to the initiator that the context shouldn't be used.
* if :meth:`delete` on one peer's context returns a final token that can be passed to the
other peer to indicate the other peer's context should be torn down as well (though it's
recommended that :meth:`delete` should return nothing, i.e. this method should not be
used by GSSAPI mechanisms).
:param context_token: The context token to pass to the security context
:type context_token: bytes
:raises: :exc:`~gssapi.error.DefectiveToken` if consistency checks on the token failed.
:exc:`~gssapi.error.NoContext` if this context is invalid.
:exc:`~gssapi.error.GSSException` for any other GSSAPI errors.
"""
minor_status = ffi.new('OM_uint32[1]')
context_token_buffer = ffi.new('gss_buffer_desc[1]')
context_token_buffer[0].length = len(context_token)
c_str_context_token = ffi.new('char[]', context_token)
context_token_buffer[0].value = c_str_context_token
retval = C.gss_process_context_token(
minor_status,
self._ctx[0],
context_token_buffer
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
|
[
"Provides",
"a",
"way",
"to",
"pass",
"an",
"asynchronous",
"token",
"to",
"the",
"security",
"context",
"outside",
"of",
"the",
"normal",
"context",
"-",
"establishment",
"token",
"passing",
"flow",
".",
"This",
"method",
"is",
"not",
"normally",
"used",
"but",
"some",
"example",
"uses",
"are",
":"
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L451-L484
|
[
"def",
"process_context_token",
"(",
"self",
",",
"context_token",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"context_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"context_token_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"context_token",
")",
"c_str_context_token",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"context_token",
")",
"context_token_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_context_token",
"retval",
"=",
"C",
".",
"gss_process_context_token",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
"[",
"0",
"]",
",",
"context_token_buffer",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.export
|
This method deactivates the security context for the calling process and returns an
interprocess token which, when passed to :meth:`imprt` in another process, will re-activate
the context in the second process. Only a single instantiation of a given context may be
active at any one time; attempting to access this security context after calling
:meth:`export` will fail. This method can only be used on a valid context where
:attr:`is_transferable` is True.
:returns: a token which represents this security context
:rtype: bytes
|
gssapi/ctx.py
|
def export(self):
"""
This method deactivates the security context for the calling process and returns an
interprocess token which, when passed to :meth:`imprt` in another process, will re-activate
the context in the second process. Only a single instantiation of a given context may be
active at any one time; attempting to access this security context after calling
:meth:`export` will fail. This method can only be used on a valid context where
:attr:`is_transferable` is True.
:returns: a token which represents this security context
:rtype: bytes
"""
if not (self.flags & C.GSS_C_TRANS_FLAG):
raise GSSException("Context is not transferable.")
if not self._ctx:
raise GSSException("Can't export empty/invalid context.")
minor_status = ffi.new('OM_uint32[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
retval = C.gss_export_sec_context(
minor_status,
self._ctx,
output_token_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
exported_token = _buf_to_str(output_token_buffer[0])
# Set our context to a 'blank' context
self._ctx = ffi.new('gss_ctx_id_t[1]')
return exported_token
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
def export(self):
"""
This method deactivates the security context for the calling process and returns an
interprocess token which, when passed to :meth:`imprt` in another process, will re-activate
the context in the second process. Only a single instantiation of a given context may be
active at any one time; attempting to access this security context after calling
:meth:`export` will fail. This method can only be used on a valid context where
:attr:`is_transferable` is True.
:returns: a token which represents this security context
:rtype: bytes
"""
if not (self.flags & C.GSS_C_TRANS_FLAG):
raise GSSException("Context is not transferable.")
if not self._ctx:
raise GSSException("Can't export empty/invalid context.")
minor_status = ffi.new('OM_uint32[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
retval = C.gss_export_sec_context(
minor_status,
self._ctx,
output_token_buffer
)
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
exported_token = _buf_to_str(output_token_buffer[0])
# Set our context to a 'blank' context
self._ctx = ffi.new('gss_ctx_id_t[1]')
return exported_token
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
[
"This",
"method",
"deactivates",
"the",
"security",
"context",
"for",
"the",
"calling",
"process",
"and",
"returns",
"an",
"interprocess",
"token",
"which",
"when",
"passed",
"to",
":",
"meth",
":",
"imprt",
"in",
"another",
"process",
"will",
"re",
"-",
"activate",
"the",
"context",
"in",
"the",
"second",
"process",
".",
"Only",
"a",
"single",
"instantiation",
"of",
"a",
"given",
"context",
"may",
"be",
"active",
"at",
"any",
"one",
"time",
";",
"attempting",
"to",
"access",
"this",
"security",
"context",
"after",
"calling",
":",
"meth",
":",
"export",
"will",
"fail",
".",
"This",
"method",
"can",
"only",
"be",
"used",
"on",
"a",
"valid",
"context",
"where",
":",
"attr",
":",
"is_transferable",
"is",
"True",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L486-L523
|
[
"def",
"export",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_TRANS_FLAG",
")",
":",
"raise",
"GSSException",
"(",
"\"Context is not transferable.\"",
")",
"if",
"not",
"self",
".",
"_ctx",
":",
"raise",
"GSSException",
"(",
"\"Can't export empty/invalid context.\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"output_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"retval",
"=",
"C",
".",
"gss_export_sec_context",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
",",
"output_token_buffer",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"exported_token",
"=",
"_buf_to_str",
"(",
"output_token_buffer",
"[",
"0",
"]",
")",
"# Set our context to a 'blank' context",
"self",
".",
"_ctx",
"=",
"ffi",
".",
"new",
"(",
"'gss_ctx_id_t[1]'",
")",
"return",
"exported_token",
"finally",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_token_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.imprt
|
This is the corresponding method to :meth:`export`, used to import a saved context token
from another process into this one and construct a :class:`Context` object from it.
:param import_token: a token obtained from the :meth:`export` of another context
:type import_token: bytes
:returns: a Context object created from the imported token
:rtype: :class:`Context`
|
gssapi/ctx.py
|
def imprt(import_token):
"""
This is the corresponding method to :meth:`export`, used to import a saved context token
from another process into this one and construct a :class:`Context` object from it.
:param import_token: a token obtained from the :meth:`export` of another context
:type import_token: bytes
:returns: a Context object created from the imported token
:rtype: :class:`Context`
"""
minor_status = ffi.new('OM_uint32[1]')
import_token_buffer = ffi.new('gss_buffer_desc[1]')
import_token_buffer[0].length = len(import_token)
c_str_import_token = ffi.new('char[]', import_token)
import_token_buffer[0].value = c_str_import_token
new_context = ffi.new('gss_ctx_id_t[1]')
retval = C.gss_import_sec_context(
minor_status,
import_token_buffer,
new_context
)
try:
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
src_name = ffi.new('gss_name_t[1]')
target_name = ffi.new('gss_name_t[1]')
mech_type = ffi.new('gss_OID[1]')
flags = ffi.new('OM_uint32[1]')
locally_initiated = ffi.new('int[1]')
established = ffi.new('int[1]')
retval = C.gss_inquire_context(
minor_status,
new_context[0],
src_name,
target_name,
ffi.NULL, # lifetime_rec
mech_type,
flags,
locally_initiated,
established
)
src_name = Name(src_name)
target_name = Name(target_name)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
mech = OID(mech_type[0][0]) if mech_type[0] else None
if locally_initiated:
new_context_obj = InitContext(target_name, mech_type=mech)
else:
new_context_obj = AcceptContext()
new_context_obj.peer_name = src_name
new_context_obj.mech_type = mech
new_context_obj.flags = flags[0]
new_context_obj.established = bool(established[0])
new_context_obj._ctx = ffi.gc(new_context, _release_gss_ctx_id_t)
return new_context_obj
except:
if new_context[0]:
C.gss_delete_sec_context(
minor_status,
new_context,
ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
)
raise
|
def imprt(import_token):
"""
This is the corresponding method to :meth:`export`, used to import a saved context token
from another process into this one and construct a :class:`Context` object from it.
:param import_token: a token obtained from the :meth:`export` of another context
:type import_token: bytes
:returns: a Context object created from the imported token
:rtype: :class:`Context`
"""
minor_status = ffi.new('OM_uint32[1]')
import_token_buffer = ffi.new('gss_buffer_desc[1]')
import_token_buffer[0].length = len(import_token)
c_str_import_token = ffi.new('char[]', import_token)
import_token_buffer[0].value = c_str_import_token
new_context = ffi.new('gss_ctx_id_t[1]')
retval = C.gss_import_sec_context(
minor_status,
import_token_buffer,
new_context
)
try:
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
src_name = ffi.new('gss_name_t[1]')
target_name = ffi.new('gss_name_t[1]')
mech_type = ffi.new('gss_OID[1]')
flags = ffi.new('OM_uint32[1]')
locally_initiated = ffi.new('int[1]')
established = ffi.new('int[1]')
retval = C.gss_inquire_context(
minor_status,
new_context[0],
src_name,
target_name,
ffi.NULL, # lifetime_rec
mech_type,
flags,
locally_initiated,
established
)
src_name = Name(src_name)
target_name = Name(target_name)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
mech = OID(mech_type[0][0]) if mech_type[0] else None
if locally_initiated:
new_context_obj = InitContext(target_name, mech_type=mech)
else:
new_context_obj = AcceptContext()
new_context_obj.peer_name = src_name
new_context_obj.mech_type = mech
new_context_obj.flags = flags[0]
new_context_obj.established = bool(established[0])
new_context_obj._ctx = ffi.gc(new_context, _release_gss_ctx_id_t)
return new_context_obj
except:
if new_context[0]:
C.gss_delete_sec_context(
minor_status,
new_context,
ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
)
raise
|
[
"This",
"is",
"the",
"corresponding",
"method",
"to",
":",
"meth",
":",
"export",
"used",
"to",
"import",
"a",
"saved",
"context",
"token",
"from",
"another",
"process",
"into",
"this",
"one",
"and",
"construct",
"a",
":",
"class",
":",
"Context",
"object",
"from",
"it",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L526-L593
|
[
"def",
"imprt",
"(",
"import_token",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"import_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"import_token_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"import_token",
")",
"c_str_import_token",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"import_token",
")",
"import_token_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_import_token",
"new_context",
"=",
"ffi",
".",
"new",
"(",
"'gss_ctx_id_t[1]'",
")",
"retval",
"=",
"C",
".",
"gss_import_sec_context",
"(",
"minor_status",
",",
"import_token_buffer",
",",
"new_context",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"src_name",
"=",
"ffi",
".",
"new",
"(",
"'gss_name_t[1]'",
")",
"target_name",
"=",
"ffi",
".",
"new",
"(",
"'gss_name_t[1]'",
")",
"mech_type",
"=",
"ffi",
".",
"new",
"(",
"'gss_OID[1]'",
")",
"flags",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"locally_initiated",
"=",
"ffi",
".",
"new",
"(",
"'int[1]'",
")",
"established",
"=",
"ffi",
".",
"new",
"(",
"'int[1]'",
")",
"retval",
"=",
"C",
".",
"gss_inquire_context",
"(",
"minor_status",
",",
"new_context",
"[",
"0",
"]",
",",
"src_name",
",",
"target_name",
",",
"ffi",
".",
"NULL",
",",
"# lifetime_rec",
"mech_type",
",",
"flags",
",",
"locally_initiated",
",",
"established",
")",
"src_name",
"=",
"Name",
"(",
"src_name",
")",
"target_name",
"=",
"Name",
"(",
"target_name",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"mech",
"=",
"OID",
"(",
"mech_type",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"if",
"mech_type",
"[",
"0",
"]",
"else",
"None",
"if",
"locally_initiated",
":",
"new_context_obj",
"=",
"InitContext",
"(",
"target_name",
",",
"mech_type",
"=",
"mech",
")",
"else",
":",
"new_context_obj",
"=",
"AcceptContext",
"(",
")",
"new_context_obj",
".",
"peer_name",
"=",
"src_name",
"new_context_obj",
".",
"mech_type",
"=",
"mech",
"new_context_obj",
".",
"flags",
"=",
"flags",
"[",
"0",
"]",
"new_context_obj",
".",
"established",
"=",
"bool",
"(",
"established",
"[",
"0",
"]",
")",
"new_context_obj",
".",
"_ctx",
"=",
"ffi",
".",
"gc",
"(",
"new_context",
",",
"_release_gss_ctx_id_t",
")",
"return",
"new_context_obj",
"except",
":",
"if",
"new_context",
"[",
"0",
"]",
":",
"C",
".",
"gss_delete_sec_context",
"(",
"minor_status",
",",
"new_context",
",",
"ffi",
".",
"cast",
"(",
"'gss_buffer_t'",
",",
"C",
".",
"GSS_C_NO_BUFFER",
")",
")",
"raise"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.lifetime
|
The lifetime of the context in seconds (only valid after :meth:`step` has been called). If
the context does not have a time limit on its validity, this will be
:const:`gssapi.C_INDEFINITE`
|
gssapi/ctx.py
|
def lifetime(self):
"""
The lifetime of the context in seconds (only valid after :meth:`step` has been called). If
the context does not have a time limit on its validity, this will be
:const:`gssapi.C_INDEFINITE`
"""
minor_status = ffi.new('OM_uint32[1]')
lifetime_rec = ffi.new('OM_uint32[1]')
retval = C.gss_inquire_context(
minor_status,
self._ctx[0],
ffi.NULL, # src_name
ffi.NULL, # target_name
lifetime_rec,
ffi.NULL, # mech_type
ffi.NULL, # ctx_flags
ffi.NULL, # locally_initiated
ffi.NULL # established
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return lifetime_rec[0]
|
def lifetime(self):
"""
The lifetime of the context in seconds (only valid after :meth:`step` has been called). If
the context does not have a time limit on its validity, this will be
:const:`gssapi.C_INDEFINITE`
"""
minor_status = ffi.new('OM_uint32[1]')
lifetime_rec = ffi.new('OM_uint32[1]')
retval = C.gss_inquire_context(
minor_status,
self._ctx[0],
ffi.NULL, # src_name
ffi.NULL, # target_name
lifetime_rec,
ffi.NULL, # mech_type
ffi.NULL, # ctx_flags
ffi.NULL, # locally_initiated
ffi.NULL # established
)
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return lifetime_rec[0]
|
[
"The",
"lifetime",
"of",
"the",
"context",
"in",
"seconds",
"(",
"only",
"valid",
"after",
":",
"meth",
":",
"step",
"has",
"been",
"called",
")",
".",
"If",
"the",
"context",
"does",
"not",
"have",
"a",
"time",
"limit",
"on",
"its",
"validity",
"this",
"will",
"be",
":",
"const",
":",
"gssapi",
".",
"C_INDEFINITE"
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L596-L622
|
[
"def",
"lifetime",
"(",
"self",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"lifetime_rec",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"retval",
"=",
"C",
".",
"gss_inquire_context",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
"[",
"0",
"]",
",",
"ffi",
".",
"NULL",
",",
"# src_name",
"ffi",
".",
"NULL",
",",
"# target_name",
"lifetime_rec",
",",
"ffi",
".",
"NULL",
",",
"# mech_type",
"ffi",
".",
"NULL",
",",
"# ctx_flags",
"ffi",
".",
"NULL",
",",
"# locally_initiated",
"ffi",
".",
"NULL",
"# established",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"lifetime_rec",
"[",
"0",
"]"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Context.delete
|
Delete a security context. This method will delete the local data structures associated
with the specified security context, and may return an output token, which when passed to
:meth:`process_context_token` on the peer may instruct it to also delete its context.
RFC 2744 recommends that GSSAPI mechanisms do not emit any output token when they're
deleted, so this behaviour could be considered deprecated.
After this method is called, this security context will become invalid and should not be
used in any way.
:returns: An output token if one was emitted by the GSSAPI mechanism, otherwise an empty
bytestring.
:rtype: bytes
|
gssapi/ctx.py
|
def delete(self):
"""
Delete a security context. This method will delete the local data structures associated
with the specified security context, and may return an output token, which when passed to
:meth:`process_context_token` on the peer may instruct it to also delete its context.
RFC 2744 recommends that GSSAPI mechanisms do not emit any output token when they're
deleted, so this behaviour could be considered deprecated.
After this method is called, this security context will become invalid and should not be
used in any way.
:returns: An output token if one was emitted by the GSSAPI mechanism, otherwise an empty
bytestring.
:rtype: bytes
"""
if not self._ctx[0]:
raise GSSException("Can't delete invalid context")
output_token_buffer = ffi.new('gss_buffer_desc[1]')
minor_status = ffi.new('OM_uint32[1]')
retval = C.gss_delete_sec_context(
minor_status,
self._ctx,
output_token_buffer
)
self._ctx = ffi.new('gss_ctx_id_t[1]')
self._reset_flags()
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return _buf_to_str(output_token_buffer[0])
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
def delete(self):
"""
Delete a security context. This method will delete the local data structures associated
with the specified security context, and may return an output token, which when passed to
:meth:`process_context_token` on the peer may instruct it to also delete its context.
RFC 2744 recommends that GSSAPI mechanisms do not emit any output token when they're
deleted, so this behaviour could be considered deprecated.
After this method is called, this security context will become invalid and should not be
used in any way.
:returns: An output token if one was emitted by the GSSAPI mechanism, otherwise an empty
bytestring.
:rtype: bytes
"""
if not self._ctx[0]:
raise GSSException("Can't delete invalid context")
output_token_buffer = ffi.new('gss_buffer_desc[1]')
minor_status = ffi.new('OM_uint32[1]')
retval = C.gss_delete_sec_context(
minor_status,
self._ctx,
output_token_buffer
)
self._ctx = ffi.new('gss_ctx_id_t[1]')
self._reset_flags()
try:
if GSS_ERROR(retval):
if minor_status[0] and self.mech_type:
raise _exception_for_status(retval, minor_status[0], self.mech_type)
else:
raise _exception_for_status(retval, minor_status[0])
return _buf_to_str(output_token_buffer[0])
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
[
"Delete",
"a",
"security",
"context",
".",
"This",
"method",
"will",
"delete",
"the",
"local",
"data",
"structures",
"associated",
"with",
"the",
"specified",
"security",
"context",
"and",
"may",
"return",
"an",
"output",
"token",
"which",
"when",
"passed",
"to",
":",
"meth",
":",
"process_context_token",
"on",
"the",
"peer",
"may",
"instruct",
"it",
"to",
"also",
"delete",
"its",
"context",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L624-L662
|
[
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ctx",
"[",
"0",
"]",
":",
"raise",
"GSSException",
"(",
"\"Can't delete invalid context\"",
")",
"output_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"retval",
"=",
"C",
".",
"gss_delete_sec_context",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
",",
"output_token_buffer",
")",
"self",
".",
"_ctx",
"=",
"ffi",
".",
"new",
"(",
"'gss_ctx_id_t[1]'",
")",
"self",
".",
"_reset_flags",
"(",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"self",
".",
"mech_type",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"self",
".",
"mech_type",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"_buf_to_str",
"(",
"output_token_buffer",
"[",
"0",
"]",
")",
"finally",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_token_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
InitContext.step
|
Performs a step to establish the context as an initiator.
This method should be called in a loop and fed input tokens from the acceptor, and its
output tokens should be sent to the acceptor, until this context's :attr:`established`
attribute is True.
:param input_token: The input token from the acceptor (omit this param or pass None on
the first call).
:type input_token: bytes
:returns: either a byte string with the next token to send to the acceptor,
or None if there is no further token to send to the acceptor.
:raises: :exc:`~gssapi.error.GSSException` if there is an error establishing the context.
|
gssapi/ctx.py
|
def step(self, input_token=None):
"""Performs a step to establish the context as an initiator.
This method should be called in a loop and fed input tokens from the acceptor, and its
output tokens should be sent to the acceptor, until this context's :attr:`established`
attribute is True.
:param input_token: The input token from the acceptor (omit this param or pass None on
the first call).
:type input_token: bytes
:returns: either a byte string with the next token to send to the acceptor,
or None if there is no further token to send to the acceptor.
:raises: :exc:`~gssapi.error.GSSException` if there is an error establishing the context.
"""
minor_status = ffi.new('OM_uint32[1]')
if input_token:
input_token_buffer = ffi.new('gss_buffer_desc[1]')
input_token_buffer[0].length = len(input_token)
c_str_input_token = ffi.new('char[]', input_token)
input_token_buffer[0].value = c_str_input_token
else:
input_token_buffer = ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
if isinstance(self._desired_mech, OID):
desired_mech = ffi.addressof(self._desired_mech._oid)
else:
desired_mech = ffi.cast('gss_OID', C.GSS_C_NO_OID)
actual_mech = ffi.new('gss_OID[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
actual_flags = ffi.new('OM_uint32[1]')
actual_time = ffi.new('OM_uint32[1]')
if self._cred_object is not None:
cred = self._cred_object._cred[0]
else:
cred = ffi.cast('gss_cred_id_t', C.GSS_C_NO_CREDENTIAL)
retval = C.gss_init_sec_context(
minor_status,
cred,
self._ctx,
self.peer_name._name[0],
desired_mech,
self._req_flags,
self._time_req,
self._channel_bindings,
input_token_buffer,
actual_mech,
output_token_buffer,
actual_flags,
actual_time
)
try:
if output_token_buffer[0].length != 0:
out_token = _buf_to_str(output_token_buffer[0])
else:
out_token = None
if GSS_ERROR(retval):
if minor_status[0] and actual_mech[0]:
raise _exception_for_status(retval, minor_status[0], actual_mech[0], out_token)
else:
raise _exception_for_status(retval, minor_status[0], None, out_token)
self.established = not (retval & C.GSS_S_CONTINUE_NEEDED)
self.flags = actual_flags[0]
if actual_mech[0]:
self.mech_type = OID(actual_mech[0][0])
return out_token
except:
if self._ctx[0]:
C.gss_delete_sec_context(
minor_status,
self._ctx,
ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
)
self._reset_flags()
raise
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
def step(self, input_token=None):
"""Performs a step to establish the context as an initiator.
This method should be called in a loop and fed input tokens from the acceptor, and its
output tokens should be sent to the acceptor, until this context's :attr:`established`
attribute is True.
:param input_token: The input token from the acceptor (omit this param or pass None on
the first call).
:type input_token: bytes
:returns: either a byte string with the next token to send to the acceptor,
or None if there is no further token to send to the acceptor.
:raises: :exc:`~gssapi.error.GSSException` if there is an error establishing the context.
"""
minor_status = ffi.new('OM_uint32[1]')
if input_token:
input_token_buffer = ffi.new('gss_buffer_desc[1]')
input_token_buffer[0].length = len(input_token)
c_str_input_token = ffi.new('char[]', input_token)
input_token_buffer[0].value = c_str_input_token
else:
input_token_buffer = ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
if isinstance(self._desired_mech, OID):
desired_mech = ffi.addressof(self._desired_mech._oid)
else:
desired_mech = ffi.cast('gss_OID', C.GSS_C_NO_OID)
actual_mech = ffi.new('gss_OID[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
actual_flags = ffi.new('OM_uint32[1]')
actual_time = ffi.new('OM_uint32[1]')
if self._cred_object is not None:
cred = self._cred_object._cred[0]
else:
cred = ffi.cast('gss_cred_id_t', C.GSS_C_NO_CREDENTIAL)
retval = C.gss_init_sec_context(
minor_status,
cred,
self._ctx,
self.peer_name._name[0],
desired_mech,
self._req_flags,
self._time_req,
self._channel_bindings,
input_token_buffer,
actual_mech,
output_token_buffer,
actual_flags,
actual_time
)
try:
if output_token_buffer[0].length != 0:
out_token = _buf_to_str(output_token_buffer[0])
else:
out_token = None
if GSS_ERROR(retval):
if minor_status[0] and actual_mech[0]:
raise _exception_for_status(retval, minor_status[0], actual_mech[0], out_token)
else:
raise _exception_for_status(retval, minor_status[0], None, out_token)
self.established = not (retval & C.GSS_S_CONTINUE_NEEDED)
self.flags = actual_flags[0]
if actual_mech[0]:
self.mech_type = OID(actual_mech[0][0])
return out_token
except:
if self._ctx[0]:
C.gss_delete_sec_context(
minor_status,
self._ctx,
ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
)
self._reset_flags()
raise
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
|
[
"Performs",
"a",
"step",
"to",
"establish",
"the",
"context",
"as",
"an",
"initiator",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L725-L810
|
[
"def",
"step",
"(",
"self",
",",
"input_token",
"=",
"None",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"if",
"input_token",
":",
"input_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"input_token_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"input_token",
")",
"c_str_input_token",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"input_token",
")",
"input_token_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_input_token",
"else",
":",
"input_token_buffer",
"=",
"ffi",
".",
"cast",
"(",
"'gss_buffer_t'",
",",
"C",
".",
"GSS_C_NO_BUFFER",
")",
"if",
"isinstance",
"(",
"self",
".",
"_desired_mech",
",",
"OID",
")",
":",
"desired_mech",
"=",
"ffi",
".",
"addressof",
"(",
"self",
".",
"_desired_mech",
".",
"_oid",
")",
"else",
":",
"desired_mech",
"=",
"ffi",
".",
"cast",
"(",
"'gss_OID'",
",",
"C",
".",
"GSS_C_NO_OID",
")",
"actual_mech",
"=",
"ffi",
".",
"new",
"(",
"'gss_OID[1]'",
")",
"output_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"actual_flags",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"actual_time",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"if",
"self",
".",
"_cred_object",
"is",
"not",
"None",
":",
"cred",
"=",
"self",
".",
"_cred_object",
".",
"_cred",
"[",
"0",
"]",
"else",
":",
"cred",
"=",
"ffi",
".",
"cast",
"(",
"'gss_cred_id_t'",
",",
"C",
".",
"GSS_C_NO_CREDENTIAL",
")",
"retval",
"=",
"C",
".",
"gss_init_sec_context",
"(",
"minor_status",
",",
"cred",
",",
"self",
".",
"_ctx",
",",
"self",
".",
"peer_name",
".",
"_name",
"[",
"0",
"]",
",",
"desired_mech",
",",
"self",
".",
"_req_flags",
",",
"self",
".",
"_time_req",
",",
"self",
".",
"_channel_bindings",
",",
"input_token_buffer",
",",
"actual_mech",
",",
"output_token_buffer",
",",
"actual_flags",
",",
"actual_time",
")",
"try",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"out_token",
"=",
"_buf_to_str",
"(",
"output_token_buffer",
"[",
"0",
"]",
")",
"else",
":",
"out_token",
"=",
"None",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"actual_mech",
"[",
"0",
"]",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"actual_mech",
"[",
"0",
"]",
",",
"out_token",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"None",
",",
"out_token",
")",
"self",
".",
"established",
"=",
"not",
"(",
"retval",
"&",
"C",
".",
"GSS_S_CONTINUE_NEEDED",
")",
"self",
".",
"flags",
"=",
"actual_flags",
"[",
"0",
"]",
"if",
"actual_mech",
"[",
"0",
"]",
":",
"self",
".",
"mech_type",
"=",
"OID",
"(",
"actual_mech",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"return",
"out_token",
"except",
":",
"if",
"self",
".",
"_ctx",
"[",
"0",
"]",
":",
"C",
".",
"gss_delete_sec_context",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
",",
"ffi",
".",
"cast",
"(",
"'gss_buffer_t'",
",",
"C",
".",
"GSS_C_NO_BUFFER",
")",
")",
"self",
".",
"_reset_flags",
"(",
")",
"raise",
"finally",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_token_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
AcceptContext.step
|
Performs a step to establish the context as an acceptor.
This method should be called in a loop and fed input tokens from the initiator, and its
output tokens should be sent to the initiator, until this context's :attr:`established`
attribute is True.
:param input_token: The input token from the initiator (required).
:type input_token: bytes
:returns: either a byte string with the next token to send to the initiator,
or None if there is no further token to send to the initiator.
:raises: :exc:`~gssapi.error.GSSException` if there is an error establishing the context.
|
gssapi/ctx.py
|
def step(self, input_token):
"""Performs a step to establish the context as an acceptor.
This method should be called in a loop and fed input tokens from the initiator, and its
output tokens should be sent to the initiator, until this context's :attr:`established`
attribute is True.
:param input_token: The input token from the initiator (required).
:type input_token: bytes
:returns: either a byte string with the next token to send to the initiator,
or None if there is no further token to send to the initiator.
:raises: :exc:`~gssapi.error.GSSException` if there is an error establishing the context.
"""
minor_status = ffi.new('OM_uint32[1]')
input_token_buffer = ffi.new('gss_buffer_desc[1]')
input_token_buffer[0].length = len(input_token)
c_str_import_token = ffi.new('char[]', input_token)
input_token_buffer[0].value = c_str_import_token
mech_type = ffi.new('gss_OID[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
src_name_handle = ffi.new('gss_name_t[1]')
actual_flags = ffi.new('OM_uint32[1]')
time_rec = ffi.new('OM_uint32[1]')
delegated_cred_handle = ffi.new('gss_cred_id_t[1]')
if self._cred_object is not None:
cred = self._cred_object._cred[0]
else:
cred = ffi.cast('gss_cred_id_t', C.GSS_C_NO_CREDENTIAL)
retval = C.gss_accept_sec_context(
minor_status,
self._ctx,
cred,
input_token_buffer,
self._channel_bindings,
src_name_handle,
mech_type,
output_token_buffer,
actual_flags,
time_rec,
delegated_cred_handle
)
if src_name_handle[0]:
src_name = MechName(src_name_handle, mech_type[0]) # make sure src_name is GC'd
try:
if output_token_buffer[0].length != 0:
out_token = _buf_to_str(output_token_buffer[0])
else:
out_token = None
if GSS_ERROR(retval):
if minor_status[0] and mech_type[0]:
raise _exception_for_status(retval, minor_status[0], mech_type[0], out_token)
else:
raise _exception_for_status(retval, minor_status[0], None, out_token)
self.established = not (retval & C.GSS_S_CONTINUE_NEEDED)
self.flags = actual_flags[0]
if (self.flags & C.GSS_C_DELEG_FLAG):
self.delegated_cred = Credential(delegated_cred_handle)
if mech_type[0]:
self.mech_type = OID(mech_type[0][0])
if src_name_handle[0]:
src_name._mech_type = self.mech_type
self.peer_name = src_name
return out_token
except:
if self._ctx:
C.gss_delete_sec_context(
minor_status,
self._ctx,
ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
)
self._reset_flags()
raise
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
# if self.delegated_cred is present, it will handle gss_release_cred:
if delegated_cred_handle[0] and not self.delegated_cred:
C.gss_release_cred(minor_status, delegated_cred_handle)
|
def step(self, input_token):
"""Performs a step to establish the context as an acceptor.
This method should be called in a loop and fed input tokens from the initiator, and its
output tokens should be sent to the initiator, until this context's :attr:`established`
attribute is True.
:param input_token: The input token from the initiator (required).
:type input_token: bytes
:returns: either a byte string with the next token to send to the initiator,
or None if there is no further token to send to the initiator.
:raises: :exc:`~gssapi.error.GSSException` if there is an error establishing the context.
"""
minor_status = ffi.new('OM_uint32[1]')
input_token_buffer = ffi.new('gss_buffer_desc[1]')
input_token_buffer[0].length = len(input_token)
c_str_import_token = ffi.new('char[]', input_token)
input_token_buffer[0].value = c_str_import_token
mech_type = ffi.new('gss_OID[1]')
output_token_buffer = ffi.new('gss_buffer_desc[1]')
src_name_handle = ffi.new('gss_name_t[1]')
actual_flags = ffi.new('OM_uint32[1]')
time_rec = ffi.new('OM_uint32[1]')
delegated_cred_handle = ffi.new('gss_cred_id_t[1]')
if self._cred_object is not None:
cred = self._cred_object._cred[0]
else:
cred = ffi.cast('gss_cred_id_t', C.GSS_C_NO_CREDENTIAL)
retval = C.gss_accept_sec_context(
minor_status,
self._ctx,
cred,
input_token_buffer,
self._channel_bindings,
src_name_handle,
mech_type,
output_token_buffer,
actual_flags,
time_rec,
delegated_cred_handle
)
if src_name_handle[0]:
src_name = MechName(src_name_handle, mech_type[0]) # make sure src_name is GC'd
try:
if output_token_buffer[0].length != 0:
out_token = _buf_to_str(output_token_buffer[0])
else:
out_token = None
if GSS_ERROR(retval):
if minor_status[0] and mech_type[0]:
raise _exception_for_status(retval, minor_status[0], mech_type[0], out_token)
else:
raise _exception_for_status(retval, minor_status[0], None, out_token)
self.established = not (retval & C.GSS_S_CONTINUE_NEEDED)
self.flags = actual_flags[0]
if (self.flags & C.GSS_C_DELEG_FLAG):
self.delegated_cred = Credential(delegated_cred_handle)
if mech_type[0]:
self.mech_type = OID(mech_type[0][0])
if src_name_handle[0]:
src_name._mech_type = self.mech_type
self.peer_name = src_name
return out_token
except:
if self._ctx:
C.gss_delete_sec_context(
minor_status,
self._ctx,
ffi.cast('gss_buffer_t', C.GSS_C_NO_BUFFER)
)
self._reset_flags()
raise
finally:
if output_token_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_token_buffer)
# if self.delegated_cred is present, it will handle gss_release_cred:
if delegated_cred_handle[0] and not self.delegated_cred:
C.gss_release_cred(minor_status, delegated_cred_handle)
|
[
"Performs",
"a",
"step",
"to",
"establish",
"the",
"context",
"as",
"an",
"acceptor",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/ctx.py#L865-L951
|
[
"def",
"step",
"(",
"self",
",",
"input_token",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"input_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"input_token_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"input_token",
")",
"c_str_import_token",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"input_token",
")",
"input_token_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_import_token",
"mech_type",
"=",
"ffi",
".",
"new",
"(",
"'gss_OID[1]'",
")",
"output_token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"src_name_handle",
"=",
"ffi",
".",
"new",
"(",
"'gss_name_t[1]'",
")",
"actual_flags",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"time_rec",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"delegated_cred_handle",
"=",
"ffi",
".",
"new",
"(",
"'gss_cred_id_t[1]'",
")",
"if",
"self",
".",
"_cred_object",
"is",
"not",
"None",
":",
"cred",
"=",
"self",
".",
"_cred_object",
".",
"_cred",
"[",
"0",
"]",
"else",
":",
"cred",
"=",
"ffi",
".",
"cast",
"(",
"'gss_cred_id_t'",
",",
"C",
".",
"GSS_C_NO_CREDENTIAL",
")",
"retval",
"=",
"C",
".",
"gss_accept_sec_context",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
",",
"cred",
",",
"input_token_buffer",
",",
"self",
".",
"_channel_bindings",
",",
"src_name_handle",
",",
"mech_type",
",",
"output_token_buffer",
",",
"actual_flags",
",",
"time_rec",
",",
"delegated_cred_handle",
")",
"if",
"src_name_handle",
"[",
"0",
"]",
":",
"src_name",
"=",
"MechName",
"(",
"src_name_handle",
",",
"mech_type",
"[",
"0",
"]",
")",
"# make sure src_name is GC'd",
"try",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"out_token",
"=",
"_buf_to_str",
"(",
"output_token_buffer",
"[",
"0",
"]",
")",
"else",
":",
"out_token",
"=",
"None",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"minor_status",
"[",
"0",
"]",
"and",
"mech_type",
"[",
"0",
"]",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"mech_type",
"[",
"0",
"]",
",",
"out_token",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"None",
",",
"out_token",
")",
"self",
".",
"established",
"=",
"not",
"(",
"retval",
"&",
"C",
".",
"GSS_S_CONTINUE_NEEDED",
")",
"self",
".",
"flags",
"=",
"actual_flags",
"[",
"0",
"]",
"if",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_DELEG_FLAG",
")",
":",
"self",
".",
"delegated_cred",
"=",
"Credential",
"(",
"delegated_cred_handle",
")",
"if",
"mech_type",
"[",
"0",
"]",
":",
"self",
".",
"mech_type",
"=",
"OID",
"(",
"mech_type",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"if",
"src_name_handle",
"[",
"0",
"]",
":",
"src_name",
".",
"_mech_type",
"=",
"self",
".",
"mech_type",
"self",
".",
"peer_name",
"=",
"src_name",
"return",
"out_token",
"except",
":",
"if",
"self",
".",
"_ctx",
":",
"C",
".",
"gss_delete_sec_context",
"(",
"minor_status",
",",
"self",
".",
"_ctx",
",",
"ffi",
".",
"cast",
"(",
"'gss_buffer_t'",
",",
"C",
".",
"GSS_C_NO_BUFFER",
")",
")",
"self",
".",
"_reset_flags",
"(",
")",
"raise",
"finally",
":",
"if",
"output_token_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_token_buffer",
")",
"# if self.delegated_cred is present, it will handle gss_release_cred:",
"if",
"delegated_cred_handle",
"[",
"0",
"]",
"and",
"not",
"self",
".",
"delegated_cred",
":",
"C",
".",
"gss_release_cred",
"(",
"minor_status",
",",
"delegated_cred_handle",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Credential.mechs
|
The set of mechanisms supported by the credential.
:type: :class:`~gssapi.oids.OIDSet`
|
gssapi/creds.py
|
def mechs(self):
"""
The set of mechanisms supported by the credential.
:type: :class:`~gssapi.oids.OIDSet`
"""
if not self._mechs:
self._mechs = self._inquire(False, False, False, True)[3]
return self._mechs
|
def mechs(self):
"""
The set of mechanisms supported by the credential.
:type: :class:`~gssapi.oids.OIDSet`
"""
if not self._mechs:
self._mechs = self._inquire(False, False, False, True)[3]
return self._mechs
|
[
"The",
"set",
"of",
"mechanisms",
"supported",
"by",
"the",
"credential",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/creds.py#L218-L226
|
[
"def",
"mechs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_mechs",
":",
"self",
".",
"_mechs",
"=",
"self",
".",
"_inquire",
"(",
"False",
",",
"False",
",",
"False",
",",
"True",
")",
"[",
"3",
"]",
"return",
"self",
".",
"_mechs"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Credential.export
|
Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The serialized token representation of this credential.
:rtype: bytes
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with exporting the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_export_cred`` C function.
|
gssapi/creds.py
|
def export(self):
"""
Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The serialized token representation of this credential.
:rtype: bytes
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with exporting the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_export_cred`` C function.
"""
if not hasattr(C, 'gss_export_cred'):
raise NotImplementedError("The GSSAPI implementation does not support gss_export_cred")
minor_status = ffi.new('OM_uint32[1]')
output_buffer = ffi.new('gss_buffer_desc[1]')
retval = C.gss_export_cred(minor_status, self._cred[0], output_buffer)
try:
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return _buf_to_str(output_buffer[0])
finally:
if output_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_buffer)
|
def export(self):
"""
Serializes this credential into a byte string, which can be passed to :meth:`imprt` in
another process in order to deserialize the byte string back into a credential. Exporting
a credential does not destroy it.
:returns: The serialized token representation of this credential.
:rtype: bytes
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with exporting the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_export_cred`` C function.
"""
if not hasattr(C, 'gss_export_cred'):
raise NotImplementedError("The GSSAPI implementation does not support gss_export_cred")
minor_status = ffi.new('OM_uint32[1]')
output_buffer = ffi.new('gss_buffer_desc[1]')
retval = C.gss_export_cred(minor_status, self._cred[0], output_buffer)
try:
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return _buf_to_str(output_buffer[0])
finally:
if output_buffer[0].length != 0:
C.gss_release_buffer(minor_status, output_buffer)
|
[
"Serializes",
"this",
"credential",
"into",
"a",
"byte",
"string",
"which",
"can",
"be",
"passed",
"to",
":",
"meth",
":",
"imprt",
"in",
"another",
"process",
"in",
"order",
"to",
"deserialize",
"the",
"byte",
"string",
"back",
"into",
"a",
"credential",
".",
"Exporting",
"a",
"credential",
"does",
"not",
"destroy",
"it",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/creds.py#L266-L293
|
[
"def",
"export",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"C",
",",
"'gss_export_cred'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"The GSSAPI implementation does not support gss_export_cred\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"output_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"retval",
"=",
"C",
".",
"gss_export_cred",
"(",
"minor_status",
",",
"self",
".",
"_cred",
"[",
"0",
"]",
",",
"output_buffer",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"_buf_to_str",
"(",
"output_buffer",
"[",
"0",
"]",
")",
"finally",
":",
"if",
"output_buffer",
"[",
"0",
"]",
".",
"length",
"!=",
"0",
":",
"C",
".",
"gss_release_buffer",
"(",
"minor_status",
",",
"output_buffer",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Credential.imprt
|
Deserializes a byte string token into a :class:`Credential` object. The token must have
previously been exported by the same GSSAPI implementation as is being used to import it.
:param token: A token previously obtained from the :meth:`export` of another
:class:`Credential` object.
:type token: bytes
:returns: A :class:`Credential` object constructed from the token.
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with importing the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_import_cred`` C function.
|
gssapi/creds.py
|
def imprt(cls, token):
"""
Deserializes a byte string token into a :class:`Credential` object. The token must have
previously been exported by the same GSSAPI implementation as is being used to import it.
:param token: A token previously obtained from the :meth:`export` of another
:class:`Credential` object.
:type token: bytes
:returns: A :class:`Credential` object constructed from the token.
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with importing the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_import_cred`` C function.
"""
if not hasattr(C, 'gss_import_cred'):
raise NotImplementedError("The GSSAPI implementation does not support gss_import_cred")
minor_status = ffi.new('OM_uint32[1]')
token_buffer = ffi.new('gss_buffer_desc[1]')
token_buffer[0].length = len(token)
c_str_token = ffi.new('char[]', token)
token_buffer[0].value = c_str_token
imported_cred = ffi.new('gss_cred_id_t[1]')
retval = C.gss_import_cred(minor_status, token_buffer, imported_cred)
try:
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return cls(imported_cred)
except:
_release_gss_cred_id_t(imported_cred)
raise
|
def imprt(cls, token):
"""
Deserializes a byte string token into a :class:`Credential` object. The token must have
previously been exported by the same GSSAPI implementation as is being used to import it.
:param token: A token previously obtained from the :meth:`export` of another
:class:`Credential` object.
:type token: bytes
:returns: A :class:`Credential` object constructed from the token.
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with importing the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_import_cred`` C function.
"""
if not hasattr(C, 'gss_import_cred'):
raise NotImplementedError("The GSSAPI implementation does not support gss_import_cred")
minor_status = ffi.new('OM_uint32[1]')
token_buffer = ffi.new('gss_buffer_desc[1]')
token_buffer[0].length = len(token)
c_str_token = ffi.new('char[]', token)
token_buffer[0].value = c_str_token
imported_cred = ffi.new('gss_cred_id_t[1]')
retval = C.gss_import_cred(minor_status, token_buffer, imported_cred)
try:
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return cls(imported_cred)
except:
_release_gss_cred_id_t(imported_cred)
raise
|
[
"Deserializes",
"a",
"byte",
"string",
"token",
"into",
"a",
":",
"class",
":",
"Credential",
"object",
".",
"The",
"token",
"must",
"have",
"previously",
"been",
"exported",
"by",
"the",
"same",
"GSSAPI",
"implementation",
"as",
"is",
"being",
"used",
"to",
"import",
"it",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/creds.py#L296-L331
|
[
"def",
"imprt",
"(",
"cls",
",",
"token",
")",
":",
"if",
"not",
"hasattr",
"(",
"C",
",",
"'gss_import_cred'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"The GSSAPI implementation does not support gss_import_cred\"",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"token_buffer",
"=",
"ffi",
".",
"new",
"(",
"'gss_buffer_desc[1]'",
")",
"token_buffer",
"[",
"0",
"]",
".",
"length",
"=",
"len",
"(",
"token",
")",
"c_str_token",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"token",
")",
"token_buffer",
"[",
"0",
"]",
".",
"value",
"=",
"c_str_token",
"imported_cred",
"=",
"ffi",
".",
"new",
"(",
"'gss_cred_id_t[1]'",
")",
"retval",
"=",
"C",
".",
"gss_import_cred",
"(",
"minor_status",
",",
"token_buffer",
",",
"imported_cred",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"cls",
"(",
"imported_cred",
")",
"except",
":",
"_release_gss_cred_id_t",
"(",
"imported_cred",
")",
"raise"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
Credential.store
|
Stores this credential into a 'credential store'. It can either store this credential in
the default credential store, or into a specific credential store specified by a set of
mechanism-specific key-value pairs. The former method of operation requires that the
underlying GSSAPI implementation supports the ``gss_store_cred`` C function, the latter
method requires support for the ``gss_store_cred_into`` C function.
:param usage: Optional parameter specifying whether to store the initiator, acceptor, or
both usages of this credential. Defaults to the value of this credential's
:attr:`usage` property.
:type usage: One of :data:`~gssapi.C_INITIATE`, :data:`~gssapi.C_ACCEPT` or
:data:`~gssapi.C_BOTH`
:param mech: Optional parameter specifying a single mechanism to store the credential
element for. If not supplied, all mechanisms' elements in this credential will be
stored.
:type mech: :class:`~gssapi.oids.OID`
:param overwrite: If True, indicates that any credential for the same principal in the
credential store should be overwritten with this credential.
:type overwrite: bool
:param default: If True, this credential should be made available as the default
credential when stored, for acquisition when no `desired_name` parameter is passed
to :class:`Credential` or for use when no credential is passed to
:class:`~gssapi.ctx.InitContext` or :class:`~gssapi.ctx.AcceptContext`. This is only
an advisory parameter to the GSSAPI implementation.
:type default: bool
:param cred_store: Optional dict or list of (key, value) pairs indicating the credential
store to use. The interpretation of these values will be mechanism-specific.
:type cred_store: dict, or list of (str, str)
:returns: A pair of values indicating the set of mechanism OIDs for which credential
elements were successfully stored, and the usage of the credential that was stored.
:rtype: tuple(:class:`~gssapi.oids.OIDSet`, int)
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with storing the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_store_cred`` or ``gss_store_cred_into`` C functions.
|
gssapi/creds.py
|
def store(self, usage=None, mech=None, overwrite=False, default=False, cred_store=None):
"""
Stores this credential into a 'credential store'. It can either store this credential in
the default credential store, or into a specific credential store specified by a set of
mechanism-specific key-value pairs. The former method of operation requires that the
underlying GSSAPI implementation supports the ``gss_store_cred`` C function, the latter
method requires support for the ``gss_store_cred_into`` C function.
:param usage: Optional parameter specifying whether to store the initiator, acceptor, or
both usages of this credential. Defaults to the value of this credential's
:attr:`usage` property.
:type usage: One of :data:`~gssapi.C_INITIATE`, :data:`~gssapi.C_ACCEPT` or
:data:`~gssapi.C_BOTH`
:param mech: Optional parameter specifying a single mechanism to store the credential
element for. If not supplied, all mechanisms' elements in this credential will be
stored.
:type mech: :class:`~gssapi.oids.OID`
:param overwrite: If True, indicates that any credential for the same principal in the
credential store should be overwritten with this credential.
:type overwrite: bool
:param default: If True, this credential should be made available as the default
credential when stored, for acquisition when no `desired_name` parameter is passed
to :class:`Credential` or for use when no credential is passed to
:class:`~gssapi.ctx.InitContext` or :class:`~gssapi.ctx.AcceptContext`. This is only
an advisory parameter to the GSSAPI implementation.
:type default: bool
:param cred_store: Optional dict or list of (key, value) pairs indicating the credential
store to use. The interpretation of these values will be mechanism-specific.
:type cred_store: dict, or list of (str, str)
:returns: A pair of values indicating the set of mechanism OIDs for which credential
elements were successfully stored, and the usage of the credential that was stored.
:rtype: tuple(:class:`~gssapi.oids.OIDSet`, int)
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with storing the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_store_cred`` or ``gss_store_cred_into`` C functions.
"""
if usage is None:
usage = self.usage
if isinstance(mech, OID):
oid_ptr = ffi.addressof(mech._oid)
else:
oid_ptr = ffi.cast('gss_OID', C.GSS_C_NO_OID)
minor_status = ffi.new('OM_uint32[1]')
elements_stored = ffi.new('gss_OID_set[1]')
usage_stored = ffi.new('gss_cred_usage_t[1]')
if cred_store is None:
if not hasattr(C, 'gss_store_cred'):
raise NotImplementedError("The GSSAPI implementation does not support "
"gss_store_cred")
retval = C.gss_store_cred(
minor_status,
self._cred[0],
ffi.cast('gss_cred_usage_t', usage),
oid_ptr,
ffi.cast('OM_uint32', overwrite),
ffi.cast('OM_uint32', default),
elements_stored,
usage_stored
)
else:
if not hasattr(C, 'gss_store_cred_into'):
raise NotImplementedError("The GSSAPI implementation does not support "
"gss_store_cred_into")
c_strings, elements, cred_store_kv_set = _make_kv_set(cred_store)
retval = C.gss_store_cred_into(
minor_status,
self._cred[0],
ffi.cast('gss_cred_usage_t', usage),
oid_ptr,
ffi.cast('OM_uint32', overwrite),
ffi.cast('OM_uint32', default),
cred_store_kv_set,
elements_stored,
usage_stored
)
try:
if GSS_ERROR(retval):
if oid_ptr:
raise _exception_for_status(retval, minor_status[0], oid_ptr)
else:
raise _exception_for_status(retval, minor_status[0])
except:
if elements_stored[0]:
C.gss_release_oid_set(minor_status, elements_stored)
raise
return (OIDSet(elements_stored), usage_stored[0])
|
def store(self, usage=None, mech=None, overwrite=False, default=False, cred_store=None):
"""
Stores this credential into a 'credential store'. It can either store this credential in
the default credential store, or into a specific credential store specified by a set of
mechanism-specific key-value pairs. The former method of operation requires that the
underlying GSSAPI implementation supports the ``gss_store_cred`` C function, the latter
method requires support for the ``gss_store_cred_into`` C function.
:param usage: Optional parameter specifying whether to store the initiator, acceptor, or
both usages of this credential. Defaults to the value of this credential's
:attr:`usage` property.
:type usage: One of :data:`~gssapi.C_INITIATE`, :data:`~gssapi.C_ACCEPT` or
:data:`~gssapi.C_BOTH`
:param mech: Optional parameter specifying a single mechanism to store the credential
element for. If not supplied, all mechanisms' elements in this credential will be
stored.
:type mech: :class:`~gssapi.oids.OID`
:param overwrite: If True, indicates that any credential for the same principal in the
credential store should be overwritten with this credential.
:type overwrite: bool
:param default: If True, this credential should be made available as the default
credential when stored, for acquisition when no `desired_name` parameter is passed
to :class:`Credential` or for use when no credential is passed to
:class:`~gssapi.ctx.InitContext` or :class:`~gssapi.ctx.AcceptContext`. This is only
an advisory parameter to the GSSAPI implementation.
:type default: bool
:param cred_store: Optional dict or list of (key, value) pairs indicating the credential
store to use. The interpretation of these values will be mechanism-specific.
:type cred_store: dict, or list of (str, str)
:returns: A pair of values indicating the set of mechanism OIDs for which credential
elements were successfully stored, and the usage of the credential that was stored.
:rtype: tuple(:class:`~gssapi.oids.OIDSet`, int)
:raises: :exc:`~gssapi.error.GSSException` if there is a problem with storing the
credential.
:exc:`NotImplementedError` if the underlying GSSAPI implementation does not
support the ``gss_store_cred`` or ``gss_store_cred_into`` C functions.
"""
if usage is None:
usage = self.usage
if isinstance(mech, OID):
oid_ptr = ffi.addressof(mech._oid)
else:
oid_ptr = ffi.cast('gss_OID', C.GSS_C_NO_OID)
minor_status = ffi.new('OM_uint32[1]')
elements_stored = ffi.new('gss_OID_set[1]')
usage_stored = ffi.new('gss_cred_usage_t[1]')
if cred_store is None:
if not hasattr(C, 'gss_store_cred'):
raise NotImplementedError("The GSSAPI implementation does not support "
"gss_store_cred")
retval = C.gss_store_cred(
minor_status,
self._cred[0],
ffi.cast('gss_cred_usage_t', usage),
oid_ptr,
ffi.cast('OM_uint32', overwrite),
ffi.cast('OM_uint32', default),
elements_stored,
usage_stored
)
else:
if not hasattr(C, 'gss_store_cred_into'):
raise NotImplementedError("The GSSAPI implementation does not support "
"gss_store_cred_into")
c_strings, elements, cred_store_kv_set = _make_kv_set(cred_store)
retval = C.gss_store_cred_into(
minor_status,
self._cred[0],
ffi.cast('gss_cred_usage_t', usage),
oid_ptr,
ffi.cast('OM_uint32', overwrite),
ffi.cast('OM_uint32', default),
cred_store_kv_set,
elements_stored,
usage_stored
)
try:
if GSS_ERROR(retval):
if oid_ptr:
raise _exception_for_status(retval, minor_status[0], oid_ptr)
else:
raise _exception_for_status(retval, minor_status[0])
except:
if elements_stored[0]:
C.gss_release_oid_set(minor_status, elements_stored)
raise
return (OIDSet(elements_stored), usage_stored[0])
|
[
"Stores",
"this",
"credential",
"into",
"a",
"credential",
"store",
".",
"It",
"can",
"either",
"store",
"this",
"credential",
"in",
"the",
"default",
"credential",
"store",
"or",
"into",
"a",
"specific",
"credential",
"store",
"specified",
"by",
"a",
"set",
"of",
"mechanism",
"-",
"specific",
"key",
"-",
"value",
"pairs",
".",
"The",
"former",
"method",
"of",
"operation",
"requires",
"that",
"the",
"underlying",
"GSSAPI",
"implementation",
"supports",
"the",
"gss_store_cred",
"C",
"function",
"the",
"latter",
"method",
"requires",
"support",
"for",
"the",
"gss_store_cred_into",
"C",
"function",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/creds.py#L333-L426
|
[
"def",
"store",
"(",
"self",
",",
"usage",
"=",
"None",
",",
"mech",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"default",
"=",
"False",
",",
"cred_store",
"=",
"None",
")",
":",
"if",
"usage",
"is",
"None",
":",
"usage",
"=",
"self",
".",
"usage",
"if",
"isinstance",
"(",
"mech",
",",
"OID",
")",
":",
"oid_ptr",
"=",
"ffi",
".",
"addressof",
"(",
"mech",
".",
"_oid",
")",
"else",
":",
"oid_ptr",
"=",
"ffi",
".",
"cast",
"(",
"'gss_OID'",
",",
"C",
".",
"GSS_C_NO_OID",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"elements_stored",
"=",
"ffi",
".",
"new",
"(",
"'gss_OID_set[1]'",
")",
"usage_stored",
"=",
"ffi",
".",
"new",
"(",
"'gss_cred_usage_t[1]'",
")",
"if",
"cred_store",
"is",
"None",
":",
"if",
"not",
"hasattr",
"(",
"C",
",",
"'gss_store_cred'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"The GSSAPI implementation does not support \"",
"\"gss_store_cred\"",
")",
"retval",
"=",
"C",
".",
"gss_store_cred",
"(",
"minor_status",
",",
"self",
".",
"_cred",
"[",
"0",
"]",
",",
"ffi",
".",
"cast",
"(",
"'gss_cred_usage_t'",
",",
"usage",
")",
",",
"oid_ptr",
",",
"ffi",
".",
"cast",
"(",
"'OM_uint32'",
",",
"overwrite",
")",
",",
"ffi",
".",
"cast",
"(",
"'OM_uint32'",
",",
"default",
")",
",",
"elements_stored",
",",
"usage_stored",
")",
"else",
":",
"if",
"not",
"hasattr",
"(",
"C",
",",
"'gss_store_cred_into'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"The GSSAPI implementation does not support \"",
"\"gss_store_cred_into\"",
")",
"c_strings",
",",
"elements",
",",
"cred_store_kv_set",
"=",
"_make_kv_set",
"(",
"cred_store",
")",
"retval",
"=",
"C",
".",
"gss_store_cred_into",
"(",
"minor_status",
",",
"self",
".",
"_cred",
"[",
"0",
"]",
",",
"ffi",
".",
"cast",
"(",
"'gss_cred_usage_t'",
",",
"usage",
")",
",",
"oid_ptr",
",",
"ffi",
".",
"cast",
"(",
"'OM_uint32'",
",",
"overwrite",
")",
",",
"ffi",
".",
"cast",
"(",
"'OM_uint32'",
",",
"default",
")",
",",
"cred_store_kv_set",
",",
"elements_stored",
",",
"usage_stored",
")",
"try",
":",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"if",
"oid_ptr",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
",",
"oid_ptr",
")",
"else",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"except",
":",
"if",
"elements_stored",
"[",
"0",
"]",
":",
"C",
".",
"gss_release_oid_set",
"(",
"minor_status",
",",
"elements_stored",
")",
"raise",
"return",
"(",
"OIDSet",
"(",
"elements_stored",
")",
",",
"usage_stored",
"[",
"0",
"]",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
get_all_mechs
|
Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI
implementation.
|
gssapi/oids.py
|
def get_all_mechs():
"""
Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI
implementation.
"""
minor_status = ffi.new('OM_uint32[1]')
mech_set = ffi.new('gss_OID_set[1]')
try:
retval = C.gss_indicate_mechs(minor_status, mech_set)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
except:
_release_OID_set(mech_set)
raise
return OIDSet(oid_set=mech_set)
|
def get_all_mechs():
"""
Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI
implementation.
"""
minor_status = ffi.new('OM_uint32[1]')
mech_set = ffi.new('gss_OID_set[1]')
try:
retval = C.gss_indicate_mechs(minor_status, mech_set)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
except:
_release_OID_set(mech_set)
raise
return OIDSet(oid_set=mech_set)
|
[
"Return",
"an",
":",
"class",
":",
"OIDSet",
"of",
"all",
"the",
"mechanisms",
"supported",
"by",
"the",
"underlying",
"GSSAPI",
"implementation",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/oids.py#L17-L31
|
[
"def",
"get_all_mechs",
"(",
")",
":",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"mech_set",
"=",
"ffi",
".",
"new",
"(",
"'gss_OID_set[1]'",
")",
"try",
":",
"retval",
"=",
"C",
".",
"gss_indicate_mechs",
"(",
"minor_status",
",",
"mech_set",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"except",
":",
"_release_OID_set",
"(",
"mech_set",
")",
"raise",
"return",
"OIDSet",
"(",
"oid_set",
"=",
"mech_set",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
OID.mech_from_string
|
Takes a string form of a mechanism OID, in dot-separated: "1.2.840.113554.1.2.2" or numeric
ASN.1: "{1 2 840 113554 1 2 2}" notation, and returns an :class:`OID` object representing
the mechanism, which can be passed to other GSSAPI methods.
:param input_string: a string representing the desired mechanism OID.
:returns: the mechanism OID.
:rtype: :class:`OID`
:raises: ValueError if the the input string is ill-formatted.
:raises: KeyError if the mechanism identified by the string is not supported by the
underlying GSSAPI implementation.
|
gssapi/oids.py
|
def mech_from_string(input_string):
"""
Takes a string form of a mechanism OID, in dot-separated: "1.2.840.113554.1.2.2" or numeric
ASN.1: "{1 2 840 113554 1 2 2}" notation, and returns an :class:`OID` object representing
the mechanism, which can be passed to other GSSAPI methods.
:param input_string: a string representing the desired mechanism OID.
:returns: the mechanism OID.
:rtype: :class:`OID`
:raises: ValueError if the the input string is ill-formatted.
:raises: KeyError if the mechanism identified by the string is not supported by the
underlying GSSAPI implementation.
"""
if not re.match(r'^\d+(\.\d+)*$', input_string):
if re.match(r'^\{\d+( \d+)*\}$', input_string):
input_string = ".".join(input_string[1:-1].split())
else:
raise ValueError(input_string)
for mech in get_all_mechs():
if input_string == str(mech):
return mech
raise KeyError("Unknown mechanism: {0}".format(input_string))
|
def mech_from_string(input_string):
"""
Takes a string form of a mechanism OID, in dot-separated: "1.2.840.113554.1.2.2" or numeric
ASN.1: "{1 2 840 113554 1 2 2}" notation, and returns an :class:`OID` object representing
the mechanism, which can be passed to other GSSAPI methods.
:param input_string: a string representing the desired mechanism OID.
:returns: the mechanism OID.
:rtype: :class:`OID`
:raises: ValueError if the the input string is ill-formatted.
:raises: KeyError if the mechanism identified by the string is not supported by the
underlying GSSAPI implementation.
"""
if not re.match(r'^\d+(\.\d+)*$', input_string):
if re.match(r'^\{\d+( \d+)*\}$', input_string):
input_string = ".".join(input_string[1:-1].split())
else:
raise ValueError(input_string)
for mech in get_all_mechs():
if input_string == str(mech):
return mech
raise KeyError("Unknown mechanism: {0}".format(input_string))
|
[
"Takes",
"a",
"string",
"form",
"of",
"a",
"mechanism",
"OID",
"in",
"dot",
"-",
"separated",
":",
"1",
".",
"2",
".",
"840",
".",
"113554",
".",
"1",
".",
"2",
".",
"2",
"or",
"numeric",
"ASN",
".",
"1",
":",
"{",
"1",
"2",
"840",
"113554",
"1",
"2",
"2",
"}",
"notation",
"and",
"returns",
"an",
":",
"class",
":",
"OID",
"object",
"representing",
"the",
"mechanism",
"which",
"can",
"be",
"passed",
"to",
"other",
"GSSAPI",
"methods",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/oids.py#L70-L91
|
[
"def",
"mech_from_string",
"(",
"input_string",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"r'^\\d+(\\.\\d+)*$'",
",",
"input_string",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'^\\{\\d+( \\d+)*\\}$'",
",",
"input_string",
")",
":",
"input_string",
"=",
"\".\"",
".",
"join",
"(",
"input_string",
"[",
"1",
":",
"-",
"1",
"]",
".",
"split",
"(",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"input_string",
")",
"for",
"mech",
"in",
"get_all_mechs",
"(",
")",
":",
"if",
"input_string",
"==",
"str",
"(",
"mech",
")",
":",
"return",
"mech",
"raise",
"KeyError",
"(",
"\"Unknown mechanism: {0}\"",
".",
"format",
"(",
"input_string",
")",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
OIDSet.singleton_set
|
Factory function to create a new :class:`OIDSet` with a single member.
:param single_oid: the OID to use as a member of the new set
:type single_oid: :class:`OID`
:returns: an OID set with the OID passed in as the only member
:rtype: :class:`OIDSet`
|
gssapi/oids.py
|
def singleton_set(cls, single_oid):
"""
Factory function to create a new :class:`OIDSet` with a single member.
:param single_oid: the OID to use as a member of the new set
:type single_oid: :class:`OID`
:returns: an OID set with the OID passed in as the only member
:rtype: :class:`OIDSet`
"""
new_set = cls()
oid_ptr = None
if isinstance(single_oid, OID):
oid_ptr = ffi.addressof(single_oid._oid)
elif isinstance(single_oid, ffi.CData):
if ffi.typeof(single_oid) == ffi.typeof('gss_OID_desc'):
oid_ptr = ffi.addressof(single_oid)
elif ffi.typeof(single_oid) == ffi.typeof('gss_OID'):
oid_ptr = single_oid
if oid_ptr is None:
raise TypeError("Expected a gssapi.oids.OID, got " + str(type(single_oid)))
minor_status = ffi.new('OM_uint32[1]')
retval = C.gss_add_oid_set_member(minor_status, oid_ptr, new_set._oid_set)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return new_set
|
def singleton_set(cls, single_oid):
"""
Factory function to create a new :class:`OIDSet` with a single member.
:param single_oid: the OID to use as a member of the new set
:type single_oid: :class:`OID`
:returns: an OID set with the OID passed in as the only member
:rtype: :class:`OIDSet`
"""
new_set = cls()
oid_ptr = None
if isinstance(single_oid, OID):
oid_ptr = ffi.addressof(single_oid._oid)
elif isinstance(single_oid, ffi.CData):
if ffi.typeof(single_oid) == ffi.typeof('gss_OID_desc'):
oid_ptr = ffi.addressof(single_oid)
elif ffi.typeof(single_oid) == ffi.typeof('gss_OID'):
oid_ptr = single_oid
if oid_ptr is None:
raise TypeError("Expected a gssapi.oids.OID, got " + str(type(single_oid)))
minor_status = ffi.new('OM_uint32[1]')
retval = C.gss_add_oid_set_member(minor_status, oid_ptr, new_set._oid_set)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
return new_set
|
[
"Factory",
"function",
"to",
"create",
"a",
"new",
":",
"class",
":",
"OIDSet",
"with",
"a",
"single",
"member",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/oids.py#L165-L190
|
[
"def",
"singleton_set",
"(",
"cls",
",",
"single_oid",
")",
":",
"new_set",
"=",
"cls",
"(",
")",
"oid_ptr",
"=",
"None",
"if",
"isinstance",
"(",
"single_oid",
",",
"OID",
")",
":",
"oid_ptr",
"=",
"ffi",
".",
"addressof",
"(",
"single_oid",
".",
"_oid",
")",
"elif",
"isinstance",
"(",
"single_oid",
",",
"ffi",
".",
"CData",
")",
":",
"if",
"ffi",
".",
"typeof",
"(",
"single_oid",
")",
"==",
"ffi",
".",
"typeof",
"(",
"'gss_OID_desc'",
")",
":",
"oid_ptr",
"=",
"ffi",
".",
"addressof",
"(",
"single_oid",
")",
"elif",
"ffi",
".",
"typeof",
"(",
"single_oid",
")",
"==",
"ffi",
".",
"typeof",
"(",
"'gss_OID'",
")",
":",
"oid_ptr",
"=",
"single_oid",
"if",
"oid_ptr",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Expected a gssapi.oids.OID, got \"",
"+",
"str",
"(",
"type",
"(",
"single_oid",
")",
")",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"retval",
"=",
"C",
".",
"gss_add_oid_set_member",
"(",
"minor_status",
",",
"oid_ptr",
",",
"new_set",
".",
"_oid_set",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"return",
"new_set"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
MutableOIDSet.add
|
Adds another :class:`OID` to this set.
:param new_oid: the OID to add.
:type new_oid: :class:`OID`
|
gssapi/oids.py
|
def add(self, new_oid):
"""
Adds another :class:`OID` to this set.
:param new_oid: the OID to add.
:type new_oid: :class:`OID`
"""
if self._oid_set[0]:
oid_ptr = None
if isinstance(new_oid, OID):
oid_ptr = ffi.addressof(new_oid._oid)
elif isinstance(new_oid, ffi.CData):
if ffi.typeof(new_oid) == ffi.typeof('gss_OID_desc'):
oid_ptr = ffi.addressof(new_oid)
elif ffi.typeof(new_oid) == ffi.typeof('gss_OID'):
oid_ptr = new_oid
if oid_ptr is None:
raise TypeError("Expected a gssapi.oids.OID, got " + str(type(new_oid)))
minor_status = ffi.new('OM_uint32[1]')
retval = C.gss_add_oid_set_member(minor_status, oid_ptr, self._oid_set)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
else:
raise GSSException("Cannot add a member to this OIDSet, its gss_OID_set is NULL!")
|
def add(self, new_oid):
"""
Adds another :class:`OID` to this set.
:param new_oid: the OID to add.
:type new_oid: :class:`OID`
"""
if self._oid_set[0]:
oid_ptr = None
if isinstance(new_oid, OID):
oid_ptr = ffi.addressof(new_oid._oid)
elif isinstance(new_oid, ffi.CData):
if ffi.typeof(new_oid) == ffi.typeof('gss_OID_desc'):
oid_ptr = ffi.addressof(new_oid)
elif ffi.typeof(new_oid) == ffi.typeof('gss_OID'):
oid_ptr = new_oid
if oid_ptr is None:
raise TypeError("Expected a gssapi.oids.OID, got " + str(type(new_oid)))
minor_status = ffi.new('OM_uint32[1]')
retval = C.gss_add_oid_set_member(minor_status, oid_ptr, self._oid_set)
if GSS_ERROR(retval):
raise _exception_for_status(retval, minor_status[0])
else:
raise GSSException("Cannot add a member to this OIDSet, its gss_OID_set is NULL!")
|
[
"Adds",
"another",
":",
"class",
":",
"OID",
"to",
"this",
"set",
"."
] |
sigmaris/python-gssapi
|
python
|
https://github.com/sigmaris/python-gssapi/blob/a8ca577b3ccf9d9fa48f16f4954a1eddd5896236/gssapi/oids.py#L224-L248
|
[
"def",
"add",
"(",
"self",
",",
"new_oid",
")",
":",
"if",
"self",
".",
"_oid_set",
"[",
"0",
"]",
":",
"oid_ptr",
"=",
"None",
"if",
"isinstance",
"(",
"new_oid",
",",
"OID",
")",
":",
"oid_ptr",
"=",
"ffi",
".",
"addressof",
"(",
"new_oid",
".",
"_oid",
")",
"elif",
"isinstance",
"(",
"new_oid",
",",
"ffi",
".",
"CData",
")",
":",
"if",
"ffi",
".",
"typeof",
"(",
"new_oid",
")",
"==",
"ffi",
".",
"typeof",
"(",
"'gss_OID_desc'",
")",
":",
"oid_ptr",
"=",
"ffi",
".",
"addressof",
"(",
"new_oid",
")",
"elif",
"ffi",
".",
"typeof",
"(",
"new_oid",
")",
"==",
"ffi",
".",
"typeof",
"(",
"'gss_OID'",
")",
":",
"oid_ptr",
"=",
"new_oid",
"if",
"oid_ptr",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Expected a gssapi.oids.OID, got \"",
"+",
"str",
"(",
"type",
"(",
"new_oid",
")",
")",
")",
"minor_status",
"=",
"ffi",
".",
"new",
"(",
"'OM_uint32[1]'",
")",
"retval",
"=",
"C",
".",
"gss_add_oid_set_member",
"(",
"minor_status",
",",
"oid_ptr",
",",
"self",
".",
"_oid_set",
")",
"if",
"GSS_ERROR",
"(",
"retval",
")",
":",
"raise",
"_exception_for_status",
"(",
"retval",
",",
"minor_status",
"[",
"0",
"]",
")",
"else",
":",
"raise",
"GSSException",
"(",
"\"Cannot add a member to this OIDSet, its gss_OID_set is NULL!\"",
")"
] |
a8ca577b3ccf9d9fa48f16f4954a1eddd5896236
|
test
|
main
|
Imports and runs setup function with given properties.
|
setup.py
|
def main(properties=properties, options=options, **custom_options):
"""Imports and runs setup function with given properties."""
return init(**dict(options, **custom_options))(**properties)
|
def main(properties=properties, options=options, **custom_options):
"""Imports and runs setup function with given properties."""
return init(**dict(options, **custom_options))(**properties)
|
[
"Imports",
"and",
"runs",
"setup",
"function",
"with",
"given",
"properties",
"."
] |
salsita/flask-raml
|
python
|
https://github.com/salsita/flask-raml/blob/9876f19d49401fa32f7d852239aa295a78149ab2/setup.py#L82-L84
|
[
"def",
"main",
"(",
"properties",
"=",
"properties",
",",
"options",
"=",
"options",
",",
"*",
"*",
"custom_options",
")",
":",
"return",
"init",
"(",
"*",
"*",
"dict",
"(",
"options",
",",
"*",
"*",
"custom_options",
")",
")",
"(",
"*",
"*",
"properties",
")"
] |
9876f19d49401fa32f7d852239aa295a78149ab2
|
test
|
init
|
Imports and returns a setup function.
If use_markdown_readme is set,
then README.md is added to setuptools READMES list.
If use_stdeb is set on a Debian based system,
then module stdeb is imported.
Stdeb supports building deb packages on Debian based systems.
The package should only be installed on the same system version
it was built on, though. See http://github.com/astraw/stdeb.
If use_distribute is set, then distribute_setup.py is imported.
|
setup.py
|
def init(
dist='dist',
minver=None,
maxver=None,
use_markdown_readme=True,
use_stdeb=False,
use_distribute=False,
):
"""Imports and returns a setup function.
If use_markdown_readme is set,
then README.md is added to setuptools READMES list.
If use_stdeb is set on a Debian based system,
then module stdeb is imported.
Stdeb supports building deb packages on Debian based systems.
The package should only be installed on the same system version
it was built on, though. See http://github.com/astraw/stdeb.
If use_distribute is set, then distribute_setup.py is imported.
"""
if not minver == maxver == None:
import sys
if not minver <= sys.version < (maxver or 'Any'):
sys.stderr.write(
'%s: requires python version in <%s, %s), not %s\n' % (
sys.argv[0], minver or 'any', maxver or 'any', sys.version.split()[0]))
sys.exit(1)
if use_distribute:
from distribute_setup import use_setuptools
use_setuptools(to_dir=dist)
from setuptools import setup
else:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if use_markdown_readme:
try:
import setuptools.command.sdist
setuptools.command.sdist.READMES = tuple(list(getattr(setuptools.command.sdist, 'READMES', ()))
+ ['README.md'])
except ImportError:
pass
if use_stdeb:
import platform
if 'debian' in platform.dist():
try:
import stdeb
except ImportError:
pass
return setup
|
def init(
dist='dist',
minver=None,
maxver=None,
use_markdown_readme=True,
use_stdeb=False,
use_distribute=False,
):
"""Imports and returns a setup function.
If use_markdown_readme is set,
then README.md is added to setuptools READMES list.
If use_stdeb is set on a Debian based system,
then module stdeb is imported.
Stdeb supports building deb packages on Debian based systems.
The package should only be installed on the same system version
it was built on, though. See http://github.com/astraw/stdeb.
If use_distribute is set, then distribute_setup.py is imported.
"""
if not minver == maxver == None:
import sys
if not minver <= sys.version < (maxver or 'Any'):
sys.stderr.write(
'%s: requires python version in <%s, %s), not %s\n' % (
sys.argv[0], minver or 'any', maxver or 'any', sys.version.split()[0]))
sys.exit(1)
if use_distribute:
from distribute_setup import use_setuptools
use_setuptools(to_dir=dist)
from setuptools import setup
else:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if use_markdown_readme:
try:
import setuptools.command.sdist
setuptools.command.sdist.READMES = tuple(list(getattr(setuptools.command.sdist, 'READMES', ()))
+ ['README.md'])
except ImportError:
pass
if use_stdeb:
import platform
if 'debian' in platform.dist():
try:
import stdeb
except ImportError:
pass
return setup
|
[
"Imports",
"and",
"returns",
"a",
"setup",
"function",
"."
] |
salsita/flask-raml
|
python
|
https://github.com/salsita/flask-raml/blob/9876f19d49401fa32f7d852239aa295a78149ab2/setup.py#L86-L141
|
[
"def",
"init",
"(",
"dist",
"=",
"'dist'",
",",
"minver",
"=",
"None",
",",
"maxver",
"=",
"None",
",",
"use_markdown_readme",
"=",
"True",
",",
"use_stdeb",
"=",
"False",
",",
"use_distribute",
"=",
"False",
",",
")",
":",
"if",
"not",
"minver",
"==",
"maxver",
"==",
"None",
":",
"import",
"sys",
"if",
"not",
"minver",
"<=",
"sys",
".",
"version",
"<",
"(",
"maxver",
"or",
"'Any'",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s: requires python version in <%s, %s), not %s\\n'",
"%",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
",",
"minver",
"or",
"'any'",
",",
"maxver",
"or",
"'any'",
",",
"sys",
".",
"version",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"use_distribute",
":",
"from",
"distribute_setup",
"import",
"use_setuptools",
"use_setuptools",
"(",
"to_dir",
"=",
"dist",
")",
"from",
"setuptools",
"import",
"setup",
"else",
":",
"try",
":",
"from",
"setuptools",
"import",
"setup",
"except",
"ImportError",
":",
"from",
"distutils",
".",
"core",
"import",
"setup",
"if",
"use_markdown_readme",
":",
"try",
":",
"import",
"setuptools",
".",
"command",
".",
"sdist",
"setuptools",
".",
"command",
".",
"sdist",
".",
"READMES",
"=",
"tuple",
"(",
"list",
"(",
"getattr",
"(",
"setuptools",
".",
"command",
".",
"sdist",
",",
"'READMES'",
",",
"(",
")",
")",
")",
"+",
"[",
"'README.md'",
"]",
")",
"except",
"ImportError",
":",
"pass",
"if",
"use_stdeb",
":",
"import",
"platform",
"if",
"'debian'",
"in",
"platform",
".",
"dist",
"(",
")",
":",
"try",
":",
"import",
"stdeb",
"except",
"ImportError",
":",
"pass",
"return",
"setup"
] |
9876f19d49401fa32f7d852239aa295a78149ab2
|
test
|
main
|
kwargs:
'command_publish_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
'command_subscribe_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
'audio_publish_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
|
microphone/__main__.py
|
def main(context=None, *args, **kwargs):
"""
kwargs:
'command_publish_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
'command_subscribe_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
'audio_publish_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
"""
# Get configuration
args = _get_command_line_args()
# Get settings filepath
settings_filepath = args.get('settings_path')
# Get settings using the settings filepath
settings = _get_settings(settings_filepath)
settings = settings.get('microphone', {})
# TODO: verify that this doesn't break things in new and interesting ways
settings.update(kwargs)
plugin_manager = pluginmanager.PluginInterface()
plugin_manager.set_entry_points('microphone.audioengines')
plugins = plugin_manager.collect_entry_point_plugins(return_dict=True)
# find the audio driver or stick to the default of `pyaudio`
audio_driver = settings.get('audio_driver', 'pyaudio')
try:
# NOTE: `AudioDriver` is a class
AudioDriver = plugins[audio_driver]
# Fail early if we can't find the plugin we're looking for
except KeyError:
logging.error('Audio driver set in microphone settings of {} not foun'
'd. Please install or fix your settings file.')
logging.error('Plugins available: {}'.format(list(plugins.keys())))
sys.exit(1)
# TODO: Assume that a computer will only use one audio driver?
# Also assume that microphones may be physcially displaced from each other
# which means that they might record simultaneously
# FIXME: these are not good default addresses
command_publish_address = settings.get('publish_address',
'tcp://127.0.0.1:6910')
command_subscribe_address = settings.get('subscribe_address',
'tcp://127.0.0.1:6823')
audio_publish_address = settings.get('audio_publish_address',
'tcp://127.0.0.1:5012')
messaging = Messaging(command_publish_address,
command_subscribe_address,
audio_publish_address)
audio_driver = AudioDriver(messaging, settings)
audio_driver.run()
|
def main(context=None, *args, **kwargs):
"""
kwargs:
'command_publish_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
'command_subscribe_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
'audio_publish_address': in the form of `tcp://*:5555`
or any other zeromq address format. IE `ipc://*:5555`
"""
# Get configuration
args = _get_command_line_args()
# Get settings filepath
settings_filepath = args.get('settings_path')
# Get settings using the settings filepath
settings = _get_settings(settings_filepath)
settings = settings.get('microphone', {})
# TODO: verify that this doesn't break things in new and interesting ways
settings.update(kwargs)
plugin_manager = pluginmanager.PluginInterface()
plugin_manager.set_entry_points('microphone.audioengines')
plugins = plugin_manager.collect_entry_point_plugins(return_dict=True)
# find the audio driver or stick to the default of `pyaudio`
audio_driver = settings.get('audio_driver', 'pyaudio')
try:
# NOTE: `AudioDriver` is a class
AudioDriver = plugins[audio_driver]
# Fail early if we can't find the plugin we're looking for
except KeyError:
logging.error('Audio driver set in microphone settings of {} not foun'
'd. Please install or fix your settings file.')
logging.error('Plugins available: {}'.format(list(plugins.keys())))
sys.exit(1)
# TODO: Assume that a computer will only use one audio driver?
# Also assume that microphones may be physcially displaced from each other
# which means that they might record simultaneously
# FIXME: these are not good default addresses
command_publish_address = settings.get('publish_address',
'tcp://127.0.0.1:6910')
command_subscribe_address = settings.get('subscribe_address',
'tcp://127.0.0.1:6823')
audio_publish_address = settings.get('audio_publish_address',
'tcp://127.0.0.1:5012')
messaging = Messaging(command_publish_address,
command_subscribe_address,
audio_publish_address)
audio_driver = AudioDriver(messaging, settings)
audio_driver.run()
|
[
"kwargs",
":",
"command_publish_address",
":",
"in",
"the",
"form",
"of",
"tcp",
":",
"//",
"*",
":",
"5555",
"or",
"any",
"other",
"zeromq",
"address",
"format",
".",
"IE",
"ipc",
":",
"//",
"*",
":",
"5555"
] |
benhoff/microphone
|
python
|
https://github.com/benhoff/microphone/blob/a89e339a9a4a17d19fd1a8cb99efee3402b65673/microphone/__main__.py#L12-L74
|
[
"def",
"main",
"(",
"context",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get configuration",
"args",
"=",
"_get_command_line_args",
"(",
")",
"# Get settings filepath",
"settings_filepath",
"=",
"args",
".",
"get",
"(",
"'settings_path'",
")",
"# Get settings using the settings filepath",
"settings",
"=",
"_get_settings",
"(",
"settings_filepath",
")",
"settings",
"=",
"settings",
".",
"get",
"(",
"'microphone'",
",",
"{",
"}",
")",
"# TODO: verify that this doesn't break things in new and interesting ways",
"settings",
".",
"update",
"(",
"kwargs",
")",
"plugin_manager",
"=",
"pluginmanager",
".",
"PluginInterface",
"(",
")",
"plugin_manager",
".",
"set_entry_points",
"(",
"'microphone.audioengines'",
")",
"plugins",
"=",
"plugin_manager",
".",
"collect_entry_point_plugins",
"(",
"return_dict",
"=",
"True",
")",
"# find the audio driver or stick to the default of `pyaudio`",
"audio_driver",
"=",
"settings",
".",
"get",
"(",
"'audio_driver'",
",",
"'pyaudio'",
")",
"try",
":",
"# NOTE: `AudioDriver` is a class",
"AudioDriver",
"=",
"plugins",
"[",
"audio_driver",
"]",
"# Fail early if we can't find the plugin we're looking for",
"except",
"KeyError",
":",
"logging",
".",
"error",
"(",
"'Audio driver set in microphone settings of {} not foun'",
"'d. Please install or fix your settings file.'",
")",
"logging",
".",
"error",
"(",
"'Plugins available: {}'",
".",
"format",
"(",
"list",
"(",
"plugins",
".",
"keys",
"(",
")",
")",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# TODO: Assume that a computer will only use one audio driver?",
"# Also assume that microphones may be physcially displaced from each other",
"# which means that they might record simultaneously",
"# FIXME: these are not good default addresses",
"command_publish_address",
"=",
"settings",
".",
"get",
"(",
"'publish_address'",
",",
"'tcp://127.0.0.1:6910'",
")",
"command_subscribe_address",
"=",
"settings",
".",
"get",
"(",
"'subscribe_address'",
",",
"'tcp://127.0.0.1:6823'",
")",
"audio_publish_address",
"=",
"settings",
".",
"get",
"(",
"'audio_publish_address'",
",",
"'tcp://127.0.0.1:5012'",
")",
"messaging",
"=",
"Messaging",
"(",
"command_publish_address",
",",
"command_subscribe_address",
",",
"audio_publish_address",
")",
"audio_driver",
"=",
"AudioDriver",
"(",
"messaging",
",",
"settings",
")",
"audio_driver",
".",
"run",
"(",
")"
] |
a89e339a9a4a17d19fd1a8cb99efee3402b65673
|
test
|
_create_file
|
Returns a file handle which is used to record audio
|
examples/record_audio.py
|
def _create_file():
"""
Returns a file handle which is used to record audio
"""
f = wave.open('audio.wav', mode='wb')
f.setnchannels(2)
p = pyaudio.PyAudio()
f.setsampwidth(p.get_sample_size(pyaudio.paInt16))
f.setframerate(p.get_default_input_device_info()['defaultSampleRate'])
try:
yield f
finally:
f.close()
|
def _create_file():
"""
Returns a file handle which is used to record audio
"""
f = wave.open('audio.wav', mode='wb')
f.setnchannels(2)
p = pyaudio.PyAudio()
f.setsampwidth(p.get_sample_size(pyaudio.paInt16))
f.setframerate(p.get_default_input_device_info()['defaultSampleRate'])
try:
yield f
finally:
f.close()
|
[
"Returns",
"a",
"file",
"handle",
"which",
"is",
"used",
"to",
"record",
"audio"
] |
benhoff/microphone
|
python
|
https://github.com/benhoff/microphone/blob/a89e339a9a4a17d19fd1a8cb99efee3402b65673/examples/record_audio.py#L15-L27
|
[
"def",
"_create_file",
"(",
")",
":",
"f",
"=",
"wave",
".",
"open",
"(",
"'audio.wav'",
",",
"mode",
"=",
"'wb'",
")",
"f",
".",
"setnchannels",
"(",
"2",
")",
"p",
"=",
"pyaudio",
".",
"PyAudio",
"(",
")",
"f",
".",
"setsampwidth",
"(",
"p",
".",
"get_sample_size",
"(",
"pyaudio",
".",
"paInt16",
")",
")",
"f",
".",
"setframerate",
"(",
"p",
".",
"get_default_input_device_info",
"(",
")",
"[",
"'defaultSampleRate'",
"]",
")",
"try",
":",
"yield",
"f",
"finally",
":",
"f",
".",
"close",
"(",
")"
] |
a89e339a9a4a17d19fd1a8cb99efee3402b65673
|
test
|
PyAudio.get_devices
|
if device_type == plugin.audioengine.DEVICE_TYPE_ALL:
return devs
else:
return [device for device in devs if device_type in device.types]
|
microphone/pyaudio_.py
|
def get_devices(self, device_type='all'):
num_devices = self._pyaudio.get_device_count()
self._logger.debug('Found %d PyAudio devices', num_devices)
for i in range(num_devices):
info = self._pyaudio.get_device_info_by_index(i)
name = info['name']
if name in self.devices:
continue
else:
self.devices[name] = PyAudioDevice(self, info)
return self.devices
"""
if device_type == plugin.audioengine.DEVICE_TYPE_ALL:
return devs
else:
return [device for device in devs if device_type in device.types]
"""
|
def get_devices(self, device_type='all'):
num_devices = self._pyaudio.get_device_count()
self._logger.debug('Found %d PyAudio devices', num_devices)
for i in range(num_devices):
info = self._pyaudio.get_device_info_by_index(i)
name = info['name']
if name in self.devices:
continue
else:
self.devices[name] = PyAudioDevice(self, info)
return self.devices
"""
if device_type == plugin.audioengine.DEVICE_TYPE_ALL:
return devs
else:
return [device for device in devs if device_type in device.types]
"""
|
[
"if",
"device_type",
"==",
"plugin",
".",
"audioengine",
".",
"DEVICE_TYPE_ALL",
":",
"return",
"devs",
"else",
":",
"return",
"[",
"device",
"for",
"device",
"in",
"devs",
"if",
"device_type",
"in",
"device",
".",
"types",
"]"
] |
benhoff/microphone
|
python
|
https://github.com/benhoff/microphone/blob/a89e339a9a4a17d19fd1a8cb99efee3402b65673/microphone/pyaudio_.py#L70-L87
|
[
"def",
"get_devices",
"(",
"self",
",",
"device_type",
"=",
"'all'",
")",
":",
"num_devices",
"=",
"self",
".",
"_pyaudio",
".",
"get_device_count",
"(",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Found %d PyAudio devices'",
",",
"num_devices",
")",
"for",
"i",
"in",
"range",
"(",
"num_devices",
")",
":",
"info",
"=",
"self",
".",
"_pyaudio",
".",
"get_device_info_by_index",
"(",
"i",
")",
"name",
"=",
"info",
"[",
"'name'",
"]",
"if",
"name",
"in",
"self",
".",
"devices",
":",
"continue",
"else",
":",
"self",
".",
"devices",
"[",
"name",
"]",
"=",
"PyAudioDevice",
"(",
"self",
",",
"info",
")",
"return",
"self",
".",
"devices"
] |
a89e339a9a4a17d19fd1a8cb99efee3402b65673
|
test
|
PyAudioDevice.open_stream
|
self._logger.debug("%s stream opened on device '%s' (%d Hz, %d " +
"channel, %d bit)", "output" if output else "input",
self.slug, rate, channels, bits)
|
microphone/pyaudio_.py
|
def open_stream(self,
bits,
channels,
rate=None,
chunksize=1024,
output=True):
if rate is None:
rate = int(self.info['defaultSampleRate'])
# Check if format is supported
is_supported_fmt = self.supports_format(bits, channels, rate,
output=output)
if not is_supported_fmt:
msg_fmt = ("PyAudioDevice {index} ({name}) doesn't support " +
"%s format (Int{bits}, {channels}-channel at" +
" {rate} Hz)") % ('output' if output else 'input')
msg = msg_fmt.format(index=self.index,
name=self.name,
bits=bits,
channels=channels,
rate=rate)
self._logger.critical(msg)
raise plugin.audioengine.UnsupportedFormat(msg)
# Everything looks fine, open the stream
direction = ('output' if output else 'input')
stream_kwargs = {
'format': bits_to_samplefmt(bits),
'channels': channels,
'rate': rate,
'output': output,
'input': not output,
('%s_device_index' % direction): self._index,
'frames_per_buffer': chunksize if output else chunksize*8 # Hacky
}
stream = self._engine._pyaudio.open(**stream_kwargs)
"""
self._logger.debug("%s stream opened on device '%s' (%d Hz, %d " +
"channel, %d bit)", "output" if output else "input",
self.slug, rate, channels, bits)
"""
try:
yield stream
finally:
stream.close()
"""
self._logger.debug("%s stream closed on device '%s'",
"output" if output else "input", self.slug)
"""
|
def open_stream(self,
bits,
channels,
rate=None,
chunksize=1024,
output=True):
if rate is None:
rate = int(self.info['defaultSampleRate'])
# Check if format is supported
is_supported_fmt = self.supports_format(bits, channels, rate,
output=output)
if not is_supported_fmt:
msg_fmt = ("PyAudioDevice {index} ({name}) doesn't support " +
"%s format (Int{bits}, {channels}-channel at" +
" {rate} Hz)") % ('output' if output else 'input')
msg = msg_fmt.format(index=self.index,
name=self.name,
bits=bits,
channels=channels,
rate=rate)
self._logger.critical(msg)
raise plugin.audioengine.UnsupportedFormat(msg)
# Everything looks fine, open the stream
direction = ('output' if output else 'input')
stream_kwargs = {
'format': bits_to_samplefmt(bits),
'channels': channels,
'rate': rate,
'output': output,
'input': not output,
('%s_device_index' % direction): self._index,
'frames_per_buffer': chunksize if output else chunksize*8 # Hacky
}
stream = self._engine._pyaudio.open(**stream_kwargs)
"""
self._logger.debug("%s stream opened on device '%s' (%d Hz, %d " +
"channel, %d bit)", "output" if output else "input",
self.slug, rate, channels, bits)
"""
try:
yield stream
finally:
stream.close()
"""
self._logger.debug("%s stream closed on device '%s'",
"output" if output else "input", self.slug)
"""
|
[
"self",
".",
"_logger",
".",
"debug",
"(",
"%s",
"stream",
"opened",
"on",
"device",
"%s",
"(",
"%d",
"Hz",
"%d",
"+",
"channel",
"%d",
"bit",
")",
"output",
"if",
"output",
"else",
"input",
"self",
".",
"slug",
"rate",
"channels",
"bits",
")"
] |
benhoff/microphone
|
python
|
https://github.com/benhoff/microphone/blob/a89e339a9a4a17d19fd1a8cb99efee3402b65673/microphone/pyaudio_.py#L173-L221
|
[
"def",
"open_stream",
"(",
"self",
",",
"bits",
",",
"channels",
",",
"rate",
"=",
"None",
",",
"chunksize",
"=",
"1024",
",",
"output",
"=",
"True",
")",
":",
"if",
"rate",
"is",
"None",
":",
"rate",
"=",
"int",
"(",
"self",
".",
"info",
"[",
"'defaultSampleRate'",
"]",
")",
"# Check if format is supported",
"is_supported_fmt",
"=",
"self",
".",
"supports_format",
"(",
"bits",
",",
"channels",
",",
"rate",
",",
"output",
"=",
"output",
")",
"if",
"not",
"is_supported_fmt",
":",
"msg_fmt",
"=",
"(",
"\"PyAudioDevice {index} ({name}) doesn't support \"",
"+",
"\"%s format (Int{bits}, {channels}-channel at\"",
"+",
"\" {rate} Hz)\"",
")",
"%",
"(",
"'output'",
"if",
"output",
"else",
"'input'",
")",
"msg",
"=",
"msg_fmt",
".",
"format",
"(",
"index",
"=",
"self",
".",
"index",
",",
"name",
"=",
"self",
".",
"name",
",",
"bits",
"=",
"bits",
",",
"channels",
"=",
"channels",
",",
"rate",
"=",
"rate",
")",
"self",
".",
"_logger",
".",
"critical",
"(",
"msg",
")",
"raise",
"plugin",
".",
"audioengine",
".",
"UnsupportedFormat",
"(",
"msg",
")",
"# Everything looks fine, open the stream",
"direction",
"=",
"(",
"'output'",
"if",
"output",
"else",
"'input'",
")",
"stream_kwargs",
"=",
"{",
"'format'",
":",
"bits_to_samplefmt",
"(",
"bits",
")",
",",
"'channels'",
":",
"channels",
",",
"'rate'",
":",
"rate",
",",
"'output'",
":",
"output",
",",
"'input'",
":",
"not",
"output",
",",
"(",
"'%s_device_index'",
"%",
"direction",
")",
":",
"self",
".",
"_index",
",",
"'frames_per_buffer'",
":",
"chunksize",
"if",
"output",
"else",
"chunksize",
"*",
"8",
"# Hacky",
"}",
"stream",
"=",
"self",
".",
"_engine",
".",
"_pyaudio",
".",
"open",
"(",
"*",
"*",
"stream_kwargs",
")",
"try",
":",
"yield",
"stream",
"finally",
":",
"stream",
".",
"close",
"(",
")",
"\"\"\"\n self._logger.debug(\"%s stream closed on device '%s'\",\n \"output\" if output else \"input\", self.slug)\n \"\"\""
] |
a89e339a9a4a17d19fd1a8cb99efee3402b65673
|
test
|
djfrontend_h5bp_css
|
Returns HTML5 Boilerplate CSS file.
Included in HTML5 Boilerplate.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_h5bp_css(version=None):
"""
Returns HTML5 Boilerplate CSS file.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_H5BP_CSS', DJFRONTEND_H5BP_CSS_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{0}djfrontend/css/h5bp/{1}/h5bp.css">',
_static_url, version)
|
def djfrontend_h5bp_css(version=None):
"""
Returns HTML5 Boilerplate CSS file.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_H5BP_CSS', DJFRONTEND_H5BP_CSS_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{0}djfrontend/css/h5bp/{1}/h5bp.css">',
_static_url, version)
|
[
"Returns",
"HTML5",
"Boilerplate",
"CSS",
"file",
".",
"Included",
"in",
"HTML5",
"Boilerplate",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L32-L42
|
[
"def",
"djfrontend_h5bp_css",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_H5BP_CSS'",
",",
"DJFRONTEND_H5BP_CSS_DEFAULT",
")",
"return",
"format_html",
"(",
"'<link rel=\"stylesheet\" href=\"{0}djfrontend/css/h5bp/{1}/h5bp.css\">'",
",",
"_static_url",
",",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_normalize
|
Returns Normalize CSS file.
Included in HTML5 Boilerplate.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_normalize(version=None):
"""
Returns Normalize CSS file.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_NORMALIZE', DJFRONTEND_NORMALIZE_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{0}djfrontend/css/normalize/{1}/normalize.css">',
_static_url, version)
|
def djfrontend_normalize(version=None):
"""
Returns Normalize CSS file.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_NORMALIZE', DJFRONTEND_NORMALIZE_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{0}djfrontend/css/normalize/{1}/normalize.css">',
_static_url, version)
|
[
"Returns",
"Normalize",
"CSS",
"file",
".",
"Included",
"in",
"HTML5",
"Boilerplate",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L46-L56
|
[
"def",
"djfrontend_normalize",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_NORMALIZE'",
",",
"DJFRONTEND_NORMALIZE_DEFAULT",
")",
"return",
"format_html",
"(",
"'<link rel=\"stylesheet\" href=\"{0}djfrontend/css/normalize/{1}/normalize.css\">'",
",",
"_static_url",
",",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_fontawesome
|
Returns Font Awesome CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_fontawesome(version=None):
"""
Returns Font Awesome CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_FONTAWESOME', DJFRONTEND_FONTAWESOME_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{0}djfrontend/css/fontawesome/{1}/font-awesome{2}.css">',
_static_url, version, _min)
|
def djfrontend_fontawesome(version=None):
"""
Returns Font Awesome CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_FONTAWESOME', DJFRONTEND_FONTAWESOME_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{0}djfrontend/css/fontawesome/{1}/font-awesome{2}.css">',
_static_url, version, _min)
|
[
"Returns",
"Font",
"Awesome",
"CSS",
"file",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L60-L70
|
[
"def",
"djfrontend_fontawesome",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_FONTAWESOME'",
",",
"DJFRONTEND_FONTAWESOME_DEFAULT",
")",
"return",
"format_html",
"(",
"'<link rel=\"stylesheet\" href=\"{0}djfrontend/css/fontawesome/{1}/font-awesome{2}.css\">'",
",",
"_static_url",
",",
"version",
",",
"_min",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_modernizr
|
Returns Modernizr JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
Included in HTML5 Boilerplate.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_modernizr(version=None):
"""
Returns Modernizr JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_MODERNIZR', DJFRONTEND_MODERNIZR_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/modernizr/{v}/modernizr.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/{v}/modernizr.min.js"></script>\n'
'<script>window.Modernizr || document.write(\'<script src="{static}djfrontend/js/modernizr/{v}/modernizr.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
def djfrontend_modernizr(version=None):
"""
Returns Modernizr JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_MODERNIZR', DJFRONTEND_MODERNIZR_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/modernizr/{v}/modernizr.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/{v}/modernizr.min.js"></script>\n'
'<script>window.Modernizr || document.write(\'<script src="{static}djfrontend/js/modernizr/{v}/modernizr.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
[
"Returns",
"Modernizr",
"JavaScript",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
".",
"Included",
"in",
"HTML5",
"Boilerplate",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L74-L89
|
[
"def",
"djfrontend_modernizr",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_MODERNIZR'",
",",
"DJFRONTEND_MODERNIZR_DEFAULT",
")",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"template",
"=",
"'<script src=\"{static}djfrontend/js/modernizr/{v}/modernizr.js\"></script>'",
"else",
":",
"template",
"=",
"(",
"'<script src=\"//cdnjs.cloudflare.com/ajax/libs/modernizr/{v}/modernizr.min.js\"></script>\\n'",
"'<script>window.Modernizr || document.write(\\'<script src=\"{static}djfrontend/js/modernizr/{v}/modernizr.min.js\"><\\/script>\\')</script>'",
")",
"return",
"format_html",
"(",
"template",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jquery
|
Returns jQuery JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
Included in HTML5 Boilerplate.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jquery(version=None):
"""
Returns jQuery JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY', DJFRONTEND_JQUERY_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/{v}/jquery.js"></script>'
else:
template = (
'<script src="//ajax.googleapis.com/ajax/libs/jquery/{v}/jquery.min.js"></script>'
'<script>window.jQuery || document.write(\'<script src="{static}djfrontend/js/jquery/{v}/jquery.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
def djfrontend_jquery(version=None):
"""
Returns jQuery JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY', DJFRONTEND_JQUERY_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/{v}/jquery.js"></script>'
else:
template = (
'<script src="//ajax.googleapis.com/ajax/libs/jquery/{v}/jquery.min.js"></script>'
'<script>window.jQuery || document.write(\'<script src="{static}djfrontend/js/jquery/{v}/jquery.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
[
"Returns",
"jQuery",
"JavaScript",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"from",
"Google",
"CDN",
"with",
"local",
"fallback",
".",
"Included",
"in",
"HTML5",
"Boilerplate",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L93-L108
|
[
"def",
"djfrontend_jquery",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY'",
",",
"DJFRONTEND_JQUERY_DEFAULT",
")",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"template",
"=",
"'<script src=\"{static}djfrontend/js/jquery/{v}/jquery.js\"></script>'",
"else",
":",
"template",
"=",
"(",
"'<script src=\"//ajax.googleapis.com/ajax/libs/jquery/{v}/jquery.min.js\"></script>'",
"'<script>window.jQuery || document.write(\\'<script src=\"{static}djfrontend/js/jquery/{v}/jquery.min.js\"><\\/script>\\')</script>'",
")",
"return",
"format_html",
"(",
"template",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jqueryui
|
Returns the jQuery UI plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jqueryui(version=None):
"""
Returns the jQuery UI plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERYUI', DJFRONTEND_JQUERYUI_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
return format_html(
'<script src="{0}djfrontend/js/jquery/jqueryui/{1}/jquery-ui.js"></script>',
settings.STATIC_URL, version)
else:
return format_html(
'<script src="//ajax.googleapis.com/ajax/libs/jqueryui/{v}/jquery-ui.min.js"></script>'
'<script>window.jQuery.ui || document.write(\'<script src="{static}djfrontend/js/jquery/jqueryui/{v}/jquery-ui.min.js"><\/script>\')</script>',
static=_static_url, v=version)
|
def djfrontend_jqueryui(version=None):
"""
Returns the jQuery UI plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERYUI', DJFRONTEND_JQUERYUI_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
return format_html(
'<script src="{0}djfrontend/js/jquery/jqueryui/{1}/jquery-ui.js"></script>',
settings.STATIC_URL, version)
else:
return format_html(
'<script src="//ajax.googleapis.com/ajax/libs/jqueryui/{v}/jquery-ui.min.js"></script>'
'<script>window.jQuery.ui || document.write(\'<script src="{static}djfrontend/js/jquery/jqueryui/{v}/jquery-ui.min.js"><\/script>\')</script>',
static=_static_url, v=version)
|
[
"Returns",
"the",
"jQuery",
"UI",
"plugin",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"from",
"Google",
"CDN",
"with",
"local",
"fallback",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L112-L128
|
[
"def",
"djfrontend_jqueryui",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERYUI'",
",",
"DJFRONTEND_JQUERYUI_DEFAULT",
")",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"return",
"format_html",
"(",
"'<script src=\"{0}djfrontend/js/jquery/jqueryui/{1}/jquery-ui.js\"></script>'",
",",
"settings",
".",
"STATIC_URL",
",",
"version",
")",
"else",
":",
"return",
"format_html",
"(",
"'<script src=\"//ajax.googleapis.com/ajax/libs/jqueryui/{v}/jquery-ui.min.js\"></script>'",
"'<script>window.jQuery.ui || document.write(\\'<script src=\"{static}djfrontend/js/jquery/jqueryui/{v}/jquery-ui.min.js\"><\\/script>\\')</script>'",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jquery_datatables
|
Returns the jQuery DataTables plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jquery_datatables(version=None):
"""
Returns the jQuery DataTables plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES', False):
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_VERSION', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.dataTables/{v}/jquery.dataTables.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/{v}/jquery.dataTables.min.js"></script>'
'<script>window.jQuery.fn.DataTable || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.dataTables/{v}/jquery.dataTables.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
def djfrontend_jquery_datatables(version=None):
"""
Returns the jQuery DataTables plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES', False):
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_VERSION', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.dataTables/{v}/jquery.dataTables.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/{v}/jquery.dataTables.min.js"></script>'
'<script>window.jQuery.fn.DataTable || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.dataTables/{v}/jquery.dataTables.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
[
"Returns",
"the",
"jQuery",
"DataTables",
"plugin",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L132-L149
|
[
"def",
"djfrontend_jquery_datatables",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES'",
",",
"False",
")",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES_VERSION'",
",",
"DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT",
")",
"else",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES'",
",",
"DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT",
")",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"template",
"=",
"'<script src=\"{static}djfrontend/js/jquery/jquery.dataTables/{v}/jquery.dataTables.js\"></script>'",
"else",
":",
"template",
"=",
"(",
"'<script src=\"//cdnjs.cloudflare.com/ajax/libs/datatables/{v}/jquery.dataTables.min.js\"></script>'",
"'<script>window.jQuery.fn.DataTable || document.write(\\'<script src=\"{static}djfrontend/js/jquery/jquery.dataTables/{v}/jquery.dataTables.min.js\"><\\/script>\\')</script>'",
")",
"return",
"format_html",
"(",
"template",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jquery_datatables_css
|
Returns the jQuery DataTables CSS file according to version number.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jquery_datatables_css(version=None):
"""
Returns the jQuery DataTables CSS file according to version number.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_CSS', False):
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_VERSION', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_CSS', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{static}djfrontend/css/jquery/jquery.dataTables/{v}/jquery.dataTables{min}.css">',
static=_static_url, v=version, min=_min)
|
def djfrontend_jquery_datatables_css(version=None):
"""
Returns the jQuery DataTables CSS file according to version number.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_CSS', False):
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_VERSION', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_CSS', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{static}djfrontend/css/jquery/jquery.dataTables/{v}/jquery.dataTables{min}.css">',
static=_static_url, v=version, min=_min)
|
[
"Returns",
"the",
"jQuery",
"DataTables",
"CSS",
"file",
"according",
"to",
"version",
"number",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L153-L166
|
[
"def",
"djfrontend_jquery_datatables_css",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES_CSS'",
",",
"False",
")",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES_VERSION'",
",",
"DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT",
")",
"else",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES_CSS'",
",",
"DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT",
")",
"return",
"format_html",
"(",
"'<link rel=\"stylesheet\" href=\"{static}djfrontend/css/jquery/jquery.dataTables/{v}/jquery.dataTables{min}.css\">'",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
",",
"min",
"=",
"_min",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jquery_datatables_themeroller
|
Returns the jQuery DataTables ThemeRoller CSS file according to version number.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jquery_datatables_themeroller(version=None):
"""
Returns the jQuery DataTables ThemeRoller CSS file according to version number.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_THEMEROLLER', False):
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_VERSION', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_THEMEROLLER', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
return format_html(
'<link rel="stylesheet" href="href="{static}djfrontend/css/jquery/jquery.dataTables/{v}/jquery.dataTables_themeroller.min.css">',
static=_static_url, v=version)
|
def djfrontend_jquery_datatables_themeroller(version=None):
"""
Returns the jQuery DataTables ThemeRoller CSS file according to version number.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_THEMEROLLER', False):
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_VERSION', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_THEMEROLLER', DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT)
return format_html(
'<link rel="stylesheet" href="href="{static}djfrontend/css/jquery/jquery.dataTables/{v}/jquery.dataTables_themeroller.min.css">',
static=_static_url, v=version)
|
[
"Returns",
"the",
"jQuery",
"DataTables",
"ThemeRoller",
"CSS",
"file",
"according",
"to",
"version",
"number",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L170-L182
|
[
"def",
"djfrontend_jquery_datatables_themeroller",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES_THEMEROLLER'",
",",
"False",
")",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES_VERSION'",
",",
"DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT",
")",
"else",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_DATATABLES_THEMEROLLER'",
",",
"DJFRONTEND_JQUERY_DATATABLES_VERSION_DEFAULT",
")",
"return",
"format_html",
"(",
"'<link rel=\"stylesheet\" href=\"href=\"{static}djfrontend/css/jquery/jquery.dataTables/{v}/jquery.dataTables_themeroller.min.css\">'",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jquery_formset
|
Returns the jQuery Dynamic Formset plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jquery_formset(version=None):
"""
Returns the jQuery Dynamic Formset plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_FORMSET', DJFRONTEND_JQUERY_FORMSET_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.formset/{v}/jquery.formset.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.formset/{v}/jquery.formset.min.js"></script>\n'
'<script>window.jQuery.fn.formset || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.formset/{v}/jquery.formset.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
def djfrontend_jquery_formset(version=None):
"""
Returns the jQuery Dynamic Formset plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_FORMSET', DJFRONTEND_JQUERY_FORMSET_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.formset/{v}/jquery.formset.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.formset/{v}/jquery.formset.min.js"></script>\n'
'<script>window.jQuery.fn.formset || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.formset/{v}/jquery.formset.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
[
"Returns",
"the",
"jQuery",
"Dynamic",
"Formset",
"plugin",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L186-L200
|
[
"def",
"djfrontend_jquery_formset",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_FORMSET'",
",",
"DJFRONTEND_JQUERY_FORMSET_DEFAULT",
")",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"template",
"=",
"'<script src=\"{static}djfrontend/js/jquery/jquery.formset/{v}/jquery.formset.js\"></script>'",
"else",
":",
"template",
"=",
"(",
"'<script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery.formset/{v}/jquery.formset.min.js\"></script>\\n'",
"'<script>window.jQuery.fn.formset || document.write(\\'<script src=\"{static}djfrontend/js/jquery/jquery.formset/{v}/jquery.formset.min.js\"><\\/script>\\')</script>'",
")",
"return",
"format_html",
"(",
"template",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jquery_scrollto
|
Returns the jQuery ScrollTo plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jquery_scrollto(version=None):
"""
Returns the jQuery ScrollTo plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_SCROLLTO', DJFRONTEND_JQUERY_SCROLLTO_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.scrollTo/{v}/jquery.scrollTo.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/{v}/jquery.scrollTo.min.js"></script>'
'<script>window.jQuery.fn.scrollTo || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.scrollTo/{v}/jquery.scrollTo.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
def djfrontend_jquery_scrollto(version=None):
"""
Returns the jQuery ScrollTo plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_SCROLLTO', DJFRONTEND_JQUERY_SCROLLTO_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.scrollTo/{v}/jquery.scrollTo.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/{v}/jquery.scrollTo.min.js"></script>'
'<script>window.jQuery.fn.scrollTo || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.scrollTo/{v}/jquery.scrollTo.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
[
"Returns",
"the",
"jQuery",
"ScrollTo",
"plugin",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L204-L218
|
[
"def",
"djfrontend_jquery_scrollto",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_SCROLLTO'",
",",
"DJFRONTEND_JQUERY_SCROLLTO_DEFAULT",
")",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"template",
"=",
"'<script src=\"{static}djfrontend/js/jquery/jquery.scrollTo/{v}/jquery.scrollTo.js\"></script>'",
"else",
":",
"template",
"=",
"(",
"'<script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/{v}/jquery.scrollTo.min.js\"></script>'",
"'<script>window.jQuery.fn.scrollTo || document.write(\\'<script src=\"{static}djfrontend/js/jquery/jquery.scrollTo/{v}/jquery.scrollTo.min.js\"><\\/script>\\')</script>'",
")",
"return",
"format_html",
"(",
"template",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_jquery_smoothscroll
|
Returns the jQuery Smooth Scroll plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_jquery_smoothscroll(version=None):
"""
Returns the jQuery Smooth Scroll plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_SMOOTHSCROLL', DJFRONTEND_JQUERY_SMOOTHSCROLL_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.smooth-scroll/{v}/jquery.smooth-scroll.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-smooth-scroll/{v}/jquery.smooth-scroll.min.js"></script>'
'<script>window.jQuery.fn.smoothScroll || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.smooth-scroll/{v}/jquery.smooth-scroll.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
def djfrontend_jquery_smoothscroll(version=None):
"""
Returns the jQuery Smooth Scroll plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_SMOOTHSCROLL', DJFRONTEND_JQUERY_SMOOTHSCROLL_DEFAULT)
if getattr(settings, 'TEMPLATE_DEBUG', False):
template = '<script src="{static}djfrontend/js/jquery/jquery.smooth-scroll/{v}/jquery.smooth-scroll.js"></script>'
else:
template = (
'<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-smooth-scroll/{v}/jquery.smooth-scroll.min.js"></script>'
'<script>window.jQuery.fn.smoothScroll || document.write(\'<script src="{static}djfrontend/js/jquery/jquery.smooth-scroll/{v}/jquery.smooth-scroll.min.js"><\/script>\')</script>')
return format_html(template, static=_static_url, v=version)
|
[
"Returns",
"the",
"jQuery",
"Smooth",
"Scroll",
"plugin",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L222-L236
|
[
"def",
"djfrontend_jquery_smoothscroll",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_SMOOTHSCROLL'",
",",
"DJFRONTEND_JQUERY_SMOOTHSCROLL_DEFAULT",
")",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"template",
"=",
"'<script src=\"{static}djfrontend/js/jquery/jquery.smooth-scroll/{v}/jquery.smooth-scroll.js\"></script>'",
"else",
":",
"template",
"=",
"(",
"'<script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery-smooth-scroll/{v}/jquery.smooth-scroll.min.js\"></script>'",
"'<script>window.jQuery.fn.smoothScroll || document.write(\\'<script src=\"{static}djfrontend/js/jquery/jquery.smooth-scroll/{v}/jquery.smooth-scroll.min.js\"><\\/script>\\')</script>'",
")",
"return",
"format_html",
"(",
"template",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_twbs_css
|
Returns Twitter Bootstrap CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_twbs_css(version=None):
"""
Returns Twitter Bootstrap CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_TWBS_CSS', False):
version = getattr(settings, 'DJFRONTEND_TWBS_VERSION', DJFRONTEND_TWBS_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_TWBS_CSS', DJFRONTEND_TWBS_VERSION_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{static}djfrontend/css/twbs/{v}/bootstrap{min}.css">',
static=_static_url, v=version, min=_min)
|
def djfrontend_twbs_css(version=None):
"""
Returns Twitter Bootstrap CSS file.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_TWBS_CSS', False):
version = getattr(settings, 'DJFRONTEND_TWBS_VERSION', DJFRONTEND_TWBS_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_TWBS_CSS', DJFRONTEND_TWBS_VERSION_DEFAULT)
return format_html(
'<link rel="stylesheet" href="{static}djfrontend/css/twbs/{v}/bootstrap{min}.css">',
static=_static_url, v=version, min=_min)
|
[
"Returns",
"Twitter",
"Bootstrap",
"CSS",
"file",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L240-L253
|
[
"def",
"djfrontend_twbs_css",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_TWBS_CSS'",
",",
"False",
")",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_TWBS_VERSION'",
",",
"DJFRONTEND_TWBS_VERSION_DEFAULT",
")",
"else",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_TWBS_CSS'",
",",
"DJFRONTEND_TWBS_VERSION_DEFAULT",
")",
"return",
"format_html",
"(",
"'<link rel=\"stylesheet\" href=\"{static}djfrontend/css/twbs/{v}/bootstrap{min}.css\">'",
",",
"static",
"=",
"_static_url",
",",
"v",
"=",
"version",
",",
"min",
"=",
"_min",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_twbs_js
|
Returns Twitter Bootstrap JavaScript file(s).
all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise.
Other choice are:
affix,
alert,
button,
carousel,
collapse,
dropdown,
modal,
popover (adds tooltip if not included),
scrollspy,
tab,
tooltip,
transition.
Individual files are not minified.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_twbs_js(version=None, files=None):
"""
Returns Twitter Bootstrap JavaScript file(s).
all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise.
Other choice are:
affix,
alert,
button,
carousel,
collapse,
dropdown,
modal,
popover (adds tooltip if not included),
scrollspy,
tab,
tooltip,
transition.
Individual files are not minified.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_TWBS_JS_VERSION', False):
version = getattr(settings, 'DJFRONTEND_TWBS_VERSION', DJFRONTEND_TWBS_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_TWBS_JS_VERSION', DJFRONTEND_TWBS_VERSION_DEFAULT)
if files:
if files != 'all':
files = files.split(' ')
elif getattr(settings, 'DJFRONTEND_TWBS_JS_FILES', False) and settings.DJFRONTEND_TWBS_JS_FILES != 'all':
files = settings.DJFRONTEND_TWBS_JS_FILES.split(' ')
else:
files = 'all'
if files == 'all':
return format_html(
'<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/{v}/js/bootstrap.min.js"></script>\n'
'<script>window.jQuery.fn.scrollspy || document.write(\'<script src="{static}djfrontend/js/twbs/{v}/bootstrap.min.js"><\/script>\')</script>',
v=version, static=_static_url)
else:
if 'popover' in files and 'tooltip' not in files:
files.append('tooltip')
for file in files:
file = ['<script src="%sdjfrontend/js/twbs/%s/%s.js"></script>' %
(_static_url, version, file) for file in files]
return mark_safe('\n'.join(file))
|
def djfrontend_twbs_js(version=None, files=None):
"""
Returns Twitter Bootstrap JavaScript file(s).
all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise.
Other choice are:
affix,
alert,
button,
carousel,
collapse,
dropdown,
modal,
popover (adds tooltip if not included),
scrollspy,
tab,
tooltip,
transition.
Individual files are not minified.
"""
if version is None:
if not getattr(settings, 'DJFRONTEND_TWBS_JS_VERSION', False):
version = getattr(settings, 'DJFRONTEND_TWBS_VERSION', DJFRONTEND_TWBS_VERSION_DEFAULT)
else:
version = getattr(settings, 'DJFRONTEND_TWBS_JS_VERSION', DJFRONTEND_TWBS_VERSION_DEFAULT)
if files:
if files != 'all':
files = files.split(' ')
elif getattr(settings, 'DJFRONTEND_TWBS_JS_FILES', False) and settings.DJFRONTEND_TWBS_JS_FILES != 'all':
files = settings.DJFRONTEND_TWBS_JS_FILES.split(' ')
else:
files = 'all'
if files == 'all':
return format_html(
'<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/{v}/js/bootstrap.min.js"></script>\n'
'<script>window.jQuery.fn.scrollspy || document.write(\'<script src="{static}djfrontend/js/twbs/{v}/bootstrap.min.js"><\/script>\')</script>',
v=version, static=_static_url)
else:
if 'popover' in files and 'tooltip' not in files:
files.append('tooltip')
for file in files:
file = ['<script src="%sdjfrontend/js/twbs/%s/%s.js"></script>' %
(_static_url, version, file) for file in files]
return mark_safe('\n'.join(file))
|
[
"Returns",
"Twitter",
"Bootstrap",
"JavaScript",
"file",
"(",
"s",
")",
".",
"all",
"returns",
"concatenated",
"file",
";",
"full",
"file",
"for",
"TEMPLATE_DEBUG",
"minified",
"otherwise",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L273-L319
|
[
"def",
"djfrontend_twbs_js",
"(",
"version",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_TWBS_JS_VERSION'",
",",
"False",
")",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_TWBS_VERSION'",
",",
"DJFRONTEND_TWBS_VERSION_DEFAULT",
")",
"else",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_TWBS_JS_VERSION'",
",",
"DJFRONTEND_TWBS_VERSION_DEFAULT",
")",
"if",
"files",
":",
"if",
"files",
"!=",
"'all'",
":",
"files",
"=",
"files",
".",
"split",
"(",
"' '",
")",
"elif",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_TWBS_JS_FILES'",
",",
"False",
")",
"and",
"settings",
".",
"DJFRONTEND_TWBS_JS_FILES",
"!=",
"'all'",
":",
"files",
"=",
"settings",
".",
"DJFRONTEND_TWBS_JS_FILES",
".",
"split",
"(",
"' '",
")",
"else",
":",
"files",
"=",
"'all'",
"if",
"files",
"==",
"'all'",
":",
"return",
"format_html",
"(",
"'<script src=\"//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/{v}/js/bootstrap.min.js\"></script>\\n'",
"'<script>window.jQuery.fn.scrollspy || document.write(\\'<script src=\"{static}djfrontend/js/twbs/{v}/bootstrap.min.js\"><\\/script>\\')</script>'",
",",
"v",
"=",
"version",
",",
"static",
"=",
"_static_url",
")",
"else",
":",
"if",
"'popover'",
"in",
"files",
"and",
"'tooltip'",
"not",
"in",
"files",
":",
"files",
".",
"append",
"(",
"'tooltip'",
")",
"for",
"file",
"in",
"files",
":",
"file",
"=",
"[",
"'<script src=\"%sdjfrontend/js/twbs/%s/%s.js\"></script>'",
"%",
"(",
"_static_url",
",",
"version",
",",
"file",
")",
"for",
"file",
"in",
"files",
"]",
"return",
"mark_safe",
"(",
"'\\n'",
".",
"join",
"(",
"file",
")",
")"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
djfrontend_ga
|
Returns Google Analytics asynchronous snippet.
Use DJFRONTEND_GA_SETDOMAINNAME to set domain for multiple, or cross-domain tracking.
Set DJFRONTEND_GA_SETALLOWLINKER to use _setAllowLinker method on target site for cross-domain tracking.
Included in HTML5 Boilerplate.
|
djfrontend/templatetags/djfrontend.py
|
def djfrontend_ga(account=None):
"""
Returns Google Analytics asynchronous snippet.
Use DJFRONTEND_GA_SETDOMAINNAME to set domain for multiple, or cross-domain tracking.
Set DJFRONTEND_GA_SETALLOWLINKER to use _setAllowLinker method on target site for cross-domain tracking.
Included in HTML5 Boilerplate.
"""
if account is None:
account = getattr(settings, 'DJFRONTEND_GA', False)
if account:
if getattr(settings, 'TEMPLATE_DEBUG', False):
return ''
else:
if getattr(settings, 'DJFRONTEND_GA_SETDOMAINNAME', False):
if getattr(settings, 'DJFRONTEND_GA_SETALLOWLINKER', False):
return mark_safe(
'<script>(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("require", "linker");ga("linker:autoLink", ["%s"]);ga("create", "%s", "auto", {"allowLinker": true});ga("send", "pageview");</script>' %
(settings.DJFRONTEND_GA_SETDOMAINNAME, account))
else:
return mark_safe(
'<script>(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create", "%s", "%s");ga("send", "pageview");</script>' %
(account, settings.DJFRONTEND_GA_SETDOMAINNAME))
else:
return mark_safe(
'<script>(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create", "%s", "auto");ga("send", "pageview");</script>' % account)
else:
return ''
|
def djfrontend_ga(account=None):
"""
Returns Google Analytics asynchronous snippet.
Use DJFRONTEND_GA_SETDOMAINNAME to set domain for multiple, or cross-domain tracking.
Set DJFRONTEND_GA_SETALLOWLINKER to use _setAllowLinker method on target site for cross-domain tracking.
Included in HTML5 Boilerplate.
"""
if account is None:
account = getattr(settings, 'DJFRONTEND_GA', False)
if account:
if getattr(settings, 'TEMPLATE_DEBUG', False):
return ''
else:
if getattr(settings, 'DJFRONTEND_GA_SETDOMAINNAME', False):
if getattr(settings, 'DJFRONTEND_GA_SETALLOWLINKER', False):
return mark_safe(
'<script>(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("require", "linker");ga("linker:autoLink", ["%s"]);ga("create", "%s", "auto", {"allowLinker": true});ga("send", "pageview");</script>' %
(settings.DJFRONTEND_GA_SETDOMAINNAME, account))
else:
return mark_safe(
'<script>(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create", "%s", "%s");ga("send", "pageview");</script>' %
(account, settings.DJFRONTEND_GA_SETDOMAINNAME))
else:
return mark_safe(
'<script>(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create", "%s", "auto");ga("send", "pageview");</script>' % account)
else:
return ''
|
[
"Returns",
"Google",
"Analytics",
"asynchronous",
"snippet",
".",
"Use",
"DJFRONTEND_GA_SETDOMAINNAME",
"to",
"set",
"domain",
"for",
"multiple",
"or",
"cross",
"-",
"domain",
"tracking",
".",
"Set",
"DJFRONTEND_GA_SETALLOWLINKER",
"to",
"use",
"_setAllowLinker",
"method",
"on",
"target",
"site",
"for",
"cross",
"-",
"domain",
"tracking",
".",
"Included",
"in",
"HTML5",
"Boilerplate",
"."
] |
jonfaustman/django-frontend
|
python
|
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L323-L350
|
[
"def",
"djfrontend_ga",
"(",
"account",
"=",
"None",
")",
":",
"if",
"account",
"is",
"None",
":",
"account",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_GA'",
",",
"False",
")",
"if",
"account",
":",
"if",
"getattr",
"(",
"settings",
",",
"'TEMPLATE_DEBUG'",
",",
"False",
")",
":",
"return",
"''",
"else",
":",
"if",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_GA_SETDOMAINNAME'",
",",
"False",
")",
":",
"if",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_GA_SETALLOWLINKER'",
",",
"False",
")",
":",
"return",
"mark_safe",
"(",
"'<script>(function(i,s,o,g,r,a,m){i[\"GoogleAnalyticsObject\"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,\"script\",\"//www.google-analytics.com/analytics.js\",\"ga\");ga(\"require\", \"linker\");ga(\"linker:autoLink\", [\"%s\"]);ga(\"create\", \"%s\", \"auto\", {\"allowLinker\": true});ga(\"send\", \"pageview\");</script>'",
"%",
"(",
"settings",
".",
"DJFRONTEND_GA_SETDOMAINNAME",
",",
"account",
")",
")",
"else",
":",
"return",
"mark_safe",
"(",
"'<script>(function(i,s,o,g,r,a,m){i[\"GoogleAnalyticsObject\"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,\"script\",\"//www.google-analytics.com/analytics.js\",\"ga\");ga(\"create\", \"%s\", \"%s\");ga(\"send\", \"pageview\");</script>'",
"%",
"(",
"account",
",",
"settings",
".",
"DJFRONTEND_GA_SETDOMAINNAME",
")",
")",
"else",
":",
"return",
"mark_safe",
"(",
"'<script>(function(i,s,o,g,r,a,m){i[\"GoogleAnalyticsObject\"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,\"script\",\"//www.google-analytics.com/analytics.js\",\"ga\");ga(\"create\", \"%s\", \"auto\");ga(\"send\", \"pageview\");</script>'",
"%",
"account",
")",
"else",
":",
"return",
"''"
] |
897934d593fade0eb1998f8fadd18c91a89e5b9a
|
test
|
CodeMirrorTextarea.render
|
u"""Render CodeMirrorTextarea
|
codemirror/widgets.py
|
def render(self, name, value, attrs=None):
u"""Render CodeMirrorTextarea"""
if self.js_var_format is not None:
js_var_bit = 'var %s = ' % (self.js_var_format % name)
else:
js_var_bit = ''
output = [super(CodeMirrorTextarea, self).render(name, value, attrs),
'<script type="text/javascript">%sCodeMirror.fromTextArea(document.getElementById(%s), %s);</script>' %
(js_var_bit, '"id_%s"' % name, self.option_json)]
return mark_safe('\n'.join(output))
|
def render(self, name, value, attrs=None):
u"""Render CodeMirrorTextarea"""
if self.js_var_format is not None:
js_var_bit = 'var %s = ' % (self.js_var_format % name)
else:
js_var_bit = ''
output = [super(CodeMirrorTextarea, self).render(name, value, attrs),
'<script type="text/javascript">%sCodeMirror.fromTextArea(document.getElementById(%s), %s);</script>' %
(js_var_bit, '"id_%s"' % name, self.option_json)]
return mark_safe('\n'.join(output))
|
[
"u",
"Render",
"CodeMirrorTextarea"
] |
lambdalisue/django-codemirror-widget
|
python
|
https://github.com/lambdalisue/django-codemirror-widget/blob/e795ade2c0c18b462e729feafa616a3047998b4b/codemirror/widgets.py#L162-L171
|
[
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"self",
".",
"js_var_format",
"is",
"not",
"None",
":",
"js_var_bit",
"=",
"'var %s = '",
"%",
"(",
"self",
".",
"js_var_format",
"%",
"name",
")",
"else",
":",
"js_var_bit",
"=",
"''",
"output",
"=",
"[",
"super",
"(",
"CodeMirrorTextarea",
",",
"self",
")",
".",
"render",
"(",
"name",
",",
"value",
",",
"attrs",
")",
",",
"'<script type=\"text/javascript\">%sCodeMirror.fromTextArea(document.getElementById(%s), %s);</script>'",
"%",
"(",
"js_var_bit",
",",
"'\"id_%s\"'",
"%",
"name",
",",
"self",
".",
"option_json",
")",
"]",
"return",
"mark_safe",
"(",
"'\\n'",
".",
"join",
"(",
"output",
")",
")"
] |
e795ade2c0c18b462e729feafa616a3047998b4b
|
test
|
iter_auth_hashes
|
Generate auth tokens tied to user and specified purpose.
The hash expires at midnight on the minute of now + minutes_valid, such
that when minutes_valid=1 you get *at least* 1 minute to use the token.
|
dddp/accounts/ddp.py
|
def iter_auth_hashes(user, purpose, minutes_valid):
"""
Generate auth tokens tied to user and specified purpose.
The hash expires at midnight on the minute of now + minutes_valid, such
that when minutes_valid=1 you get *at least* 1 minute to use the token.
"""
now = timezone.now().replace(microsecond=0, second=0)
for minute in range(minutes_valid + 1):
yield hashlib.sha1(
'%s:%s:%s:%s:%s' % (
now - datetime.timedelta(minutes=minute),
user.password,
purpose,
user.pk,
settings.SECRET_KEY,
),
).hexdigest()
|
def iter_auth_hashes(user, purpose, minutes_valid):
"""
Generate auth tokens tied to user and specified purpose.
The hash expires at midnight on the minute of now + minutes_valid, such
that when minutes_valid=1 you get *at least* 1 minute to use the token.
"""
now = timezone.now().replace(microsecond=0, second=0)
for minute in range(minutes_valid + 1):
yield hashlib.sha1(
'%s:%s:%s:%s:%s' % (
now - datetime.timedelta(minutes=minute),
user.password,
purpose,
user.pk,
settings.SECRET_KEY,
),
).hexdigest()
|
[
"Generate",
"auth",
"tokens",
"tied",
"to",
"user",
"and",
"specified",
"purpose",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L66-L83
|
[
"def",
"iter_auth_hashes",
"(",
"user",
",",
"purpose",
",",
"minutes_valid",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
".",
"replace",
"(",
"microsecond",
"=",
"0",
",",
"second",
"=",
"0",
")",
"for",
"minute",
"in",
"range",
"(",
"minutes_valid",
"+",
"1",
")",
":",
"yield",
"hashlib",
".",
"sha1",
"(",
"'%s:%s:%s:%s:%s'",
"%",
"(",
"now",
"-",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"minute",
")",
",",
"user",
".",
"password",
",",
"purpose",
",",
"user",
".",
"pk",
",",
"settings",
".",
"SECRET_KEY",
",",
")",
",",
")",
".",
"hexdigest",
"(",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
calc_expiry_time
|
Return specific time an auth_hash will expire.
|
dddp/accounts/ddp.py
|
def calc_expiry_time(minutes_valid):
"""Return specific time an auth_hash will expire."""
return (
timezone.now() + datetime.timedelta(minutes=minutes_valid + 1)
).replace(second=0, microsecond=0)
|
def calc_expiry_time(minutes_valid):
"""Return specific time an auth_hash will expire."""
return (
timezone.now() + datetime.timedelta(minutes=minutes_valid + 1)
).replace(second=0, microsecond=0)
|
[
"Return",
"specific",
"time",
"an",
"auth_hash",
"will",
"expire",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L91-L95
|
[
"def",
"calc_expiry_time",
"(",
"minutes_valid",
")",
":",
"return",
"(",
"timezone",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"minutes_valid",
"+",
"1",
")",
")",
".",
"replace",
"(",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
get_user_token
|
Return login token info for given user.
|
dddp/accounts/ddp.py
|
def get_user_token(user, purpose, minutes_valid):
"""Return login token info for given user."""
token = ''.join(
dumps([
user.get_username(),
get_auth_hash(user, purpose),
]).encode('base64').split('\n')
)
return {
'id': get_meteor_id(user),
'token': token,
'tokenExpires': calc_expiry_time(minutes_valid),
}
|
def get_user_token(user, purpose, minutes_valid):
"""Return login token info for given user."""
token = ''.join(
dumps([
user.get_username(),
get_auth_hash(user, purpose),
]).encode('base64').split('\n')
)
return {
'id': get_meteor_id(user),
'token': token,
'tokenExpires': calc_expiry_time(minutes_valid),
}
|
[
"Return",
"login",
"token",
"info",
"for",
"given",
"user",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L98-L110
|
[
"def",
"get_user_token",
"(",
"user",
",",
"purpose",
",",
"minutes_valid",
")",
":",
"token",
"=",
"''",
".",
"join",
"(",
"dumps",
"(",
"[",
"user",
".",
"get_username",
"(",
")",
",",
"get_auth_hash",
"(",
"user",
",",
"purpose",
")",
",",
"]",
")",
".",
"encode",
"(",
"'base64'",
")",
".",
"split",
"(",
"'\\n'",
")",
")",
"return",
"{",
"'id'",
":",
"get_meteor_id",
"(",
"user",
")",
",",
"'token'",
":",
"token",
",",
"'tokenExpires'",
":",
"calc_expiry_time",
"(",
"minutes_valid",
")",
",",
"}"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Users.serialize
|
Serialize user as per Meteor accounts serialization.
|
dddp/accounts/ddp.py
|
def serialize(self, obj, *args, **kwargs):
"""Serialize user as per Meteor accounts serialization."""
# use default serialization, then modify to suit our needs.
data = super(Users, self).serialize(obj, *args, **kwargs)
# everything that isn't handled explicitly ends up in `profile`
profile = data.pop('fields')
profile.setdefault('name', obj.get_full_name())
fields = data['fields'] = {
'username': obj.get_username(),
'emails': [],
'profile': profile,
'permissions': sorted(self.model.get_all_permissions(obj)),
}
# clear out sensitive data
for sensitive in [
'password',
'user_permissions_ids',
'is_active',
'is_staff',
'is_superuser',
'groups_ids',
]:
profile.pop(sensitive, None)
# createdAt (default is django.contrib.auth.models.User.date_joined)
try:
fields['createdAt'] = profile.pop('date_joined')
except KeyError:
date_joined = getattr(
obj, 'get_date_joined',
lambda: getattr(obj, 'date_joined', None)
)()
if date_joined:
fields['createdAt'] = date_joined
# email (default is django.contrib.auth.models.User.email)
try:
email = profile.pop('email')
except KeyError:
email = getattr(
obj, 'get_email',
lambda: getattr(obj, 'email', None)
)()
if email:
fields['emails'].append({'address': email, 'verified': True})
return data
|
def serialize(self, obj, *args, **kwargs):
"""Serialize user as per Meteor accounts serialization."""
# use default serialization, then modify to suit our needs.
data = super(Users, self).serialize(obj, *args, **kwargs)
# everything that isn't handled explicitly ends up in `profile`
profile = data.pop('fields')
profile.setdefault('name', obj.get_full_name())
fields = data['fields'] = {
'username': obj.get_username(),
'emails': [],
'profile': profile,
'permissions': sorted(self.model.get_all_permissions(obj)),
}
# clear out sensitive data
for sensitive in [
'password',
'user_permissions_ids',
'is_active',
'is_staff',
'is_superuser',
'groups_ids',
]:
profile.pop(sensitive, None)
# createdAt (default is django.contrib.auth.models.User.date_joined)
try:
fields['createdAt'] = profile.pop('date_joined')
except KeyError:
date_joined = getattr(
obj, 'get_date_joined',
lambda: getattr(obj, 'date_joined', None)
)()
if date_joined:
fields['createdAt'] = date_joined
# email (default is django.contrib.auth.models.User.email)
try:
email = profile.pop('email')
except KeyError:
email = getattr(
obj, 'get_email',
lambda: getattr(obj, 'email', None)
)()
if email:
fields['emails'].append({'address': email, 'verified': True})
return data
|
[
"Serialize",
"user",
"as",
"per",
"Meteor",
"accounts",
"serialization",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L125-L173
|
[
"def",
"serialize",
"(",
"self",
",",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# use default serialization, then modify to suit our needs.",
"data",
"=",
"super",
"(",
"Users",
",",
"self",
")",
".",
"serialize",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# everything that isn't handled explicitly ends up in `profile`",
"profile",
"=",
"data",
".",
"pop",
"(",
"'fields'",
")",
"profile",
".",
"setdefault",
"(",
"'name'",
",",
"obj",
".",
"get_full_name",
"(",
")",
")",
"fields",
"=",
"data",
"[",
"'fields'",
"]",
"=",
"{",
"'username'",
":",
"obj",
".",
"get_username",
"(",
")",
",",
"'emails'",
":",
"[",
"]",
",",
"'profile'",
":",
"profile",
",",
"'permissions'",
":",
"sorted",
"(",
"self",
".",
"model",
".",
"get_all_permissions",
"(",
"obj",
")",
")",
",",
"}",
"# clear out sensitive data",
"for",
"sensitive",
"in",
"[",
"'password'",
",",
"'user_permissions_ids'",
",",
"'is_active'",
",",
"'is_staff'",
",",
"'is_superuser'",
",",
"'groups_ids'",
",",
"]",
":",
"profile",
".",
"pop",
"(",
"sensitive",
",",
"None",
")",
"# createdAt (default is django.contrib.auth.models.User.date_joined)",
"try",
":",
"fields",
"[",
"'createdAt'",
"]",
"=",
"profile",
".",
"pop",
"(",
"'date_joined'",
")",
"except",
"KeyError",
":",
"date_joined",
"=",
"getattr",
"(",
"obj",
",",
"'get_date_joined'",
",",
"lambda",
":",
"getattr",
"(",
"obj",
",",
"'date_joined'",
",",
"None",
")",
")",
"(",
")",
"if",
"date_joined",
":",
"fields",
"[",
"'createdAt'",
"]",
"=",
"date_joined",
"# email (default is django.contrib.auth.models.User.email)",
"try",
":",
"email",
"=",
"profile",
".",
"pop",
"(",
"'email'",
")",
"except",
"KeyError",
":",
"email",
"=",
"getattr",
"(",
"obj",
",",
"'get_email'",
",",
"lambda",
":",
"getattr",
"(",
"obj",
",",
"'email'",
",",
"None",
")",
")",
"(",
")",
"if",
"email",
":",
"fields",
"[",
"'emails'",
"]",
".",
"append",
"(",
"{",
"'address'",
":",
"email",
",",
"'verified'",
":",
"True",
"}",
")",
"return",
"data"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Users.deserialize_profile
|
De-serialize user profile fields into concrete model fields.
|
dddp/accounts/ddp.py
|
def deserialize_profile(profile, key_prefix='', pop=False):
"""De-serialize user profile fields into concrete model fields."""
result = {}
if pop:
getter = profile.pop
else:
getter = profile.get
def prefixed(name):
"""Return name prefixed by `key_prefix`."""
return '%s%s' % (key_prefix, name)
for key in profile.keys():
val = getter(key)
if key == prefixed('name'):
result['full_name'] = val
else:
raise MeteorError(400, 'Bad profile key: %r' % key)
return result
|
def deserialize_profile(profile, key_prefix='', pop=False):
"""De-serialize user profile fields into concrete model fields."""
result = {}
if pop:
getter = profile.pop
else:
getter = profile.get
def prefixed(name):
"""Return name prefixed by `key_prefix`."""
return '%s%s' % (key_prefix, name)
for key in profile.keys():
val = getter(key)
if key == prefixed('name'):
result['full_name'] = val
else:
raise MeteorError(400, 'Bad profile key: %r' % key)
return result
|
[
"De",
"-",
"serialize",
"user",
"profile",
"fields",
"into",
"concrete",
"model",
"fields",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L176-L194
|
[
"def",
"deserialize_profile",
"(",
"profile",
",",
"key_prefix",
"=",
"''",
",",
"pop",
"=",
"False",
")",
":",
"result",
"=",
"{",
"}",
"if",
"pop",
":",
"getter",
"=",
"profile",
".",
"pop",
"else",
":",
"getter",
"=",
"profile",
".",
"get",
"def",
"prefixed",
"(",
"name",
")",
":",
"\"\"\"Return name prefixed by `key_prefix`.\"\"\"",
"return",
"'%s%s'",
"%",
"(",
"key_prefix",
",",
"name",
")",
"for",
"key",
"in",
"profile",
".",
"keys",
"(",
")",
":",
"val",
"=",
"getter",
"(",
"key",
")",
"if",
"key",
"==",
"prefixed",
"(",
"'name'",
")",
":",
"result",
"[",
"'full_name'",
"]",
"=",
"val",
"else",
":",
"raise",
"MeteorError",
"(",
"400",
",",
"'Bad profile key: %r'",
"%",
"key",
")",
"return",
"result"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Users.update
|
Update user data.
|
dddp/accounts/ddp.py
|
def update(self, selector, update, options=None):
"""Update user data."""
# we're ignoring the `options` argument at this time
del options
user = get_object(
self.model, selector['_id'],
pk=this.user_id,
)
profile_update = self.deserialize_profile(
update['$set'], key_prefix='profile.', pop=True,
)
if len(update['$set']) != 0:
raise MeteorError(400, 'Invalid update fields: %r')
for key, val in profile_update.items():
setattr(user, key, val)
user.save()
|
def update(self, selector, update, options=None):
"""Update user data."""
# we're ignoring the `options` argument at this time
del options
user = get_object(
self.model, selector['_id'],
pk=this.user_id,
)
profile_update = self.deserialize_profile(
update['$set'], key_prefix='profile.', pop=True,
)
if len(update['$set']) != 0:
raise MeteorError(400, 'Invalid update fields: %r')
for key, val in profile_update.items():
setattr(user, key, val)
user.save()
|
[
"Update",
"user",
"data",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L197-L213
|
[
"def",
"update",
"(",
"self",
",",
"selector",
",",
"update",
",",
"options",
"=",
"None",
")",
":",
"# we're ignoring the `options` argument at this time",
"del",
"options",
"user",
"=",
"get_object",
"(",
"self",
".",
"model",
",",
"selector",
"[",
"'_id'",
"]",
",",
"pk",
"=",
"this",
".",
"user_id",
",",
")",
"profile_update",
"=",
"self",
".",
"deserialize_profile",
"(",
"update",
"[",
"'$set'",
"]",
",",
"key_prefix",
"=",
"'profile.'",
",",
"pop",
"=",
"True",
",",
")",
"if",
"len",
"(",
"update",
"[",
"'$set'",
"]",
")",
"!=",
"0",
":",
"raise",
"MeteorError",
"(",
"400",
",",
"'Invalid update fields: %r'",
")",
"for",
"key",
",",
"val",
"in",
"profile_update",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"user",
",",
"key",
",",
"val",
")",
"user",
".",
"save",
"(",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.user_factory
|
Retrieve the current user (or None) from the database.
|
dddp/accounts/ddp.py
|
def user_factory(self):
"""Retrieve the current user (or None) from the database."""
if this.user_id is None:
return None
return self.user_model.objects.get(pk=this.user_id)
|
def user_factory(self):
"""Retrieve the current user (or None) from the database."""
if this.user_id is None:
return None
return self.user_model.objects.get(pk=this.user_id)
|
[
"Retrieve",
"the",
"current",
"user",
"(",
"or",
"None",
")",
"from",
"the",
"database",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L243-L247
|
[
"def",
"user_factory",
"(",
"self",
")",
":",
"if",
"this",
".",
"user_id",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"user_model",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"this",
".",
"user_id",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.update_subs
|
Update subs to send added/removed for collections with user_rel.
|
dddp/accounts/ddp.py
|
def update_subs(new_user_id):
"""Update subs to send added/removed for collections with user_rel."""
for sub in Subscription.objects.filter(connection=this.ws.connection):
params = loads(sub.params_ejson)
pub = API.get_pub_by_name(sub.publication)
# calculate the querysets prior to update
pre = collections.OrderedDict([
(col, query) for col, query
in API.sub_unique_objects(sub, params, pub)
])
# save the subscription with the updated user_id
sub.user_id = new_user_id
sub.save()
# calculate the querysets after the update
post = collections.OrderedDict([
(col, query) for col, query
in API.sub_unique_objects(sub, params, pub)
])
# first pass, send `added` for objs unique to `post`
for col_post, query in post.items():
try:
qs_pre = pre[col_post]
query = query.exclude(
pk__in=qs_pre.order_by().values('pk'),
)
except KeyError:
# collection not included pre-auth, everything is added.
pass
for obj in query:
this.ws.send(col_post.obj_change_as_msg(obj, ADDED))
# second pass, send `removed` for objs unique to `pre`
for col_pre, query in pre.items():
try:
qs_post = post[col_pre]
query = query.exclude(
pk__in=qs_post.order_by().values('pk'),
)
except KeyError:
# collection not included post-auth, everything is removed.
pass
for obj in query:
this.ws.send(col_pre.obj_change_as_msg(obj, REMOVED))
|
def update_subs(new_user_id):
"""Update subs to send added/removed for collections with user_rel."""
for sub in Subscription.objects.filter(connection=this.ws.connection):
params = loads(sub.params_ejson)
pub = API.get_pub_by_name(sub.publication)
# calculate the querysets prior to update
pre = collections.OrderedDict([
(col, query) for col, query
in API.sub_unique_objects(sub, params, pub)
])
# save the subscription with the updated user_id
sub.user_id = new_user_id
sub.save()
# calculate the querysets after the update
post = collections.OrderedDict([
(col, query) for col, query
in API.sub_unique_objects(sub, params, pub)
])
# first pass, send `added` for objs unique to `post`
for col_post, query in post.items():
try:
qs_pre = pre[col_post]
query = query.exclude(
pk__in=qs_pre.order_by().values('pk'),
)
except KeyError:
# collection not included pre-auth, everything is added.
pass
for obj in query:
this.ws.send(col_post.obj_change_as_msg(obj, ADDED))
# second pass, send `removed` for objs unique to `pre`
for col_pre, query in pre.items():
try:
qs_post = post[col_pre]
query = query.exclude(
pk__in=qs_post.order_by().values('pk'),
)
except KeyError:
# collection not included post-auth, everything is removed.
pass
for obj in query:
this.ws.send(col_pre.obj_change_as_msg(obj, REMOVED))
|
[
"Update",
"subs",
"to",
"send",
"added",
"/",
"removed",
"for",
"collections",
"with",
"user_rel",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L255-L301
|
[
"def",
"update_subs",
"(",
"new_user_id",
")",
":",
"for",
"sub",
"in",
"Subscription",
".",
"objects",
".",
"filter",
"(",
"connection",
"=",
"this",
".",
"ws",
".",
"connection",
")",
":",
"params",
"=",
"loads",
"(",
"sub",
".",
"params_ejson",
")",
"pub",
"=",
"API",
".",
"get_pub_by_name",
"(",
"sub",
".",
"publication",
")",
"# calculate the querysets prior to update",
"pre",
"=",
"collections",
".",
"OrderedDict",
"(",
"[",
"(",
"col",
",",
"query",
")",
"for",
"col",
",",
"query",
"in",
"API",
".",
"sub_unique_objects",
"(",
"sub",
",",
"params",
",",
"pub",
")",
"]",
")",
"# save the subscription with the updated user_id",
"sub",
".",
"user_id",
"=",
"new_user_id",
"sub",
".",
"save",
"(",
")",
"# calculate the querysets after the update",
"post",
"=",
"collections",
".",
"OrderedDict",
"(",
"[",
"(",
"col",
",",
"query",
")",
"for",
"col",
",",
"query",
"in",
"API",
".",
"sub_unique_objects",
"(",
"sub",
",",
"params",
",",
"pub",
")",
"]",
")",
"# first pass, send `added` for objs unique to `post`",
"for",
"col_post",
",",
"query",
"in",
"post",
".",
"items",
"(",
")",
":",
"try",
":",
"qs_pre",
"=",
"pre",
"[",
"col_post",
"]",
"query",
"=",
"query",
".",
"exclude",
"(",
"pk__in",
"=",
"qs_pre",
".",
"order_by",
"(",
")",
".",
"values",
"(",
"'pk'",
")",
",",
")",
"except",
"KeyError",
":",
"# collection not included pre-auth, everything is added.",
"pass",
"for",
"obj",
"in",
"query",
":",
"this",
".",
"ws",
".",
"send",
"(",
"col_post",
".",
"obj_change_as_msg",
"(",
"obj",
",",
"ADDED",
")",
")",
"# second pass, send `removed` for objs unique to `pre`",
"for",
"col_pre",
",",
"query",
"in",
"pre",
".",
"items",
"(",
")",
":",
"try",
":",
"qs_post",
"=",
"post",
"[",
"col_pre",
"]",
"query",
"=",
"query",
".",
"exclude",
"(",
"pk__in",
"=",
"qs_post",
".",
"order_by",
"(",
")",
".",
"values",
"(",
"'pk'",
")",
",",
")",
"except",
"KeyError",
":",
"# collection not included post-auth, everything is removed.",
"pass",
"for",
"obj",
"in",
"query",
":",
"this",
".",
"ws",
".",
"send",
"(",
"col_pre",
".",
"obj_change_as_msg",
"(",
"obj",
",",
"REMOVED",
")",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.auth_failed
|
Consistent fail so we don't provide attackers with valuable info.
|
dddp/accounts/ddp.py
|
def auth_failed(**credentials):
"""Consistent fail so we don't provide attackers with valuable info."""
if credentials:
user_login_failed.send_robust(
sender=__name__,
credentials=auth._clean_credentials(credentials),
)
raise MeteorError(403, 'Authentication failed.')
|
def auth_failed(**credentials):
"""Consistent fail so we don't provide attackers with valuable info."""
if credentials:
user_login_failed.send_robust(
sender=__name__,
credentials=auth._clean_credentials(credentials),
)
raise MeteorError(403, 'Authentication failed.')
|
[
"Consistent",
"fail",
"so",
"we",
"don",
"t",
"provide",
"attackers",
"with",
"valuable",
"info",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L304-L311
|
[
"def",
"auth_failed",
"(",
"*",
"*",
"credentials",
")",
":",
"if",
"credentials",
":",
"user_login_failed",
".",
"send_robust",
"(",
"sender",
"=",
"__name__",
",",
"credentials",
"=",
"auth",
".",
"_clean_credentials",
"(",
"credentials",
")",
",",
")",
"raise",
"MeteorError",
"(",
"403",
",",
"'Authentication failed.'",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.validated_user
|
Resolve and validate auth token, returns user object.
|
dddp/accounts/ddp.py
|
def validated_user(cls, token, purpose, minutes_valid):
"""Resolve and validate auth token, returns user object."""
try:
username, auth_hash = loads(token.decode('base64'))
except (ValueError, Error):
cls.auth_failed(token=token)
try:
user = cls.user_model.objects.get(**{
cls.user_model.USERNAME_FIELD: username,
'is_active': True,
})
user.backend = 'django.contrib.auth.backends.ModelBackend'
except cls.user_model.DoesNotExist:
cls.auth_failed(username=username, token=token)
if auth_hash not in iter_auth_hashes(user, purpose, minutes_valid):
cls.auth_failed(username=username, token=token)
return user
|
def validated_user(cls, token, purpose, minutes_valid):
"""Resolve and validate auth token, returns user object."""
try:
username, auth_hash = loads(token.decode('base64'))
except (ValueError, Error):
cls.auth_failed(token=token)
try:
user = cls.user_model.objects.get(**{
cls.user_model.USERNAME_FIELD: username,
'is_active': True,
})
user.backend = 'django.contrib.auth.backends.ModelBackend'
except cls.user_model.DoesNotExist:
cls.auth_failed(username=username, token=token)
if auth_hash not in iter_auth_hashes(user, purpose, minutes_valid):
cls.auth_failed(username=username, token=token)
return user
|
[
"Resolve",
"and",
"validate",
"auth",
"token",
"returns",
"user",
"object",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L314-L330
|
[
"def",
"validated_user",
"(",
"cls",
",",
"token",
",",
"purpose",
",",
"minutes_valid",
")",
":",
"try",
":",
"username",
",",
"auth_hash",
"=",
"loads",
"(",
"token",
".",
"decode",
"(",
"'base64'",
")",
")",
"except",
"(",
"ValueError",
",",
"Error",
")",
":",
"cls",
".",
"auth_failed",
"(",
"token",
"=",
"token",
")",
"try",
":",
"user",
"=",
"cls",
".",
"user_model",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"{",
"cls",
".",
"user_model",
".",
"USERNAME_FIELD",
":",
"username",
",",
"'is_active'",
":",
"True",
",",
"}",
")",
"user",
".",
"backend",
"=",
"'django.contrib.auth.backends.ModelBackend'",
"except",
"cls",
".",
"user_model",
".",
"DoesNotExist",
":",
"cls",
".",
"auth_failed",
"(",
"username",
"=",
"username",
",",
"token",
"=",
"token",
")",
"if",
"auth_hash",
"not",
"in",
"iter_auth_hashes",
"(",
"user",
",",
"purpose",
",",
"minutes_valid",
")",
":",
"cls",
".",
"auth_failed",
"(",
"username",
"=",
"username",
",",
"token",
"=",
"token",
")",
"return",
"user"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.check_secure
|
Check request, return False if using SSL or local connection.
|
dddp/accounts/ddp.py
|
def check_secure():
"""Check request, return False if using SSL or local connection."""
if this.request.is_secure():
return True # using SSL
elif this.request.META['REMOTE_ADDR'] in [
'localhost',
'127.0.0.1',
]:
return True # localhost
raise MeteorError(403, 'Authentication refused without SSL.')
|
def check_secure():
"""Check request, return False if using SSL or local connection."""
if this.request.is_secure():
return True # using SSL
elif this.request.META['REMOTE_ADDR'] in [
'localhost',
'127.0.0.1',
]:
return True # localhost
raise MeteorError(403, 'Authentication refused without SSL.')
|
[
"Check",
"request",
"return",
"False",
"if",
"using",
"SSL",
"or",
"local",
"connection",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L333-L342
|
[
"def",
"check_secure",
"(",
")",
":",
"if",
"this",
".",
"request",
".",
"is_secure",
"(",
")",
":",
"return",
"True",
"# using SSL",
"elif",
"this",
".",
"request",
".",
"META",
"[",
"'REMOTE_ADDR'",
"]",
"in",
"[",
"'localhost'",
",",
"'127.0.0.1'",
",",
"]",
":",
"return",
"True",
"# localhost",
"raise",
"MeteorError",
"(",
"403",
",",
"'Authentication refused without SSL.'",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.get_username
|
Retrieve username from user selector.
|
dddp/accounts/ddp.py
|
def get_username(self, user):
"""Retrieve username from user selector."""
if isinstance(user, basestring):
return user
elif isinstance(user, dict) and len(user) == 1:
[(key, val)] = user.items()
if key == 'username' or (key == self.user_model.USERNAME_FIELD):
# username provided directly
return val
elif key in ('email', 'emails.address'):
email_field = getattr(self.user_model, 'EMAIL_FIELD', 'email')
if self.user_model.USERNAME_FIELD == email_field:
return val # email is username
# find username by email
return self.user_model.objects.values_list(
self.user_model.USERNAME_FIELD, flat=True,
).get(**{email_field: val})
elif key in ('id', 'pk'):
# find username by primary key (ID)
return self.user_model.objects.values_list(
self.user_model.USERNAME_FIELD, flat=True,
).get(
pk=val,
)
else:
raise MeteorError(400, 'Invalid user lookup: %r' % key)
else:
raise MeteorError(400, 'Invalid user expression: %r' % user)
|
def get_username(self, user):
"""Retrieve username from user selector."""
if isinstance(user, basestring):
return user
elif isinstance(user, dict) and len(user) == 1:
[(key, val)] = user.items()
if key == 'username' or (key == self.user_model.USERNAME_FIELD):
# username provided directly
return val
elif key in ('email', 'emails.address'):
email_field = getattr(self.user_model, 'EMAIL_FIELD', 'email')
if self.user_model.USERNAME_FIELD == email_field:
return val # email is username
# find username by email
return self.user_model.objects.values_list(
self.user_model.USERNAME_FIELD, flat=True,
).get(**{email_field: val})
elif key in ('id', 'pk'):
# find username by primary key (ID)
return self.user_model.objects.values_list(
self.user_model.USERNAME_FIELD, flat=True,
).get(
pk=val,
)
else:
raise MeteorError(400, 'Invalid user lookup: %r' % key)
else:
raise MeteorError(400, 'Invalid user expression: %r' % user)
|
[
"Retrieve",
"username",
"from",
"user",
"selector",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L344-L371
|
[
"def",
"get_username",
"(",
"self",
",",
"user",
")",
":",
"if",
"isinstance",
"(",
"user",
",",
"basestring",
")",
":",
"return",
"user",
"elif",
"isinstance",
"(",
"user",
",",
"dict",
")",
"and",
"len",
"(",
"user",
")",
"==",
"1",
":",
"[",
"(",
"key",
",",
"val",
")",
"]",
"=",
"user",
".",
"items",
"(",
")",
"if",
"key",
"==",
"'username'",
"or",
"(",
"key",
"==",
"self",
".",
"user_model",
".",
"USERNAME_FIELD",
")",
":",
"# username provided directly",
"return",
"val",
"elif",
"key",
"in",
"(",
"'email'",
",",
"'emails.address'",
")",
":",
"email_field",
"=",
"getattr",
"(",
"self",
".",
"user_model",
",",
"'EMAIL_FIELD'",
",",
"'email'",
")",
"if",
"self",
".",
"user_model",
".",
"USERNAME_FIELD",
"==",
"email_field",
":",
"return",
"val",
"# email is username",
"# find username by email",
"return",
"self",
".",
"user_model",
".",
"objects",
".",
"values_list",
"(",
"self",
".",
"user_model",
".",
"USERNAME_FIELD",
",",
"flat",
"=",
"True",
",",
")",
".",
"get",
"(",
"*",
"*",
"{",
"email_field",
":",
"val",
"}",
")",
"elif",
"key",
"in",
"(",
"'id'",
",",
"'pk'",
")",
":",
"# find username by primary key (ID)",
"return",
"self",
".",
"user_model",
".",
"objects",
".",
"values_list",
"(",
"self",
".",
"user_model",
".",
"USERNAME_FIELD",
",",
"flat",
"=",
"True",
",",
")",
".",
"get",
"(",
"pk",
"=",
"val",
",",
")",
"else",
":",
"raise",
"MeteorError",
"(",
"400",
",",
"'Invalid user lookup: %r'",
"%",
"key",
")",
"else",
":",
"raise",
"MeteorError",
"(",
"400",
",",
"'Invalid user expression: %r'",
"%",
"user",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.create_user
|
Register a new user account.
|
dddp/accounts/ddp.py
|
def create_user(self, params):
"""Register a new user account."""
receivers = create_user.send(
sender=__name__,
request=this.request,
params=params,
)
if len(receivers) == 0:
raise NotImplementedError(
'Handler for `create_user` not registered.'
)
user = receivers[0][1]
user = auth.authenticate(
username=user.get_username(), password=params['password'],
)
self.do_login(user)
return get_user_token(
user=user, purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
|
def create_user(self, params):
"""Register a new user account."""
receivers = create_user.send(
sender=__name__,
request=this.request,
params=params,
)
if len(receivers) == 0:
raise NotImplementedError(
'Handler for `create_user` not registered.'
)
user = receivers[0][1]
user = auth.authenticate(
username=user.get_username(), password=params['password'],
)
self.do_login(user)
return get_user_token(
user=user, purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
|
[
"Register",
"a",
"new",
"user",
"account",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L405-L424
|
[
"def",
"create_user",
"(",
"self",
",",
"params",
")",
":",
"receivers",
"=",
"create_user",
".",
"send",
"(",
"sender",
"=",
"__name__",
",",
"request",
"=",
"this",
".",
"request",
",",
"params",
"=",
"params",
",",
")",
"if",
"len",
"(",
"receivers",
")",
"==",
"0",
":",
"raise",
"NotImplementedError",
"(",
"'Handler for `create_user` not registered.'",
")",
"user",
"=",
"receivers",
"[",
"0",
"]",
"[",
"1",
"]",
"user",
"=",
"auth",
".",
"authenticate",
"(",
"username",
"=",
"user",
".",
"get_username",
"(",
")",
",",
"password",
"=",
"params",
"[",
"'password'",
"]",
",",
")",
"self",
".",
"do_login",
"(",
"user",
")",
"return",
"get_user_token",
"(",
"user",
"=",
"user",
",",
"purpose",
"=",
"HashPurpose",
".",
"RESUME_LOGIN",
",",
"minutes_valid",
"=",
"HASH_MINUTES_VALID",
"[",
"HashPurpose",
".",
"RESUME_LOGIN",
"]",
",",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.do_login
|
Login a user.
|
dddp/accounts/ddp.py
|
def do_login(self, user):
"""Login a user."""
this.user_id = user.pk
this.user_ddp_id = get_meteor_id(user)
# silent subscription (sans sub/nosub msg) to LoggedInUser pub
this.user_sub_id = meteor_random_id()
API.do_sub(this.user_sub_id, 'LoggedInUser', silent=True)
self.update_subs(user.pk)
user_logged_in.send(
sender=user.__class__, request=this.request, user=user,
)
|
def do_login(self, user):
"""Login a user."""
this.user_id = user.pk
this.user_ddp_id = get_meteor_id(user)
# silent subscription (sans sub/nosub msg) to LoggedInUser pub
this.user_sub_id = meteor_random_id()
API.do_sub(this.user_sub_id, 'LoggedInUser', silent=True)
self.update_subs(user.pk)
user_logged_in.send(
sender=user.__class__, request=this.request, user=user,
)
|
[
"Login",
"a",
"user",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L426-L436
|
[
"def",
"do_login",
"(",
"self",
",",
"user",
")",
":",
"this",
".",
"user_id",
"=",
"user",
".",
"pk",
"this",
".",
"user_ddp_id",
"=",
"get_meteor_id",
"(",
"user",
")",
"# silent subscription (sans sub/nosub msg) to LoggedInUser pub",
"this",
".",
"user_sub_id",
"=",
"meteor_random_id",
"(",
")",
"API",
".",
"do_sub",
"(",
"this",
".",
"user_sub_id",
",",
"'LoggedInUser'",
",",
"silent",
"=",
"True",
")",
"self",
".",
"update_subs",
"(",
"user",
".",
"pk",
")",
"user_logged_in",
".",
"send",
"(",
"sender",
"=",
"user",
".",
"__class__",
",",
"request",
"=",
"this",
".",
"request",
",",
"user",
"=",
"user",
",",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.do_logout
|
Logout a user.
|
dddp/accounts/ddp.py
|
def do_logout(self):
"""Logout a user."""
# silent unsubscription (sans sub/nosub msg) from LoggedInUser pub
API.do_unsub(this.user_sub_id, silent=True)
del this.user_sub_id
self.update_subs(None)
user_logged_out.send(
sender=self.user_model, request=this.request, user=this.user,
)
this.user_id = None
this.user_ddp_id = None
|
def do_logout(self):
"""Logout a user."""
# silent unsubscription (sans sub/nosub msg) from LoggedInUser pub
API.do_unsub(this.user_sub_id, silent=True)
del this.user_sub_id
self.update_subs(None)
user_logged_out.send(
sender=self.user_model, request=this.request, user=this.user,
)
this.user_id = None
this.user_ddp_id = None
|
[
"Logout",
"a",
"user",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L438-L448
|
[
"def",
"do_logout",
"(",
"self",
")",
":",
"# silent unsubscription (sans sub/nosub msg) from LoggedInUser pub",
"API",
".",
"do_unsub",
"(",
"this",
".",
"user_sub_id",
",",
"silent",
"=",
"True",
")",
"del",
"this",
".",
"user_sub_id",
"self",
".",
"update_subs",
"(",
"None",
")",
"user_logged_out",
".",
"send",
"(",
"sender",
"=",
"self",
".",
"user_model",
",",
"request",
"=",
"this",
".",
"request",
",",
"user",
"=",
"this",
".",
"user",
",",
")",
"this",
".",
"user_id",
"=",
"None",
"this",
".",
"user_ddp_id",
"=",
"None"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.login
|
Login either with resume token or password.
|
dddp/accounts/ddp.py
|
def login(self, params):
"""Login either with resume token or password."""
if 'password' in params:
return self.login_with_password(params)
elif 'resume' in params:
return self.login_with_resume_token(params)
else:
self.auth_failed(**params)
|
def login(self, params):
"""Login either with resume token or password."""
if 'password' in params:
return self.login_with_password(params)
elif 'resume' in params:
return self.login_with_resume_token(params)
else:
self.auth_failed(**params)
|
[
"Login",
"either",
"with",
"resume",
"token",
"or",
"password",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L456-L463
|
[
"def",
"login",
"(",
"self",
",",
"params",
")",
":",
"if",
"'password'",
"in",
"params",
":",
"return",
"self",
".",
"login_with_password",
"(",
"params",
")",
"elif",
"'resume'",
"in",
"params",
":",
"return",
"self",
".",
"login_with_resume_token",
"(",
"params",
")",
"else",
":",
"self",
".",
"auth_failed",
"(",
"*",
"*",
"params",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.login_with_password
|
Authenticate using credentials supplied in params.
|
dddp/accounts/ddp.py
|
def login_with_password(self, params):
"""Authenticate using credentials supplied in params."""
# never allow insecure login
self.check_secure()
username = self.get_username(params['user'])
password = self.get_password(params['password'])
user = auth.authenticate(username=username, password=password)
if user is not None:
# the password verified for the user
if user.is_active:
self.do_login(user)
return get_user_token(
user=user, purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
# Call to `authenticate` couldn't verify the username and password.
# It will have sent the `user_login_failed` signal, no need to pass the
# `username` argument to auth_failed().
self.auth_failed()
|
def login_with_password(self, params):
"""Authenticate using credentials supplied in params."""
# never allow insecure login
self.check_secure()
username = self.get_username(params['user'])
password = self.get_password(params['password'])
user = auth.authenticate(username=username, password=password)
if user is not None:
# the password verified for the user
if user.is_active:
self.do_login(user)
return get_user_token(
user=user, purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
# Call to `authenticate` couldn't verify the username and password.
# It will have sent the `user_login_failed` signal, no need to pass the
# `username` argument to auth_failed().
self.auth_failed()
|
[
"Authenticate",
"using",
"credentials",
"supplied",
"in",
"params",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L465-L486
|
[
"def",
"login_with_password",
"(",
"self",
",",
"params",
")",
":",
"# never allow insecure login",
"self",
".",
"check_secure",
"(",
")",
"username",
"=",
"self",
".",
"get_username",
"(",
"params",
"[",
"'user'",
"]",
")",
"password",
"=",
"self",
".",
"get_password",
"(",
"params",
"[",
"'password'",
"]",
")",
"user",
"=",
"auth",
".",
"authenticate",
"(",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")",
"if",
"user",
"is",
"not",
"None",
":",
"# the password verified for the user",
"if",
"user",
".",
"is_active",
":",
"self",
".",
"do_login",
"(",
"user",
")",
"return",
"get_user_token",
"(",
"user",
"=",
"user",
",",
"purpose",
"=",
"HashPurpose",
".",
"RESUME_LOGIN",
",",
"minutes_valid",
"=",
"HASH_MINUTES_VALID",
"[",
"HashPurpose",
".",
"RESUME_LOGIN",
"]",
",",
")",
"# Call to `authenticate` couldn't verify the username and password.",
"# It will have sent the `user_login_failed` signal, no need to pass the",
"# `username` argument to auth_failed().",
"self",
".",
"auth_failed",
"(",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.login_with_resume_token
|
Login with existing resume token.
Either the token is valid and the user is logged in, or the token is
invalid and a non-specific ValueError("Login failed.") exception is
raised - don't be tempted to give clues to attackers as to why their
logins are invalid!
|
dddp/accounts/ddp.py
|
def login_with_resume_token(self, params):
"""
Login with existing resume token.
Either the token is valid and the user is logged in, or the token is
invalid and a non-specific ValueError("Login failed.") exception is
raised - don't be tempted to give clues to attackers as to why their
logins are invalid!
"""
# never allow insecure login
self.check_secure()
# pull the username and auth_hash from the token
user = self.validated_user(
params['resume'], purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
self.do_login(user)
return get_user_token(
user=user, purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
|
def login_with_resume_token(self, params):
"""
Login with existing resume token.
Either the token is valid and the user is logged in, or the token is
invalid and a non-specific ValueError("Login failed.") exception is
raised - don't be tempted to give clues to attackers as to why their
logins are invalid!
"""
# never allow insecure login
self.check_secure()
# pull the username and auth_hash from the token
user = self.validated_user(
params['resume'], purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
self.do_login(user)
return get_user_token(
user=user, purpose=HashPurpose.RESUME_LOGIN,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.RESUME_LOGIN],
)
|
[
"Login",
"with",
"existing",
"resume",
"token",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L488-L510
|
[
"def",
"login_with_resume_token",
"(",
"self",
",",
"params",
")",
":",
"# never allow insecure login",
"self",
".",
"check_secure",
"(",
")",
"# pull the username and auth_hash from the token",
"user",
"=",
"self",
".",
"validated_user",
"(",
"params",
"[",
"'resume'",
"]",
",",
"purpose",
"=",
"HashPurpose",
".",
"RESUME_LOGIN",
",",
"minutes_valid",
"=",
"HASH_MINUTES_VALID",
"[",
"HashPurpose",
".",
"RESUME_LOGIN",
"]",
",",
")",
"self",
".",
"do_login",
"(",
"user",
")",
"return",
"get_user_token",
"(",
"user",
"=",
"user",
",",
"purpose",
"=",
"HashPurpose",
".",
"RESUME_LOGIN",
",",
"minutes_valid",
"=",
"HASH_MINUTES_VALID",
"[",
"HashPurpose",
".",
"RESUME_LOGIN",
"]",
",",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.change_password
|
Change password.
|
dddp/accounts/ddp.py
|
def change_password(self, old_password, new_password):
"""Change password."""
try:
user = this.user
except self.user_model.DoesNotExist:
self.auth_failed()
user = auth.authenticate(
username=user.get_username(),
password=self.get_password(old_password),
)
if user is None:
self.auth_failed()
else:
user.set_password(self.get_password(new_password))
user.save()
password_changed.send(
sender=__name__,
request=this.request,
user=user,
)
return {"passwordChanged": True}
|
def change_password(self, old_password, new_password):
"""Change password."""
try:
user = this.user
except self.user_model.DoesNotExist:
self.auth_failed()
user = auth.authenticate(
username=user.get_username(),
password=self.get_password(old_password),
)
if user is None:
self.auth_failed()
else:
user.set_password(self.get_password(new_password))
user.save()
password_changed.send(
sender=__name__,
request=this.request,
user=user,
)
return {"passwordChanged": True}
|
[
"Change",
"password",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L513-L533
|
[
"def",
"change_password",
"(",
"self",
",",
"old_password",
",",
"new_password",
")",
":",
"try",
":",
"user",
"=",
"this",
".",
"user",
"except",
"self",
".",
"user_model",
".",
"DoesNotExist",
":",
"self",
".",
"auth_failed",
"(",
")",
"user",
"=",
"auth",
".",
"authenticate",
"(",
"username",
"=",
"user",
".",
"get_username",
"(",
")",
",",
"password",
"=",
"self",
".",
"get_password",
"(",
"old_password",
")",
",",
")",
"if",
"user",
"is",
"None",
":",
"self",
".",
"auth_failed",
"(",
")",
"else",
":",
"user",
".",
"set_password",
"(",
"self",
".",
"get_password",
"(",
"new_password",
")",
")",
"user",
".",
"save",
"(",
")",
"password_changed",
".",
"send",
"(",
"sender",
"=",
"__name__",
",",
"request",
"=",
"this",
".",
"request",
",",
"user",
"=",
"user",
",",
")",
"return",
"{",
"\"passwordChanged\"",
":",
"True",
"}"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.forgot_password
|
Request password reset email.
|
dddp/accounts/ddp.py
|
def forgot_password(self, params):
"""Request password reset email."""
username = self.get_username(params)
try:
user = self.user_model.objects.get(**{
self.user_model.USERNAME_FIELD: username,
})
except self.user_model.DoesNotExist:
self.auth_failed()
minutes_valid = HASH_MINUTES_VALID[HashPurpose.PASSWORD_RESET]
token = get_user_token(
user=user, purpose=HashPurpose.PASSWORD_RESET,
minutes_valid=minutes_valid,
)
forgot_password.send(
sender=__name__,
user=user,
token=token,
request=this.request,
expiry_date=calc_expiry_time(minutes_valid),
)
|
def forgot_password(self, params):
"""Request password reset email."""
username = self.get_username(params)
try:
user = self.user_model.objects.get(**{
self.user_model.USERNAME_FIELD: username,
})
except self.user_model.DoesNotExist:
self.auth_failed()
minutes_valid = HASH_MINUTES_VALID[HashPurpose.PASSWORD_RESET]
token = get_user_token(
user=user, purpose=HashPurpose.PASSWORD_RESET,
minutes_valid=minutes_valid,
)
forgot_password.send(
sender=__name__,
user=user,
token=token,
request=this.request,
expiry_date=calc_expiry_time(minutes_valid),
)
|
[
"Request",
"password",
"reset",
"email",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L536-L558
|
[
"def",
"forgot_password",
"(",
"self",
",",
"params",
")",
":",
"username",
"=",
"self",
".",
"get_username",
"(",
"params",
")",
"try",
":",
"user",
"=",
"self",
".",
"user_model",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"{",
"self",
".",
"user_model",
".",
"USERNAME_FIELD",
":",
"username",
",",
"}",
")",
"except",
"self",
".",
"user_model",
".",
"DoesNotExist",
":",
"self",
".",
"auth_failed",
"(",
")",
"minutes_valid",
"=",
"HASH_MINUTES_VALID",
"[",
"HashPurpose",
".",
"PASSWORD_RESET",
"]",
"token",
"=",
"get_user_token",
"(",
"user",
"=",
"user",
",",
"purpose",
"=",
"HashPurpose",
".",
"PASSWORD_RESET",
",",
"minutes_valid",
"=",
"minutes_valid",
",",
")",
"forgot_password",
".",
"send",
"(",
"sender",
"=",
"__name__",
",",
"user",
"=",
"user",
",",
"token",
"=",
"token",
",",
"request",
"=",
"this",
".",
"request",
",",
"expiry_date",
"=",
"calc_expiry_time",
"(",
"minutes_valid",
")",
",",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Auth.reset_password
|
Reset password using a token received in email then logs user in.
|
dddp/accounts/ddp.py
|
def reset_password(self, token, new_password):
"""Reset password using a token received in email then logs user in."""
user = self.validated_user(
token, purpose=HashPurpose.PASSWORD_RESET,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.PASSWORD_RESET],
)
user.set_password(new_password)
user.save()
self.do_login(user)
return {"userId": this.user_ddp_id}
|
def reset_password(self, token, new_password):
"""Reset password using a token received in email then logs user in."""
user = self.validated_user(
token, purpose=HashPurpose.PASSWORD_RESET,
minutes_valid=HASH_MINUTES_VALID[HashPurpose.PASSWORD_RESET],
)
user.set_password(new_password)
user.save()
self.do_login(user)
return {"userId": this.user_ddp_id}
|
[
"Reset",
"password",
"using",
"a",
"token",
"received",
"in",
"email",
"then",
"logs",
"user",
"in",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L561-L570
|
[
"def",
"reset_password",
"(",
"self",
",",
"token",
",",
"new_password",
")",
":",
"user",
"=",
"self",
".",
"validated_user",
"(",
"token",
",",
"purpose",
"=",
"HashPurpose",
".",
"PASSWORD_RESET",
",",
"minutes_valid",
"=",
"HASH_MINUTES_VALID",
"[",
"HashPurpose",
".",
"PASSWORD_RESET",
"]",
",",
")",
"user",
".",
"set_password",
"(",
"new_password",
")",
"user",
".",
"save",
"(",
")",
"self",
".",
"do_login",
"(",
"user",
")",
"return",
"{",
"\"userId\"",
":",
"this",
".",
"user_ddp_id",
"}"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
dict_merge
|
Recursive dict merge.
Recursively merges dict's. not just simple lft['key'] = rgt['key'], if
both lft and rgt have a key who's value is a dict then dict_merge is
called on both values and the result stored in the returned dictionary.
|
dddp/views.py
|
def dict_merge(lft, rgt):
"""
Recursive dict merge.
Recursively merges dict's. not just simple lft['key'] = rgt['key'], if
both lft and rgt have a key who's value is a dict then dict_merge is
called on both values and the result stored in the returned dictionary.
"""
if not isinstance(rgt, dict):
return rgt
result = deepcopy(lft)
for key, val in rgt.iteritems():
if key in result and isinstance(result[key], dict):
result[key] = dict_merge(result[key], val)
else:
result[key] = deepcopy(val)
return result
|
def dict_merge(lft, rgt):
"""
Recursive dict merge.
Recursively merges dict's. not just simple lft['key'] = rgt['key'], if
both lft and rgt have a key who's value is a dict then dict_merge is
called on both values and the result stored in the returned dictionary.
"""
if not isinstance(rgt, dict):
return rgt
result = deepcopy(lft)
for key, val in rgt.iteritems():
if key in result and isinstance(result[key], dict):
result[key] = dict_merge(result[key], val)
else:
result[key] = deepcopy(val)
return result
|
[
"Recursive",
"dict",
"merge",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/views.py#L18-L34
|
[
"def",
"dict_merge",
"(",
"lft",
",",
"rgt",
")",
":",
"if",
"not",
"isinstance",
"(",
"rgt",
",",
"dict",
")",
":",
"return",
"rgt",
"result",
"=",
"deepcopy",
"(",
"lft",
")",
"for",
"key",
",",
"val",
"in",
"rgt",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"in",
"result",
"and",
"isinstance",
"(",
"result",
"[",
"key",
"]",
",",
"dict",
")",
":",
"result",
"[",
"key",
"]",
"=",
"dict_merge",
"(",
"result",
"[",
"key",
"]",
",",
"val",
")",
"else",
":",
"result",
"[",
"key",
"]",
"=",
"deepcopy",
"(",
"val",
")",
"return",
"result"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
read
|
Read encoded contents from specified path or return default.
|
dddp/views.py
|
def read(path, default=None, encoding='utf8'):
"""Read encoded contents from specified path or return default."""
if not path:
return default
try:
with io.open(path, mode='r', encoding=encoding) as contents:
return contents.read()
except IOError:
if default is not None:
return default
raise
|
def read(path, default=None, encoding='utf8'):
"""Read encoded contents from specified path or return default."""
if not path:
return default
try:
with io.open(path, mode='r', encoding=encoding) as contents:
return contents.read()
except IOError:
if default is not None:
return default
raise
|
[
"Read",
"encoded",
"contents",
"from",
"specified",
"path",
"or",
"return",
"default",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/views.py#L37-L47
|
[
"def",
"read",
"(",
"path",
",",
"default",
"=",
"None",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"if",
"not",
"path",
":",
"return",
"default",
"try",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"contents",
":",
"return",
"contents",
".",
"read",
"(",
")",
"except",
"IOError",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"raise"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
MeteorView.get
|
Return HTML (or other related content) for Meteor.
|
dddp/views.py
|
def get(self, request, path):
"""Return HTML (or other related content) for Meteor."""
if path == 'meteor_runtime_config.js':
config = {
'DDP_DEFAULT_CONNECTION_URL': request.build_absolute_uri('/'),
'PUBLIC_SETTINGS': self.meteor_settings.get('public', {}),
'ROOT_URL': request.build_absolute_uri(
'%s/' % (
self.runtime_config.get('ROOT_URL_PATH_PREFIX', ''),
),
),
'ROOT_URL_PATH_PREFIX': '',
}
# Use HTTPS instead of HTTP if SECURE_SSL_REDIRECT is set
if config['DDP_DEFAULT_CONNECTION_URL'].startswith('http:') \
and settings.SECURE_SSL_REDIRECT:
config['DDP_DEFAULT_CONNECTION_URL'] = 'https:%s' % (
config['DDP_DEFAULT_CONNECTION_URL'].split(':', 1)[1],
)
config.update(self.runtime_config)
return HttpResponse(
'__meteor_runtime_config__ = %s;' % dumps(config),
content_type='text/javascript',
)
try:
file_path, content_type = self.url_map[path]
with open(file_path, 'r') as content:
return HttpResponse(
content.read(),
content_type=content_type,
)
except KeyError:
return HttpResponse(self.html)
|
def get(self, request, path):
"""Return HTML (or other related content) for Meteor."""
if path == 'meteor_runtime_config.js':
config = {
'DDP_DEFAULT_CONNECTION_URL': request.build_absolute_uri('/'),
'PUBLIC_SETTINGS': self.meteor_settings.get('public', {}),
'ROOT_URL': request.build_absolute_uri(
'%s/' % (
self.runtime_config.get('ROOT_URL_PATH_PREFIX', ''),
),
),
'ROOT_URL_PATH_PREFIX': '',
}
# Use HTTPS instead of HTTP if SECURE_SSL_REDIRECT is set
if config['DDP_DEFAULT_CONNECTION_URL'].startswith('http:') \
and settings.SECURE_SSL_REDIRECT:
config['DDP_DEFAULT_CONNECTION_URL'] = 'https:%s' % (
config['DDP_DEFAULT_CONNECTION_URL'].split(':', 1)[1],
)
config.update(self.runtime_config)
return HttpResponse(
'__meteor_runtime_config__ = %s;' % dumps(config),
content_type='text/javascript',
)
try:
file_path, content_type = self.url_map[path]
with open(file_path, 'r') as content:
return HttpResponse(
content.read(),
content_type=content_type,
)
except KeyError:
return HttpResponse(self.html)
|
[
"Return",
"HTML",
"(",
"or",
"other",
"related",
"content",
")",
"for",
"Meteor",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/views.py#L248-L280
|
[
"def",
"get",
"(",
"self",
",",
"request",
",",
"path",
")",
":",
"if",
"path",
"==",
"'meteor_runtime_config.js'",
":",
"config",
"=",
"{",
"'DDP_DEFAULT_CONNECTION_URL'",
":",
"request",
".",
"build_absolute_uri",
"(",
"'/'",
")",
",",
"'PUBLIC_SETTINGS'",
":",
"self",
".",
"meteor_settings",
".",
"get",
"(",
"'public'",
",",
"{",
"}",
")",
",",
"'ROOT_URL'",
":",
"request",
".",
"build_absolute_uri",
"(",
"'%s/'",
"%",
"(",
"self",
".",
"runtime_config",
".",
"get",
"(",
"'ROOT_URL_PATH_PREFIX'",
",",
"''",
")",
",",
")",
",",
")",
",",
"'ROOT_URL_PATH_PREFIX'",
":",
"''",
",",
"}",
"# Use HTTPS instead of HTTP if SECURE_SSL_REDIRECT is set",
"if",
"config",
"[",
"'DDP_DEFAULT_CONNECTION_URL'",
"]",
".",
"startswith",
"(",
"'http:'",
")",
"and",
"settings",
".",
"SECURE_SSL_REDIRECT",
":",
"config",
"[",
"'DDP_DEFAULT_CONNECTION_URL'",
"]",
"=",
"'https:%s'",
"%",
"(",
"config",
"[",
"'DDP_DEFAULT_CONNECTION_URL'",
"]",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"1",
"]",
",",
")",
"config",
".",
"update",
"(",
"self",
".",
"runtime_config",
")",
"return",
"HttpResponse",
"(",
"'__meteor_runtime_config__ = %s;'",
"%",
"dumps",
"(",
"config",
")",
",",
"content_type",
"=",
"'text/javascript'",
",",
")",
"try",
":",
"file_path",
",",
"content_type",
"=",
"self",
".",
"url_map",
"[",
"path",
"]",
"with",
"open",
"(",
"file_path",
",",
"'r'",
")",
"as",
"content",
":",
"return",
"HttpResponse",
"(",
"content",
".",
"read",
"(",
")",
",",
"content_type",
"=",
"content_type",
",",
")",
"except",
"KeyError",
":",
"return",
"HttpResponse",
"(",
"self",
".",
"html",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
get_meteor_id
|
Return an Alea ID for the given object.
|
dddp/models.py
|
def get_meteor_id(obj_or_model, obj_pk=None):
"""Return an Alea ID for the given object."""
if obj_or_model is None:
return None
# Django model._meta is now public API -> pylint: disable=W0212
meta = obj_or_model._meta
model = meta.model
if model is ObjectMapping:
# this doesn't make sense - raise TypeError
raise TypeError("Can't map ObjectMapping instances through self.")
# try getting value of AleaIdField straight from instance if possible
if isinstance(obj_or_model, model):
# obj_or_model is an instance, not a model.
if isinstance(meta.pk, AleaIdField):
return obj_or_model.pk
if obj_pk is None:
# fall back to primary key, but coerce as string type for lookup.
obj_pk = str(obj_or_model.pk)
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique
]
if len(alea_unique_fields) == 1:
# found an AleaIdField with unique=True, assume it's got the value.
aid = alea_unique_fields[0].attname
if isinstance(obj_or_model, model):
val = getattr(obj_or_model, aid)
elif obj_pk is None:
val = None
else:
val = model.objects.values_list(aid, flat=True).get(
pk=obj_pk,
)
if val:
return val
if obj_pk is None:
# bail out if args are (model, pk) but pk is None.
return None
# fallback to using AleaIdField from ObjectMapping model.
content_type = ContentType.objects.get_for_model(model)
try:
return ObjectMapping.objects.values_list(
'meteor_id', flat=True,
).get(
content_type=content_type,
object_id=obj_pk,
)
except ObjectDoesNotExist:
return ObjectMapping.objects.create(
content_type=content_type,
object_id=obj_pk,
meteor_id=meteor_random_id('/collection/%s' % meta),
).meteor_id
|
def get_meteor_id(obj_or_model, obj_pk=None):
"""Return an Alea ID for the given object."""
if obj_or_model is None:
return None
# Django model._meta is now public API -> pylint: disable=W0212
meta = obj_or_model._meta
model = meta.model
if model is ObjectMapping:
# this doesn't make sense - raise TypeError
raise TypeError("Can't map ObjectMapping instances through self.")
# try getting value of AleaIdField straight from instance if possible
if isinstance(obj_or_model, model):
# obj_or_model is an instance, not a model.
if isinstance(meta.pk, AleaIdField):
return obj_or_model.pk
if obj_pk is None:
# fall back to primary key, but coerce as string type for lookup.
obj_pk = str(obj_or_model.pk)
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique
]
if len(alea_unique_fields) == 1:
# found an AleaIdField with unique=True, assume it's got the value.
aid = alea_unique_fields[0].attname
if isinstance(obj_or_model, model):
val = getattr(obj_or_model, aid)
elif obj_pk is None:
val = None
else:
val = model.objects.values_list(aid, flat=True).get(
pk=obj_pk,
)
if val:
return val
if obj_pk is None:
# bail out if args are (model, pk) but pk is None.
return None
# fallback to using AleaIdField from ObjectMapping model.
content_type = ContentType.objects.get_for_model(model)
try:
return ObjectMapping.objects.values_list(
'meteor_id', flat=True,
).get(
content_type=content_type,
object_id=obj_pk,
)
except ObjectDoesNotExist:
return ObjectMapping.objects.create(
content_type=content_type,
object_id=obj_pk,
meteor_id=meteor_random_id('/collection/%s' % meta),
).meteor_id
|
[
"Return",
"an",
"Alea",
"ID",
"for",
"the",
"given",
"object",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/models.py#L20-L76
|
[
"def",
"get_meteor_id",
"(",
"obj_or_model",
",",
"obj_pk",
"=",
"None",
")",
":",
"if",
"obj_or_model",
"is",
"None",
":",
"return",
"None",
"# Django model._meta is now public API -> pylint: disable=W0212",
"meta",
"=",
"obj_or_model",
".",
"_meta",
"model",
"=",
"meta",
".",
"model",
"if",
"model",
"is",
"ObjectMapping",
":",
"# this doesn't make sense - raise TypeError",
"raise",
"TypeError",
"(",
"\"Can't map ObjectMapping instances through self.\"",
")",
"# try getting value of AleaIdField straight from instance if possible",
"if",
"isinstance",
"(",
"obj_or_model",
",",
"model",
")",
":",
"# obj_or_model is an instance, not a model.",
"if",
"isinstance",
"(",
"meta",
".",
"pk",
",",
"AleaIdField",
")",
":",
"return",
"obj_or_model",
".",
"pk",
"if",
"obj_pk",
"is",
"None",
":",
"# fall back to primary key, but coerce as string type for lookup.",
"obj_pk",
"=",
"str",
"(",
"obj_or_model",
".",
"pk",
")",
"alea_unique_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"meta",
".",
"local_fields",
"if",
"isinstance",
"(",
"field",
",",
"AleaIdField",
")",
"and",
"field",
".",
"unique",
"]",
"if",
"len",
"(",
"alea_unique_fields",
")",
"==",
"1",
":",
"# found an AleaIdField with unique=True, assume it's got the value.",
"aid",
"=",
"alea_unique_fields",
"[",
"0",
"]",
".",
"attname",
"if",
"isinstance",
"(",
"obj_or_model",
",",
"model",
")",
":",
"val",
"=",
"getattr",
"(",
"obj_or_model",
",",
"aid",
")",
"elif",
"obj_pk",
"is",
"None",
":",
"val",
"=",
"None",
"else",
":",
"val",
"=",
"model",
".",
"objects",
".",
"values_list",
"(",
"aid",
",",
"flat",
"=",
"True",
")",
".",
"get",
"(",
"pk",
"=",
"obj_pk",
",",
")",
"if",
"val",
":",
"return",
"val",
"if",
"obj_pk",
"is",
"None",
":",
"# bail out if args are (model, pk) but pk is None.",
"return",
"None",
"# fallback to using AleaIdField from ObjectMapping model.",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"try",
":",
"return",
"ObjectMapping",
".",
"objects",
".",
"values_list",
"(",
"'meteor_id'",
",",
"flat",
"=",
"True",
",",
")",
".",
"get",
"(",
"content_type",
"=",
"content_type",
",",
"object_id",
"=",
"obj_pk",
",",
")",
"except",
"ObjectDoesNotExist",
":",
"return",
"ObjectMapping",
".",
"objects",
".",
"create",
"(",
"content_type",
"=",
"content_type",
",",
"object_id",
"=",
"obj_pk",
",",
"meteor_id",
"=",
"meteor_random_id",
"(",
"'/collection/%s'",
"%",
"meta",
")",
",",
")",
".",
"meteor_id"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
get_meteor_ids
|
Return Alea ID mapping for all given ids of specified model.
|
dddp/models.py
|
def get_meteor_ids(model, object_ids):
"""Return Alea ID mapping for all given ids of specified model."""
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
result = collections.OrderedDict(
(str(obj_pk), None)
for obj_pk
in object_ids
)
if isinstance(meta.pk, AleaIdField):
# primary_key is an AleaIdField, use it.
return collections.OrderedDict(
(obj_pk, obj_pk) for obj_pk in object_ids
)
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique and not field.null
]
if len(alea_unique_fields) == 1:
aid = alea_unique_fields[0].name
query = model.objects.filter(
pk__in=object_ids,
).values_list('pk', aid)
else:
content_type = ContentType.objects.get_for_model(model)
query = ObjectMapping.objects.filter(
content_type=content_type,
object_id__in=list(result)
).values_list('object_id', 'meteor_id')
for obj_pk, meteor_id in query:
result[str(obj_pk)] = meteor_id
for obj_pk, meteor_id in result.items():
if meteor_id is None:
result[obj_pk] = get_meteor_id(model, obj_pk)
return result
|
def get_meteor_ids(model, object_ids):
"""Return Alea ID mapping for all given ids of specified model."""
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
result = collections.OrderedDict(
(str(obj_pk), None)
for obj_pk
in object_ids
)
if isinstance(meta.pk, AleaIdField):
# primary_key is an AleaIdField, use it.
return collections.OrderedDict(
(obj_pk, obj_pk) for obj_pk in object_ids
)
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique and not field.null
]
if len(alea_unique_fields) == 1:
aid = alea_unique_fields[0].name
query = model.objects.filter(
pk__in=object_ids,
).values_list('pk', aid)
else:
content_type = ContentType.objects.get_for_model(model)
query = ObjectMapping.objects.filter(
content_type=content_type,
object_id__in=list(result)
).values_list('object_id', 'meteor_id')
for obj_pk, meteor_id in query:
result[str(obj_pk)] = meteor_id
for obj_pk, meteor_id in result.items():
if meteor_id is None:
result[obj_pk] = get_meteor_id(model, obj_pk)
return result
|
[
"Return",
"Alea",
"ID",
"mapping",
"for",
"all",
"given",
"ids",
"of",
"specified",
"model",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/models.py#L80-L115
|
[
"def",
"get_meteor_ids",
"(",
"model",
",",
"object_ids",
")",
":",
"# Django model._meta is now public API -> pylint: disable=W0212",
"meta",
"=",
"model",
".",
"_meta",
"result",
"=",
"collections",
".",
"OrderedDict",
"(",
"(",
"str",
"(",
"obj_pk",
")",
",",
"None",
")",
"for",
"obj_pk",
"in",
"object_ids",
")",
"if",
"isinstance",
"(",
"meta",
".",
"pk",
",",
"AleaIdField",
")",
":",
"# primary_key is an AleaIdField, use it.",
"return",
"collections",
".",
"OrderedDict",
"(",
"(",
"obj_pk",
",",
"obj_pk",
")",
"for",
"obj_pk",
"in",
"object_ids",
")",
"alea_unique_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"meta",
".",
"local_fields",
"if",
"isinstance",
"(",
"field",
",",
"AleaIdField",
")",
"and",
"field",
".",
"unique",
"and",
"not",
"field",
".",
"null",
"]",
"if",
"len",
"(",
"alea_unique_fields",
")",
"==",
"1",
":",
"aid",
"=",
"alea_unique_fields",
"[",
"0",
"]",
".",
"name",
"query",
"=",
"model",
".",
"objects",
".",
"filter",
"(",
"pk__in",
"=",
"object_ids",
",",
")",
".",
"values_list",
"(",
"'pk'",
",",
"aid",
")",
"else",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"query",
"=",
"ObjectMapping",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"content_type",
",",
"object_id__in",
"=",
"list",
"(",
"result",
")",
")",
".",
"values_list",
"(",
"'object_id'",
",",
"'meteor_id'",
")",
"for",
"obj_pk",
",",
"meteor_id",
"in",
"query",
":",
"result",
"[",
"str",
"(",
"obj_pk",
")",
"]",
"=",
"meteor_id",
"for",
"obj_pk",
",",
"meteor_id",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"meteor_id",
"is",
"None",
":",
"result",
"[",
"obj_pk",
"]",
"=",
"get_meteor_id",
"(",
"model",
",",
"obj_pk",
")",
"return",
"result"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
get_object_id
|
Return an object ID for the given meteor_id.
|
dddp/models.py
|
def get_object_id(model, meteor_id):
"""Return an object ID for the given meteor_id."""
if meteor_id is None:
return None
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
if model is ObjectMapping:
# this doesn't make sense - raise TypeError
raise TypeError("Can't map ObjectMapping instances through self.")
if isinstance(meta.pk, AleaIdField):
# meteor_id is the primary key
return meteor_id
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique
]
if len(alea_unique_fields) == 1:
# found an AleaIdField with unique=True, assume it's got the value.
val = model.objects.values_list(
'pk', flat=True,
).get(**{
alea_unique_fields[0].attname: meteor_id,
})
if val:
return val
content_type = ContentType.objects.get_for_model(model)
return ObjectMapping.objects.filter(
content_type=content_type,
meteor_id=meteor_id,
).values_list('object_id', flat=True).get()
|
def get_object_id(model, meteor_id):
"""Return an object ID for the given meteor_id."""
if meteor_id is None:
return None
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
if model is ObjectMapping:
# this doesn't make sense - raise TypeError
raise TypeError("Can't map ObjectMapping instances through self.")
if isinstance(meta.pk, AleaIdField):
# meteor_id is the primary key
return meteor_id
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique
]
if len(alea_unique_fields) == 1:
# found an AleaIdField with unique=True, assume it's got the value.
val = model.objects.values_list(
'pk', flat=True,
).get(**{
alea_unique_fields[0].attname: meteor_id,
})
if val:
return val
content_type = ContentType.objects.get_for_model(model)
return ObjectMapping.objects.filter(
content_type=content_type,
meteor_id=meteor_id,
).values_list('object_id', flat=True).get()
|
[
"Return",
"an",
"object",
"ID",
"for",
"the",
"given",
"meteor_id",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/models.py#L118-L152
|
[
"def",
"get_object_id",
"(",
"model",
",",
"meteor_id",
")",
":",
"if",
"meteor_id",
"is",
"None",
":",
"return",
"None",
"# Django model._meta is now public API -> pylint: disable=W0212",
"meta",
"=",
"model",
".",
"_meta",
"if",
"model",
"is",
"ObjectMapping",
":",
"# this doesn't make sense - raise TypeError",
"raise",
"TypeError",
"(",
"\"Can't map ObjectMapping instances through self.\"",
")",
"if",
"isinstance",
"(",
"meta",
".",
"pk",
",",
"AleaIdField",
")",
":",
"# meteor_id is the primary key",
"return",
"meteor_id",
"alea_unique_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"meta",
".",
"local_fields",
"if",
"isinstance",
"(",
"field",
",",
"AleaIdField",
")",
"and",
"field",
".",
"unique",
"]",
"if",
"len",
"(",
"alea_unique_fields",
")",
"==",
"1",
":",
"# found an AleaIdField with unique=True, assume it's got the value.",
"val",
"=",
"model",
".",
"objects",
".",
"values_list",
"(",
"'pk'",
",",
"flat",
"=",
"True",
",",
")",
".",
"get",
"(",
"*",
"*",
"{",
"alea_unique_fields",
"[",
"0",
"]",
".",
"attname",
":",
"meteor_id",
",",
"}",
")",
"if",
"val",
":",
"return",
"val",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"return",
"ObjectMapping",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"content_type",
",",
"meteor_id",
"=",
"meteor_id",
",",
")",
".",
"values_list",
"(",
"'object_id'",
",",
"flat",
"=",
"True",
")",
".",
"get",
"(",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
get_object_ids
|
Return all object IDs for the given meteor_ids.
|
dddp/models.py
|
def get_object_ids(model, meteor_ids):
"""Return all object IDs for the given meteor_ids."""
if model is ObjectMapping:
# this doesn't make sense - raise TypeError
raise TypeError("Can't map ObjectMapping instances through self.")
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique and not field.null
]
result = collections.OrderedDict(
(str(meteor_id), None)
for meteor_id
in meteor_ids
)
if len(alea_unique_fields) == 1:
aid = alea_unique_fields[0].name
query = model.objects.filter(**{
'%s__in' % aid: meteor_ids,
}).values_list(aid, 'pk')
else:
content_type = ContentType.objects.get_for_model(model)
query = ObjectMapping.objects.filter(
content_type=content_type,
meteor_id__in=meteor_ids,
).values_list('meteor_id', 'object_id')
for meteor_id, object_id in query:
result[meteor_id] = object_id
return result
|
def get_object_ids(model, meteor_ids):
"""Return all object IDs for the given meteor_ids."""
if model is ObjectMapping:
# this doesn't make sense - raise TypeError
raise TypeError("Can't map ObjectMapping instances through self.")
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique and not field.null
]
result = collections.OrderedDict(
(str(meteor_id), None)
for meteor_id
in meteor_ids
)
if len(alea_unique_fields) == 1:
aid = alea_unique_fields[0].name
query = model.objects.filter(**{
'%s__in' % aid: meteor_ids,
}).values_list(aid, 'pk')
else:
content_type = ContentType.objects.get_for_model(model)
query = ObjectMapping.objects.filter(
content_type=content_type,
meteor_id__in=meteor_ids,
).values_list('meteor_id', 'object_id')
for meteor_id, object_id in query:
result[meteor_id] = object_id
return result
|
[
"Return",
"all",
"object",
"IDs",
"for",
"the",
"given",
"meteor_ids",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/models.py#L155-L185
|
[
"def",
"get_object_ids",
"(",
"model",
",",
"meteor_ids",
")",
":",
"if",
"model",
"is",
"ObjectMapping",
":",
"# this doesn't make sense - raise TypeError",
"raise",
"TypeError",
"(",
"\"Can't map ObjectMapping instances through self.\"",
")",
"# Django model._meta is now public API -> pylint: disable=W0212",
"meta",
"=",
"model",
".",
"_meta",
"alea_unique_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"meta",
".",
"local_fields",
"if",
"isinstance",
"(",
"field",
",",
"AleaIdField",
")",
"and",
"field",
".",
"unique",
"and",
"not",
"field",
".",
"null",
"]",
"result",
"=",
"collections",
".",
"OrderedDict",
"(",
"(",
"str",
"(",
"meteor_id",
")",
",",
"None",
")",
"for",
"meteor_id",
"in",
"meteor_ids",
")",
"if",
"len",
"(",
"alea_unique_fields",
")",
"==",
"1",
":",
"aid",
"=",
"alea_unique_fields",
"[",
"0",
"]",
".",
"name",
"query",
"=",
"model",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"{",
"'%s__in'",
"%",
"aid",
":",
"meteor_ids",
",",
"}",
")",
".",
"values_list",
"(",
"aid",
",",
"'pk'",
")",
"else",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"query",
"=",
"ObjectMapping",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"content_type",
",",
"meteor_id__in",
"=",
"meteor_ids",
",",
")",
".",
"values_list",
"(",
"'meteor_id'",
",",
"'object_id'",
")",
"for",
"meteor_id",
",",
"object_id",
"in",
"query",
":",
"result",
"[",
"meteor_id",
"]",
"=",
"object_id",
"return",
"result"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
get_object
|
Return an object for the given meteor_id.
|
dddp/models.py
|
def get_object(model, meteor_id, *args, **kwargs):
"""Return an object for the given meteor_id."""
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
if isinstance(meta.pk, AleaIdField):
# meteor_id is the primary key
return model.objects.filter(*args, **kwargs).get(pk=meteor_id)
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique and not field.null
]
if len(alea_unique_fields) == 1:
return model.objects.filter(*args, **kwargs).get(**{
alea_unique_fields[0].name: meteor_id,
})
return model.objects.filter(*args, **kwargs).get(
pk=get_object_id(model, meteor_id),
)
|
def get_object(model, meteor_id, *args, **kwargs):
"""Return an object for the given meteor_id."""
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
if isinstance(meta.pk, AleaIdField):
# meteor_id is the primary key
return model.objects.filter(*args, **kwargs).get(pk=meteor_id)
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaIdField) and field.unique and not field.null
]
if len(alea_unique_fields) == 1:
return model.objects.filter(*args, **kwargs).get(**{
alea_unique_fields[0].name: meteor_id,
})
return model.objects.filter(*args, **kwargs).get(
pk=get_object_id(model, meteor_id),
)
|
[
"Return",
"an",
"object",
"for",
"the",
"given",
"meteor_id",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/models.py#L188-L208
|
[
"def",
"get_object",
"(",
"model",
",",
"meteor_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Django model._meta is now public API -> pylint: disable=W0212",
"meta",
"=",
"model",
".",
"_meta",
"if",
"isinstance",
"(",
"meta",
".",
"pk",
",",
"AleaIdField",
")",
":",
"# meteor_id is the primary key",
"return",
"model",
".",
"objects",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"pk",
"=",
"meteor_id",
")",
"alea_unique_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"meta",
".",
"local_fields",
"if",
"isinstance",
"(",
"field",
",",
"AleaIdField",
")",
"and",
"field",
".",
"unique",
"and",
"not",
"field",
".",
"null",
"]",
"if",
"len",
"(",
"alea_unique_fields",
")",
"==",
"1",
":",
"return",
"model",
".",
"objects",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"*",
"*",
"{",
"alea_unique_fields",
"[",
"0",
"]",
".",
"name",
":",
"meteor_id",
",",
"}",
")",
"return",
"model",
".",
"objects",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"get",
"(",
"pk",
"=",
"get_object_id",
"(",
"model",
",",
"meteor_id",
")",
",",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
AleaIdField.get_pk_value_on_save
|
Generate ID if required.
|
dddp/models.py
|
def get_pk_value_on_save(self, instance):
"""Generate ID if required."""
value = super(AleaIdField, self).get_pk_value_on_save(instance)
if not value:
value = self.get_seeded_value(instance)
return value
|
def get_pk_value_on_save(self, instance):
"""Generate ID if required."""
value = super(AleaIdField, self).get_pk_value_on_save(instance)
if not value:
value = self.get_seeded_value(instance)
return value
|
[
"Generate",
"ID",
"if",
"required",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/models.py#L235-L240
|
[
"def",
"get_pk_value_on_save",
"(",
"self",
",",
"instance",
")",
":",
"value",
"=",
"super",
"(",
"AleaIdField",
",",
"self",
")",
".",
"get_pk_value_on_save",
"(",
"instance",
")",
"if",
"not",
"value",
":",
"value",
"=",
"self",
".",
"get_seeded_value",
"(",
"instance",
")",
"return",
"value"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
AleaIdField.pre_save
|
Generate ID if required.
|
dddp/models.py
|
def pre_save(self, model_instance, add):
"""Generate ID if required."""
value = super(AleaIdField, self).pre_save(model_instance, add)
if (not value) and self.default in (meteor_random_id, NOT_PROVIDED):
value = self.get_seeded_value(model_instance)
setattr(model_instance, self.attname, value)
return value
|
def pre_save(self, model_instance, add):
"""Generate ID if required."""
value = super(AleaIdField, self).pre_save(model_instance, add)
if (not value) and self.default in (meteor_random_id, NOT_PROVIDED):
value = self.get_seeded_value(model_instance)
setattr(model_instance, self.attname, value)
return value
|
[
"Generate",
"ID",
"if",
"required",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/models.py#L242-L248
|
[
"def",
"pre_save",
"(",
"self",
",",
"model_instance",
",",
"add",
")",
":",
"value",
"=",
"super",
"(",
"AleaIdField",
",",
"self",
")",
".",
"pre_save",
"(",
"model_instance",
",",
"add",
")",
"if",
"(",
"not",
"value",
")",
"and",
"self",
".",
"default",
"in",
"(",
"meteor_random_id",
",",
"NOT_PROVIDED",
")",
":",
"value",
"=",
"self",
".",
"get_seeded_value",
"(",
"model_instance",
")",
"setattr",
"(",
"model_instance",
",",
"self",
".",
"attname",
",",
"value",
")",
"return",
"value"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
set_default_forwards
|
Set default value for AleaIdField.
|
dddp/migrations/__init__.py
|
def set_default_forwards(app_name, operation, apps, schema_editor):
"""Set default value for AleaIdField."""
model = apps.get_model(app_name, operation.model_name)
for obj_pk in model.objects.values_list('pk', flat=True):
model.objects.filter(pk=obj_pk).update(**{
operation.name: get_meteor_id(model, obj_pk),
})
|
def set_default_forwards(app_name, operation, apps, schema_editor):
"""Set default value for AleaIdField."""
model = apps.get_model(app_name, operation.model_name)
for obj_pk in model.objects.values_list('pk', flat=True):
model.objects.filter(pk=obj_pk).update(**{
operation.name: get_meteor_id(model, obj_pk),
})
|
[
"Set",
"default",
"value",
"for",
"AleaIdField",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/migrations/__init__.py#L43-L49
|
[
"def",
"set_default_forwards",
"(",
"app_name",
",",
"operation",
",",
"apps",
",",
"schema_editor",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"app_name",
",",
"operation",
".",
"model_name",
")",
"for",
"obj_pk",
"in",
"model",
".",
"objects",
".",
"values_list",
"(",
"'pk'",
",",
"flat",
"=",
"True",
")",
":",
"model",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"obj_pk",
")",
".",
"update",
"(",
"*",
"*",
"{",
"operation",
".",
"name",
":",
"get_meteor_id",
"(",
"model",
",",
"obj_pk",
")",
",",
"}",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
set_default_reverse
|
Unset default value for AleaIdField.
|
dddp/migrations/__init__.py
|
def set_default_reverse(app_name, operation, apps, schema_editor):
"""Unset default value for AleaIdField."""
model = apps.get_model(app_name, operation.model_name)
for obj_pk in model.objects.values_list('pk', flat=True):
get_meteor_id(model, obj_pk)
|
def set_default_reverse(app_name, operation, apps, schema_editor):
"""Unset default value for AleaIdField."""
model = apps.get_model(app_name, operation.model_name)
for obj_pk in model.objects.values_list('pk', flat=True):
get_meteor_id(model, obj_pk)
|
[
"Unset",
"default",
"value",
"for",
"AleaIdField",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/migrations/__init__.py#L52-L56
|
[
"def",
"set_default_reverse",
"(",
"app_name",
",",
"operation",
",",
"apps",
",",
"schema_editor",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"app_name",
",",
"operation",
".",
"model_name",
")",
"for",
"obj_pk",
"in",
"model",
".",
"objects",
".",
"values_list",
"(",
"'pk'",
",",
"flat",
"=",
"True",
")",
":",
"get_meteor_id",
"(",
"model",
",",
"obj_pk",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
TruncateOperation.truncate
|
Truncate tables.
|
dddp/migrations/__init__.py
|
def truncate(self, app_label, schema_editor, models):
"""Truncate tables."""
for model_name in models:
model = '%s_%s' % (app_label, model_name)
schema_editor.execute(
'TRUNCATE TABLE %s RESTART IDENTITY CASCADE' % (
model.lower(),
),
)
|
def truncate(self, app_label, schema_editor, models):
"""Truncate tables."""
for model_name in models:
model = '%s_%s' % (app_label, model_name)
schema_editor.execute(
'TRUNCATE TABLE %s RESTART IDENTITY CASCADE' % (
model.lower(),
),
)
|
[
"Truncate",
"tables",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/migrations/__init__.py#L16-L24
|
[
"def",
"truncate",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"models",
")",
":",
"for",
"model_name",
"in",
"models",
":",
"model",
"=",
"'%s_%s'",
"%",
"(",
"app_label",
",",
"model_name",
")",
"schema_editor",
".",
"execute",
"(",
"'TRUNCATE TABLE %s RESTART IDENTITY CASCADE'",
"%",
"(",
"model",
".",
"lower",
"(",
")",
",",
")",
",",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
TruncateOperation.database_forwards
|
Use schema_editor to apply any forward changes.
|
dddp/migrations/__init__.py
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Use schema_editor to apply any forward changes."""
self.truncate(app_label, schema_editor, self.truncate_forwards)
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Use schema_editor to apply any forward changes."""
self.truncate(app_label, schema_editor, self.truncate_forwards)
|
[
"Use",
"schema_editor",
"to",
"apply",
"any",
"forward",
"changes",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/migrations/__init__.py#L30-L32
|
[
"def",
"database_forwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"self",
".",
"truncate",
"(",
"app_label",
",",
"schema_editor",
",",
"self",
".",
"truncate_forwards",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
TruncateOperation.database_backwards
|
Use schema_editor to apply any reverse changes.
|
dddp/migrations/__init__.py
|
def database_backwards(self, app_label, schema_editor, from_state, to_state):
"""Use schema_editor to apply any reverse changes."""
self.truncate(app_label, schema_editor, self.truncate_backwards)
|
def database_backwards(self, app_label, schema_editor, from_state, to_state):
"""Use schema_editor to apply any reverse changes."""
self.truncate(app_label, schema_editor, self.truncate_backwards)
|
[
"Use",
"schema_editor",
"to",
"apply",
"any",
"reverse",
"changes",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/migrations/__init__.py#L34-L36
|
[
"def",
"database_backwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"self",
".",
"truncate",
"(",
"app_label",
",",
"schema_editor",
",",
"self",
".",
"truncate_backwards",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
build_meteor.initialize_options
|
Set command option defaults.
|
setup.py
|
def initialize_options(self):
"""Set command option defaults."""
setuptools.command.build_py.build_py.initialize_options(self)
self.meteor = 'meteor'
self.meteor_debug = False
self.build_lib = None
self.package_dir = None
self.meteor_builds = []
self.no_prune_npm = None
self.inplace = True
|
def initialize_options(self):
"""Set command option defaults."""
setuptools.command.build_py.build_py.initialize_options(self)
self.meteor = 'meteor'
self.meteor_debug = False
self.build_lib = None
self.package_dir = None
self.meteor_builds = []
self.no_prune_npm = None
self.inplace = True
|
[
"Set",
"command",
"option",
"defaults",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/setup.py#L48-L57
|
[
"def",
"initialize_options",
"(",
"self",
")",
":",
"setuptools",
".",
"command",
".",
"build_py",
".",
"build_py",
".",
"initialize_options",
"(",
"self",
")",
"self",
".",
"meteor",
"=",
"'meteor'",
"self",
".",
"meteor_debug",
"=",
"False",
"self",
".",
"build_lib",
"=",
"None",
"self",
".",
"package_dir",
"=",
"None",
"self",
".",
"meteor_builds",
"=",
"[",
"]",
"self",
".",
"no_prune_npm",
"=",
"None",
"self",
".",
"inplace",
"=",
"True"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
build_meteor.finalize_options
|
Update command options.
|
setup.py
|
def finalize_options(self):
"""Update command options."""
# Get all the information we need to install pure Python modules
# from the umbrella 'install' command -- build (source) directory,
# install (target) directory, and whether to compile .py files.
self.set_undefined_options(
'build',
('build_lib', 'build_lib'),
)
self.set_undefined_options(
'build_py',
('package_dir', 'package_dir'),
)
setuptools.command.build_py.build_py.finalize_options(self)
|
def finalize_options(self):
"""Update command options."""
# Get all the information we need to install pure Python modules
# from the umbrella 'install' command -- build (source) directory,
# install (target) directory, and whether to compile .py files.
self.set_undefined_options(
'build',
('build_lib', 'build_lib'),
)
self.set_undefined_options(
'build_py',
('package_dir', 'package_dir'),
)
setuptools.command.build_py.build_py.finalize_options(self)
|
[
"Update",
"command",
"options",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/setup.py#L59-L72
|
[
"def",
"finalize_options",
"(",
"self",
")",
":",
"# Get all the information we need to install pure Python modules",
"# from the umbrella 'install' command -- build (source) directory,",
"# install (target) directory, and whether to compile .py files.",
"self",
".",
"set_undefined_options",
"(",
"'build'",
",",
"(",
"'build_lib'",
",",
"'build_lib'",
")",
",",
")",
"self",
".",
"set_undefined_options",
"(",
"'build_py'",
",",
"(",
"'package_dir'",
",",
"'package_dir'",
")",
",",
")",
"setuptools",
".",
"command",
".",
"build_py",
".",
"build_py",
".",
"finalize_options",
"(",
"self",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
build_meteor.run
|
Peform build.
|
setup.py
|
def run(self):
"""Peform build."""
for (package, source, target, extra_args) in self.meteor_builds:
src_dir = self.get_package_dir(package)
# convert UNIX-style paths to directory names
project_dir = self.path_to_dir(src_dir, source)
target_dir = self.path_to_dir(src_dir, target)
output_dir = self.path_to_dir(
os.path.abspath(SETUP_DIR if self.inplace else self.build_lib),
target_dir,
)
# construct command line.
cmdline = [self.meteor, 'build', '--directory', output_dir]
no_prune_npm = self.no_prune_npm
if extra_args[:1] == ['--no-prune-npm']:
no_prune_npm = True
extra_args[:1] = []
if self.meteor_debug and '--debug' not in cmdline:
cmdline.append('--debug')
cmdline.extend(extra_args)
# execute command
log.info(
'building meteor app %r (%s)', project_dir, ' '.join(cmdline),
)
subprocess.check_call(cmdline, cwd=project_dir)
if not no_prune_npm:
# django-ddp doesn't use bundle/programs/server/npm cruft
npm_build_dir = os.path.join(
output_dir, 'bundle', 'programs', 'server', 'npm',
)
log.info('pruning meteor npm build %r', npm_build_dir)
shutil.rmtree(npm_build_dir)
|
def run(self):
"""Peform build."""
for (package, source, target, extra_args) in self.meteor_builds:
src_dir = self.get_package_dir(package)
# convert UNIX-style paths to directory names
project_dir = self.path_to_dir(src_dir, source)
target_dir = self.path_to_dir(src_dir, target)
output_dir = self.path_to_dir(
os.path.abspath(SETUP_DIR if self.inplace else self.build_lib),
target_dir,
)
# construct command line.
cmdline = [self.meteor, 'build', '--directory', output_dir]
no_prune_npm = self.no_prune_npm
if extra_args[:1] == ['--no-prune-npm']:
no_prune_npm = True
extra_args[:1] = []
if self.meteor_debug and '--debug' not in cmdline:
cmdline.append('--debug')
cmdline.extend(extra_args)
# execute command
log.info(
'building meteor app %r (%s)', project_dir, ' '.join(cmdline),
)
subprocess.check_call(cmdline, cwd=project_dir)
if not no_prune_npm:
# django-ddp doesn't use bundle/programs/server/npm cruft
npm_build_dir = os.path.join(
output_dir, 'bundle', 'programs', 'server', 'npm',
)
log.info('pruning meteor npm build %r', npm_build_dir)
shutil.rmtree(npm_build_dir)
|
[
"Peform",
"build",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/setup.py#L89-L120
|
[
"def",
"run",
"(",
"self",
")",
":",
"for",
"(",
"package",
",",
"source",
",",
"target",
",",
"extra_args",
")",
"in",
"self",
".",
"meteor_builds",
":",
"src_dir",
"=",
"self",
".",
"get_package_dir",
"(",
"package",
")",
"# convert UNIX-style paths to directory names",
"project_dir",
"=",
"self",
".",
"path_to_dir",
"(",
"src_dir",
",",
"source",
")",
"target_dir",
"=",
"self",
".",
"path_to_dir",
"(",
"src_dir",
",",
"target",
")",
"output_dir",
"=",
"self",
".",
"path_to_dir",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"SETUP_DIR",
"if",
"self",
".",
"inplace",
"else",
"self",
".",
"build_lib",
")",
",",
"target_dir",
",",
")",
"# construct command line.",
"cmdline",
"=",
"[",
"self",
".",
"meteor",
",",
"'build'",
",",
"'--directory'",
",",
"output_dir",
"]",
"no_prune_npm",
"=",
"self",
".",
"no_prune_npm",
"if",
"extra_args",
"[",
":",
"1",
"]",
"==",
"[",
"'--no-prune-npm'",
"]",
":",
"no_prune_npm",
"=",
"True",
"extra_args",
"[",
":",
"1",
"]",
"=",
"[",
"]",
"if",
"self",
".",
"meteor_debug",
"and",
"'--debug'",
"not",
"in",
"cmdline",
":",
"cmdline",
".",
"append",
"(",
"'--debug'",
")",
"cmdline",
".",
"extend",
"(",
"extra_args",
")",
"# execute command",
"log",
".",
"info",
"(",
"'building meteor app %r (%s)'",
",",
"project_dir",
",",
"' '",
".",
"join",
"(",
"cmdline",
")",
",",
")",
"subprocess",
".",
"check_call",
"(",
"cmdline",
",",
"cwd",
"=",
"project_dir",
")",
"if",
"not",
"no_prune_npm",
":",
"# django-ddp doesn't use bundle/programs/server/npm cruft",
"npm_build_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'bundle'",
",",
"'programs'",
",",
"'server'",
",",
"'npm'",
",",
")",
"log",
".",
"info",
"(",
"'pruning meteor npm build %r'",
",",
"npm_build_dir",
")",
"shutil",
".",
"rmtree",
"(",
"npm_build_dir",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
build_meteor.path_to_dir
|
Convert a UNIX-style path into platform specific directory spec.
|
setup.py
|
def path_to_dir(*path_args):
"""Convert a UNIX-style path into platform specific directory spec."""
return os.path.join(
*list(path_args[:-1]) + path_args[-1].split(posixpath.sep)
)
|
def path_to_dir(*path_args):
"""Convert a UNIX-style path into platform specific directory spec."""
return os.path.join(
*list(path_args[:-1]) + path_args[-1].split(posixpath.sep)
)
|
[
"Convert",
"a",
"UNIX",
"-",
"style",
"path",
"into",
"platform",
"specific",
"directory",
"spec",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/setup.py#L123-L127
|
[
"def",
"path_to_dir",
"(",
"*",
"path_args",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"list",
"(",
"path_args",
"[",
":",
"-",
"1",
"]",
")",
"+",
"path_args",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"posixpath",
".",
"sep",
")",
")"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Alea.seed
|
Seed internal state from supplied values.
|
dddp/alea.py
|
def seed(self, values):
"""Seed internal state from supplied values."""
if not values:
# Meteor uses epoch seconds as the seed if no args supplied, we use
# a much more secure seed by default to avoid hash collisions.
seed_ids = [int, str, random, self, values, self.__class__]
random.shuffle(seed_ids)
values = list(map(id, seed_ids)) + [time.time(), os.urandom(512)]
mash = Mash()
self.c = 1
self.s0 = mash(' ')
self.s1 = mash(' ')
self.s2 = mash(' ')
for val in values:
self.s0 -= mash(val)
if self.s0 < 0:
self.s0 += 1
self.s1 -= mash(val)
if self.s1 < 0:
self.s1 += 1
self.s2 -= mash(val)
if self.s2 < 0:
self.s2 += 1
|
def seed(self, values):
"""Seed internal state from supplied values."""
if not values:
# Meteor uses epoch seconds as the seed if no args supplied, we use
# a much more secure seed by default to avoid hash collisions.
seed_ids = [int, str, random, self, values, self.__class__]
random.shuffle(seed_ids)
values = list(map(id, seed_ids)) + [time.time(), os.urandom(512)]
mash = Mash()
self.c = 1
self.s0 = mash(' ')
self.s1 = mash(' ')
self.s2 = mash(' ')
for val in values:
self.s0 -= mash(val)
if self.s0 < 0:
self.s0 += 1
self.s1 -= mash(val)
if self.s1 < 0:
self.s1 += 1
self.s2 -= mash(val)
if self.s2 < 0:
self.s2 += 1
|
[
"Seed",
"internal",
"state",
"from",
"supplied",
"values",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/alea.py#L110-L134
|
[
"def",
"seed",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"values",
":",
"# Meteor uses epoch seconds as the seed if no args supplied, we use",
"# a much more secure seed by default to avoid hash collisions.",
"seed_ids",
"=",
"[",
"int",
",",
"str",
",",
"random",
",",
"self",
",",
"values",
",",
"self",
".",
"__class__",
"]",
"random",
".",
"shuffle",
"(",
"seed_ids",
")",
"values",
"=",
"list",
"(",
"map",
"(",
"id",
",",
"seed_ids",
")",
")",
"+",
"[",
"time",
".",
"time",
"(",
")",
",",
"os",
".",
"urandom",
"(",
"512",
")",
"]",
"mash",
"=",
"Mash",
"(",
")",
"self",
".",
"c",
"=",
"1",
"self",
".",
"s0",
"=",
"mash",
"(",
"' '",
")",
"self",
".",
"s1",
"=",
"mash",
"(",
"' '",
")",
"self",
".",
"s2",
"=",
"mash",
"(",
"' '",
")",
"for",
"val",
"in",
"values",
":",
"self",
".",
"s0",
"-=",
"mash",
"(",
"val",
")",
"if",
"self",
".",
"s0",
"<",
"0",
":",
"self",
".",
"s0",
"+=",
"1",
"self",
".",
"s1",
"-=",
"mash",
"(",
"val",
")",
"if",
"self",
".",
"s1",
"<",
"0",
":",
"self",
".",
"s1",
"+=",
"1",
"self",
".",
"s2",
"-=",
"mash",
"(",
"val",
")",
"if",
"self",
".",
"s2",
"<",
"0",
":",
"self",
".",
"s2",
"+=",
"1"
] |
1e1954b06fe140346acea43582515991685e4e01
|
test
|
Alea.state
|
Return internal state, useful for testing.
|
dddp/alea.py
|
def state(self):
"""Return internal state, useful for testing."""
return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2}
|
def state(self):
"""Return internal state, useful for testing."""
return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2}
|
[
"Return",
"internal",
"state",
"useful",
"for",
"testing",
"."
] |
jazzband/django-ddp
|
python
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/alea.py#L137-L139
|
[
"def",
"state",
"(",
"self",
")",
":",
"return",
"{",
"'c'",
":",
"self",
".",
"c",
",",
"'s0'",
":",
"self",
".",
"s0",
",",
"'s1'",
":",
"self",
".",
"s1",
",",
"'s2'",
":",
"self",
".",
"s2",
"}"
] |
1e1954b06fe140346acea43582515991685e4e01
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.