INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns a tuple with ( location of next data field contents of requested data field ). | 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]
... |
Calculate two s complement. | 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 ... |
Decode base64 coded part of the 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 |
Parses ssh options string. | 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, o... |
Parses ssh - rsa public keys. | 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)
sel... |
Parses ssh - dsa public keys. | 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... |
Parses ecdsa - sha public keys. | 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_al... |
Parses ed25516 keys. | 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)
ver... |
Validates SSH public key. | 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 fi... |
Creates a friendly error message from a GSS status code. This is used to create the: attr: GSSCException. message of a: class: GSSCException. | 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 GSS... |
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 mec... | 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 ... |
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... | 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
... |
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. | 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 ... |
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. | 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 t... |
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. | 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.
"""
retu... |
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. | 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.
... |
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 ve... | 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... |
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. | 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` paramet... |
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. | 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:`... |
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. | 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 determin... |
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. | 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.... |
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: | 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 i... |
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 secur... | 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
... |
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. | 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
... |
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 | 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]')
lifetim... |
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. | 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.
... |
Performs a step to establish the context as an initiator. | 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.... |
Performs a step to establish the context as an acceptor. | 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.
... |
The set of mechanisms supported by the credential. | 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 |
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. | 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 ... |
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. | 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
... |
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_c... | 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... |
Return an: class: OIDSet of all the mechanisms supported by the underlying GSSAPI implementation. | 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(... |
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. | 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.
... |
Factory function to create a new: class: OIDSet with a single member. | 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
:rtyp... |
Adds another: class: OID to this set. | 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._oi... |
Imports and runs setup function with given 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 returns a setup function. | 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 b... |
kwargs: command_publish_address: in the form of tcp:// *: 5555 or any other zeromq address format. IE ipc:// *: 5555 | 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`
... |
Returns a file handle which is used to record audio | 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:... |
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 se... |
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 ) | 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_... |
Returns HTML5 Boilerplate CSS file. Included in HTML5 Boilerplate. | 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/c... |
Returns Normalize CSS file. Included in HTML5 Boilerplate. | 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/no... |
Returns Font Awesome CSS file. TEMPLATE_DEBUG returns full file otherwise returns minified file. | 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(
'<lin... |
Returns Modernizr JavaScript file according to version number. TEMPLATE_DEBUG returns full file otherwise returns minified file. Included in HTML5 Boilerplate. | 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', DJFRONT... |
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. | 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, '... |
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. | 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', DJFRONTE... |
Returns the jQuery DataTables plugin file according to version number. TEMPLATE_DEBUG returns full file otherwise returns minified file. | 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):
v... |
Returns the jQuery DataTables CSS file according to version number. | 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',... |
Returns the jQuery DataTables ThemeRoller CSS file according to version number. | 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... |
Returns the jQuery Dynamic Formset plugin file according to version number. TEMPLATE_DEBUG returns full file otherwise returns minified file. | 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_F... |
Returns the jQuery ScrollTo plugin file according to version number. TEMPLATE_DEBUG returns full file otherwise returns minified file. | 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_SCROLL... |
Returns the jQuery Smooth Scroll plugin file according to version number. TEMPLATE_DEBUG returns full file otherwise returns minified file. | 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_... |
Returns Twitter Bootstrap CSS file. TEMPLATE_DEBUG returns full file otherwise returns minified file. | 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',... |
Returns Twitter Bootstrap JavaScript file ( s ). all returns concatenated file ; full file for TEMPLATE_DEBUG minified otherwise. | 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,
... |
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. | 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 Boilerp... |
u Render CodeMirrorTextarea | 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),
... |
Generate auth tokens tied to user and specified purpose. | 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(micro... |
Return specific time an auth_hash will expire. | 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 login token info for given user. | 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... |
Serialize user as per Meteor accounts serialization. | 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`
... |
De - serialize user profile fields into concrete model fields. | 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 `... |
Update user data. | 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(... |
Retrieve the current user ( or None ) from the database. | 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) |
Update subs to send added/ removed for collections with user_rel. | 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 que... |
Consistent fail so we don t provide attackers with valuable info. | 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(40... |
Resolve and validate auth token returns user object. | 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_m... |
Check request return False if using SSL or local connection. | 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 # loc... |
Retrieve username from user selector. | 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):
... |
Register a new user account. | 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_... |
Login a 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)
... |
Logout a user. | 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.requ... |
Login either with resume token or password. | 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) |
Authenticate using credentials supplied in params. | 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(userna... |
Login with existing resume token. | 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 wh... |
Change password. | 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(o... |
Request password reset email. | 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:
se... |
Reset password using a token received in email then logs user in. | 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_p... |
Recursive dict merge. | 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, ... |
Read encoded contents from specified path or return default. | 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 Non... |
Return HTML ( or other related content ) for Meteor. | 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', {}),
... |
Return an Alea ID for the given object. | 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 ... |
Return Alea ID mapping for all given ids of specified model. | 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... |
Return an object ID for the given meteor_id. | 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
... |
Return all object IDs for the given meteor_ids. | 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=W02... |
Return an object for the given 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, **k... |
Generate ID if required. | 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. | 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... |
Set default value for AleaIdField. | 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_met... |
Unset default value for AleaIdField. | 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) |
Truncate tables. | 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(),
... |
Use schema_editor to apply any forward changes. | 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 reverse changes. | 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) |
Set command option defaults. | 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_pr... |
Update command options. | 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... |
Peform build. | 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... |
Convert a UNIX - style path into platform specific directory spec. | 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)
) |
Seed internal state from supplied values. | 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._... |
Return internal state useful for testing. | def state(self):
"""Return internal state, useful for testing."""
return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.