Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def key_exists_in_list_or_dict(key, lst_or_dct): if isinstance(lst_or_dct, dict) and key in lst_or_dct: return True elif isinstance(lst_or_dct, list): min_i, max_i = 0, len(lst_or_dct) if min_i <= key < max_i: return True ...
[ "True if `lst_or_dct[key]` does not raise an Exception" ]
Please provide a description of the function:def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None): keys = list(keys) keychain = [] while len(keys[:-1]) > 0: key = keys.pop(0) try: lst_or_dct = lst_or_dct[key] except (KeyError, IndexError): ...
[ "\n Raise MetainfoError is not of a particular type\n\n lst_or_dct: list or dict instance\n keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a\n value\n exp_types: Sequence of types that the value specified by `keys` must be an\n instance of\n must_exi...
Please provide a description of the function:def error_message_and_exit(message, error_result): if message: error_message(message) puts(json.dumps(error_result, indent=2)) sys.exit(1)
[ "Prints error messages in blue, the failed task result and quits." ]
Please provide a description of the function:def print_prompt_values(values, message=None, sub_attr=None): if message: prompt_message(message) for index, entry in enumerate(values): if sub_attr: line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr)) else: ...
[ "Prints prompt title and choices with a bit of formatting." ]
Please provide a description of the function:def prompt_for_input(message, input_type=None): while True: output = prompt.query(message) if input_type: try: output = input_type(output) except ValueError: error_message('Invalid input type')...
[ "Prints prompt instruction and does basic input parsing." ]
Please provide a description of the function:def prompt_for_choice(values, message, input_type=int, output_type=None): output = None while not output: index = prompt_for_input(message, input_type=input_type) try: output = utf8(values[index]) except IndexError: ...
[ "Prints prompt with a list of choices to choose from." ]
Please provide a description of the function:def _retrieve_result(endpoints, token_header): request_list = [ (url, token_header) for (task_id, url) in endpoints ] responses = concurrent_get(request_list) # Quick sanity check assert len(endpoints...
[ "Prepare the request list and execute them concurrently." ]
Please provide a description of the function:def _build_endpoint(self, endpoint_name): endpoint_relative = settings.get('asmaster_endpoints', endpoint_name) return '%s%s' % (self.host, endpoint_relative)
[ "Generate an enpoint url from a setting name.\n\n Args:\n endpoint_name(str): setting name for the enpoint to build\n\n Returns:\n (str) url enpoint\n " ]
Please provide a description of the function:def _set_allowed_services_and_actions(self, services): for service in services: self.services[service['name']] = {} for action in service['actions']: name = action.pop('name') self.services[service['na...
[ "Expect services to be a list of service dictionaries, each with `name` and `actions` keys." ]
Please provide a description of the function:def list_subscriptions(self, service): data = { 'service': service, } return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header)
[ "Asks for a list of all subscribed accounts and devices, along with their statuses." ]
Please provide a description of the function:def subscribe_account(self, username, password, service): data = { 'service': service, 'username': username, 'password': password, } return self._perform_post_request(self.subscribe_account_endpoint, data,...
[ "Subscribe an account for a service.\n " ]
Please provide a description of the function:def reset_subscription_since(self, account_id, datetime_str): data = { 'account_id': account_id, 'datetime': datetime_str, } return self._perform_post_request(self.reset_subscription_since_endpoint, data, self.token_he...
[ "Handler for `--reset-subscription-since` command.\n\n Args:\n account_id(int): id of the account to reset.\n datetime_str(str): string representing the datetime used in the\n next poll to retrieve data since.\n\n Returns:\n (str) json encoded response.\...
Please provide a description of the function:def _parse_response(response, post_request=False): try: data = response.json() except: msg = 'Unhandled HTTP %s response, shown truncated below:\n%s...' % ( response.status_code, response.text[:50] ...
[ "Treat the response from ASApi.\n\n The json is dumped before checking the status as even if the response is\n not properly formed we are in trouble.\n " ]
Please provide a description of the function:def file_id_to_file_name(file_id): if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id): return file_id # prefix with "re_" to avoid name collision with real fileids return "re_{}".format(hashlib.sha1(file_id).hexdigest())
[ "Sometimes file ids are not the file names on the device, but are instead generated\n by the API. These are not guaranteed to be valid file names so need hashing.\n " ]
Please provide a description of the function:def sync(func): sync_timeout = 3600 # Match standard synchronous timeout. def wraps(*args, **kwargs): task = func(*args, **kwargs) task.wait_for_result(timeout=sync_timeout) result = json.loads(task.result) return result re...
[ "Decorator to make a task synchronous." ]
Please provide a description of the function:def fetch_data(self): choices = self.available_data choices.insert(0, 'All') selected_data_type = utils.select_item( choices, 'Please select what data to fetch:', 'Available data:', ) if s...
[ "Prompt for a data type choice and execute the `fetch_data` task.\n The results are saved to a file in json format.\n " ]
Please provide a description of the function:def log_in(self): if not self.password: # Password wasn't give, ask for it now self.password = getpass.getpass('Password: ') utils.pending_message('Performing login...') login_result = self.client.login( ...
[ "Perform the `log_in` task to setup the API session for future data requests." ]
Please provide a description of the function:def handle_failed_login(self, login_result): error_code = login_result.get('error') if '2fa-required' in error_code: utils.error_message('Login Failed: 2FA or 2SV is active!') self.trigger_two_step_login(login_result) ...
[ "If Two Factor Authentication (2FA/2SV) is enabled, the initial\n login will fail with a predictable error. Catching this error allows us\n to begin the authentication process.\n\n Other types of errors can be treated in a similar way.\n " ]
Please provide a description of the function:def get_devices(self): utils.pending_message('Fetching device list...') get_devices_task = self.client.devices( account=self.account ) # We wait for device list info as this sample relies on it next. get_devices_...
[ "Execute the `get_devices` task and store the results in `self.devices`." ]
Please provide a description of the function:def download_files(self, files): utils.pending_message( "Downloading {nfiles} file{plural}...".format( nfiles=len(files), plural='s' if len(files) > 1 else '' )) for file in files: ...
[ "This method uses the `download_file` task to retrieve binary files\n such as attachments, images and videos.\n\n Notice that this method does not wait for the tasks it creates to return\n a result synchronously.\n ", "Callback to save a download file result to a file on disk." ]
Please provide a description of the function:def register_account(self, username, service): data = { 'service': service, 'username': username, } return self._perform_post_request(self.register_account_endpoint, data, self.token_header)
[ "Register an account against a service.\n The account that we're querying must be referenced during any\n future task requests - so we know which account to link the task\n too.\n " ]
Please provide a description of the function:def perform_task(self, service, task_name, account, payload, callback=None): data = { 'service': service, 'action': task_name, 'account': account, } data.update(payload) response = self._perform_po...
[ "Submit a task to the API.\n The task is executed asyncronously, and a Task object is returned.\n " ]
Please provide a description of the function:def task_status(self, task_id): data = { 'task_ids': task_id, } return self._perform_post_request(self.task_status_endpoint, data, self.token_header)
[ "Find the status of a task." ]
Please provide a description of the function:def result_consumed(self, task_id): logger.debug('Sending result consumed message.') data = { 'task_ids': task_id, } return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header)
[ "Report the result as successfully consumed." ]
Please provide a description of the function:def _parse_response(response, post_request=False): data = response.json() if not response.ok: utils.error_message_and_exit('Push Api Error:', data) if post_request and not data['success']: raise Exception('Push Api E...
[ "Treat the response from ASApi.\n\n The json is dumped before checking the status as even if the response is\n not properly formed we are in trouble.\n\n TODO: Streamline error checking.\n " ]
Please provide a description of the function:def clean_deleted_sessions(cls): for federate_slo in cls.objects.all(): if not SessionStore(session_key=federate_slo.session_key).get('authenticated'): federate_slo.delete()
[ "remove old :class:`FederateSLO` object for which the session do not exists anymore" ]
Please provide a description of the function:def send_mails(cls): if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS: try: obj = cls.objects.get() except cls.DoesNotExist: obj = NewVersionWarning.objects.create(version=VERSION) ...
[ "\n For each new django-cas-server version, if the current instance is not up to date\n send one mail to ``settings.ADMINS``.\n " ]
Please provide a description of the function:def get_login_url(self): params = {'service': self.service_url} if self.renew: params.update({'renew': 'true'}) params.update(self.extra_login_params) url = urllib_parse.urljoin(self.server_url, 'login') query = u...
[ "Generates CAS login URL" ]
Please provide a description of the function:def get_logout_url(self, redirect_url=None): url = urllib_parse.urljoin(self.server_url, 'logout') if redirect_url: params = {self.logout_redirect_param_name: redirect_url} url += '?' + urllib_parse.urlencode(params) r...
[ "Generates CAS logout URL" ]
Please provide a description of the function:def get_proxy_url(self, pgt): params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url}) return "%s/proxy?%s" % (self.server_url, params)
[ "Returns proxy url, given the proxy granting ticket" ]
Please provide a description of the function:def get_proxy_ticket(self, pgt): response = urllib_request.urlopen(self.get_proxy_url(pgt)) if response.code == 200: from lxml import etree root = etree.fromstring(response.read()) tickets = root.xpath( ...
[ "Returns proxy ticket given the proxy granting ticket" ]
Please provide a description of the function:def verify_ticket(self, ticket): params = [('ticket', ticket), ('service', self.service_url)] if self.renew: params.append(('renew', 'true')) url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' + urllib_p...
[ "Verifies CAS 1.0 authentication ticket.\n\n Returns username on success and None on failure.\n " ]
Please provide a description of the function:def verify_ticket(self, ticket): (response, charset) = self.get_verification_response(ticket) return self.verify_response(response, charset)
[ "Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes" ]
Please provide a description of the function:def get_saml_assertion(cls, ticket): # RequestID [REQUIRED] - unique identifier for the request request_id = uuid4() # e.g. 2014-06-02T09:21:03.071189 timestamp = datetime.datetime.now().isoformat() return SAML_ASSERTION_TEM...
[ "\n http://www.jasig.org/cas/protocol#samlvalidate-cas-3.0\n\n SAML request values:\n\n RequestID [REQUIRED]:\n unique identifier for the request\n IssueInstant [REQUIRED]:\n timestamp of the request\n samlp:AssertionArtifact [REQUIRED]:\n the vali...
Please provide a description of the function:def get_conn(cls): conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, cli...
[ "Return a connection object to the ldap database" ]
Please provide a description of the function:def attributs(self): if self.user: attr = {} # _meta.get_fields() is from the new documented _meta interface in django 1.8 try: field_names = [ field.attname for field in self.user._meta...
[ "\n The user attributes, defined as the fields on the :attr:`user` object.\n\n :return: a :class:`dict` with the :attr:`user` object fields. Attributes may be\n If the user do not exists, the returned :class:`dict` is empty.\n :rtype: dict\n " ]
Please provide a description of the function:def json_encode(obj): try: return json_encode.encoder.encode(obj) except AttributeError: json_encode.encoder = DjangoJSONEncoder(default=six.text_type) return json_encode(obj)
[ "Encode a python object to json" ]
Please provide a description of the function:def context(params): params["settings"] = settings params["message_levels"] = DEFAULT_MESSAGE_LEVELS if settings.CAS_NEW_VERSION_HTML_WARNING: LAST_VERSION = last_version() params["VERSION"] = VERSION params["LAST_VERSION"] = LAST_VE...
[ "\n Function that add somes variable to the context before template rendering\n\n :param dict params: The context dictionary used to render templates.\n :return: The ``params`` dictionary with the key ``settings`` set to\n :obj:`django.conf.settings`.\n :rtype: dict\n " ]
Please provide a description of the function:def json_response(request, data): data["messages"] = [] for msg in messages.get_messages(request): data["messages"].append({'message': msg.message, 'level': msg.level_tag}) return HttpResponse(json.dumps(data), content_type="application/json")
[ "\n Wrapper dumping `data` to a json and sending it to the user with an HttpResponse\n\n :param django.http.HttpRequest request: The request object used to generate this response.\n :param dict data: The python dictionnary to return as a json\n :return: The content of ``data`` serialized...
Please provide a description of the function:def import_attr(path): # if we got a str, decode it to unicode (normally it should only contain ascii) if isinstance(path, six.binary_type): path = path.decode("utf-8") # if path is not an unicode, return it unchanged (may be it is already the attrib...
[ "\n transform a python dotted path to the attr\n\n :param path: A dotted path to a python object or a python object\n :type path: :obj:`unicode` or :obj:`str` or anything\n :return: The python object pointed by the dotted path or the python object unchanged\n " ]
Please provide a description of the function:def redirect_params(url_name, params=None): url = reverse(url_name) params = urlencode(params if params else {}) return HttpResponseRedirect(url + "?%s" % params)
[ "\n Redirect to ``url_name`` with ``params`` as querystring\n\n :param unicode url_name: a URL pattern name\n :param params: Some parameter to append to the reversed URL\n :type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`\n :return: A redirection to the URL with name ``...
Please provide a description of the function:def reverse_params(url_name, params=None, **kwargs): url = reverse(url_name, **kwargs) params = urlencode(params if params else {}) if params: return u"%s?%s" % (url, params) else: return url
[ "\n compute the reverse url of ``url_name`` and add to it parameters from ``params``\n as querystring\n\n :param unicode url_name: a URL pattern name\n :param params: Some parameter to append to the reversed URL\n :type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`\n ...
Please provide a description of the function:def copy_params(get_or_post_params, ignore=None): if ignore is None: ignore = set() params = {} for key in get_or_post_params: if key not in ignore and get_or_post_params[key]: params[key] = get_or_post_params[key] return para...
[ "\n copy a :class:`django.http.QueryDict` in a :obj:`dict` ignoring keys in the set ``ignore``\n\n :param django.http.QueryDict get_or_post_params: A GET or POST\n :class:`QueryDict<django.http.QueryDict>`\n :param set ignore: An optinal set of keys to ignore during the copy\n ...
Please provide a description of the function:def set_cookie(response, key, value, max_age): expires = datetime.strftime( datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT" ) response.set_cookie( key, value, max_age=max_age, expire...
[ "\n Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes\n\n :param django.http.HttpResponse response: a django response where to set the cookie\n :param unicode key: the cookie key\n :param unicode value: the cookie value\n :param int max_age...
Please provide a description of the function:def get_current_url(request, ignore_params=None): if ignore_params is None: ignore_params = set() protocol = u'https' if request.is_secure() else u"http" service_url = u"%s://%s%s" % (protocol, request.get_host(), request.path) if request.GET: ...
[ "\n Giving a django request, return the current http url, possibly ignoring some GET parameters\n\n :param django.http.HttpRequest request: The current request object.\n :param set ignore_params: An optional set of GET parameters to ignore\n :return: The URL of the current page, possibly...
Please provide a description of the function:def update_url(url, params): if not isinstance(url, bytes): url = url.encode('utf-8') for key, value in list(params.items()): if not isinstance(key, bytes): del params[key] key = key.encode('utf-8') if not isinstan...
[ "\n update parameters using ``params`` in the ``url`` query string\n\n :param url: An URL possibily with a querystring\n :type url: :obj:`unicode` or :obj:`str`\n :param dict params: A dictionary of parameters for updating the url querystring\n :return: The URL with an updated que...
Please provide a description of the function:def unpack_nested_exception(error): i = 0 while True: if error.args[i:]: if isinstance(error.args[i], Exception): error = error.args[i] i = 0 else: i += 1 else: b...
[ "\n If exception are stacked, return the first one\n\n :param error: A python exception with possible exception embeded within\n :return: A python exception with no exception embeded within\n " ]
Please provide a description of the function:def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN): random_part = u''.join( random.choice( string.ascii_letters + string.digits ) for _ in range(lg - len(prefix or "") - 1) ) if prefix is not None: return u'%s-%s' % ...
[ "\n Generate a ticket with prefix ``prefix`` and length ``lg``\n\n :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU)\n :param int lg: The length of the generated ticket (with the prefix)\n :return: A randomlly generated ticket of length ``lg``\n :rtype: un...
Please provide a description of the function:def get_tuple(nuplet, index, default=None): if nuplet is None: return default try: return nuplet[index] except IndexError: return default
[ "\n :param tuple nuplet: A tuple\n :param int index: An index\n :param default: An optional default value\n :return: ``nuplet[index]`` if defined, else ``default`` (possibly ``None``)\n " ]
Please provide a description of the function:def crypt_salt_is_valid(salt): if len(salt) < 2: return False else: if salt[0] == '$': if salt[1] == '$': return False else: if '$' not in salt[1:]: return False ...
[ "\n Validate a salt as crypt salt\n\n :param str salt: a password salt\n :return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise\n :rtype: bool\n " ]
Please provide a description of the function:def check_password(method, password, hashed_password, charset): if not isinstance(password, six.binary_type): password = password.encode(charset) if not isinstance(hashed_password, six.binary_type): hashed_password = hashed_password.encode(charse...
[ "\n Check that ``password`` match `hashed_password` using ``method``,\n assuming the encoding is ``charset``.\n\n :param str method: on of ``\"crypt\"``, ``\"ldap\"``, ``\"hex_md5\"``, ``\"hex_sha1\"``,\n ``\"hex_sha224\"``, ``\"hex_sha256\"``, ``\"hex_sha384\"``, ``\"hex_sha512\"``,...
Please provide a description of the function:def last_version(): try: last_update, version, success = last_version._cache except AttributeError: last_update = 0 version = None success = False cache_delta = 24 * 3600 if success else 600 if (time.time() - last_update) ...
[ "\n Fetch the last version from pypi and return it. On successful fetch from pypi, the response\n is cached 24h, on error, it is cached 10 min.\n\n :return: the last django-cas-server version\n :rtype: unicode\n " ]
Please provide a description of the function:def regexpr_validator(value): try: re.compile(value) except re.error: raise ValidationError( _('"%(value)s" is not a valid regular expression'), params={'value': value} )
[ "\n Test that ``value`` is a valid regular expression\n\n :param unicode value: A regular expression to test\n :raises ValidationError: if ``value`` is not a valid regular expression\n " ]
Please provide a description of the function:def _raise_bad_scheme(cls, scheme, valid, msg): valid_schemes = [s.decode() for s in valid] valid_schemes.sort() raise cls.BadScheme(msg % (scheme, u", ".join(valid_schemes)))
[ "\n Raise :attr:`BadScheme` error for ``scheme``, possible valid scheme are\n in ``valid``, the error message is ``msg``\n\n :param bytes scheme: A bad scheme\n :param list valid: A list a valid scheme\n :param str msg: The error template message\n :...
Please provide a description of the function:def hash(cls, scheme, password, salt=None, charset="utf8"): scheme = scheme.upper() cls._test_scheme(scheme) if salt is None or salt == b"": salt = b"" cls._test_scheme_nosalt(scheme) else: cls._tes...
[ "\n Hash ``password`` with ``scheme`` using ``salt``.\n This three variable beeing encoded in ``charset``.\n\n :param bytes scheme: A valid scheme\n :param bytes password: A byte string to hash using ``scheme``\n :param bytes salt: An optional salt to use if ``schem...
Please provide a description of the function:def get_scheme(cls, hashed_passord): if not hashed_passord[0] == b'{'[0] or b'}' not in hashed_passord: raise cls.BadHash("%r should start with the scheme enclosed with { }" % hashed_passord) scheme = hashed_passord.split(b'}', 1)[0] ...
[ "\n Return the scheme of ``hashed_passord`` or raise :attr:`BadHash`\n\n :param bytes hashed_passord: A hashed password\n :return: The scheme used by the hashed password\n :rtype: bytes\n :raises BadHash: if no valid scheme is found within ``hashed_passord``\n ...
Please provide a description of the function:def get_salt(cls, hashed_passord): scheme = cls.get_scheme(hashed_passord) cls._test_scheme(scheme) if scheme in cls.schemes_nosalt: return b"" elif scheme == b'{CRYPT}': return b'$'.join(hashed_passord.split(b...
[ "\n Return the salt of ``hashed_passord`` possibly empty\n\n :param bytes hashed_passord: A hashed password\n :return: The salt used by the hashed password (empty if no salt is used)\n :rtype: bytes\n :raises BadHash: if no valid scheme is found within ``hashed...
Please provide a description of the function:def verify_ticket(self, ticket): try: username, attributs = self.client.verify_ticket(ticket)[:2] except urllib.error.URLError: return False if username is not None: if attributs is None: at...
[ "\n test ``ticket`` against the CAS provider, if valid, create a\n :class:`FederatedUser<cas_server.models.FederatedUser>` matching provider returned\n username and attributes.\n\n :param unicode ticket: The ticket to validate against the provider CAS\n :return...
Please provide a description of the function:def register_slo(username, session_key, ticket): try: FederateSLO.objects.create( username=username, session_key=session_key, ticket=ticket ) except IntegrityError: # pragma: no...
[ "\n association a ``ticket`` with a (``username``, ``session_key``) for processing later SLO\n request by creating a :class:`cas_server.models.FederateSLO` object.\n\n :param unicode username: A logged user username, with the ``@`` component.\n :param unicode session_key:...
Please provide a description of the function:def clean_sessions(self, logout_request): try: slos = self.client.get_saml_slos(logout_request) or [] except NameError: # pragma: no cover (should not happen) slos = [] for slo in slos: for federate_slo in...
[ "\n process a SLO request: Search for ticket values in ``logout_request``. For each\n ticket value matching a :class:`cas_server.models.FederateSLO`, disconnect the\n corresponding user.\n\n :param unicode logout_request: An XML document contening one or more Single Log O...
Please provide a description of the function:def visit_snippet(self, node): lang = self.highlightlang linenos = node.rawsource.count('\n') >= self.highlightlinenothreshold - 1 fname = node['filename'] highlight_args = node.get('highlight_args', {}) if 'language' in node: # code-block di...
[ "\n HTML document generator visit handler\n " ]
Please provide a description of the function:def visit_snippet_latex(self, node): code = node.rawsource.rstrip('\n') lang = self.hlsettingstack[-1][0] linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1 fname = node['filename'] highlight_args = node.get('highlight_args', {}) if 'l...
[ "\n Latex document generator visit handler\n " ]
Please provide a description of the function:def active_link(context, viewnames, css_class=None, strict=None, *args, **kwargs): if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) ...
[ "\n Renders the given CSS class if the request path matches the path of the view.\n :param context: The context where the tag was called. Used to access the request object.\n :param viewnames: The name of the view or views separated by || (include namespaces if any).\n :param css_class: The CSS class to...
Please provide a description of the function:def clean(self): cleaned_data = super(UserCredential, self).clean() if "username" in cleaned_data and "password" in cleaned_data: auth = utils.import_attr(settings.CAS_AUTH_CLASS)(cleaned_data["username"]) if auth.test_passwor...
[ "\n Validate that the submited :attr:`username` and :attr:`password` are valid\n\n :raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`\n are not valid.\n :return: The cleaned POST data\n :rtype: dict\n " ]
Please provide a description of the function:def clean(self): cleaned_data = super(FederateUserCredential, self).clean() try: user = models.FederatedUser.get_from_federated_username(cleaned_data["username"]) user.ticket = "" user.save() # should not h...
[ "\n Validate that the submited :attr:`username` and :attr:`password` are valid using\n the :class:`CASFederateAuth<cas_server.auth.CASFederateAuth>` auth class.\n\n :raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`\n do not correspond ...
Please provide a description of the function:def logout(self, all_session=False): # initialize the counter of the number of destroyed sesisons session_nb = 0 # save the current user username before flushing the session username = self.request.session.get("username") if u...
[ "\n effectively destroy a CAS session\n\n :param boolean all_session: If ``True`` destroy all the user sessions, otherwise\n destroy the current user session.\n :return: The number of destroyed sessions\n :rtype: int\n " ]
Please provide a description of the function:def init_get(self, request): self.request = request self.service = request.GET.get('service') self.url = request.GET.get('url') self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
[ "\n Initialize the :class:`LogoutView` attributes on GET request\n\n :param django.http.HttpRequest request: The current request object\n " ]
Please provide a description of the function:def get(self, request, *args, **kwargs): logger.info("logout requested") # initialize the class attributes self.init_get(request) # if CAS federation mode is enable, bakup the provider before flushing the sessions if settings....
[ "\n method called on GET request on this view\n\n :param django.http.HttpRequest request: The current request object\n " ]
Please provide a description of the function:def get_cas_client(self, request, provider, renew=False): # compute the current url, ignoring ticket dans provider GET parameters service_url = utils.get_current_url(request, {"ticket", "provider"}) self.service_url = service_url retu...
[ "\n return a CAS client object matching provider\n\n :param django.http.HttpRequest request: The current request object\n :param cas_server.models.FederatedIendityProvider provider: the user identity provider\n :return: The user CAS client object\n :rtype: :cla...
Please provide a description of the function:def post(self, request, provider=None): # if settings.CAS_FEDERATE is not True redirect to the login page if not settings.CAS_FEDERATE: logger.warning("CAS_FEDERATE is False, set it to True to use federation") return redirect(...
[ "\n method called on POST request\n\n :param django.http.HttpRequest request: The current request object\n :param unicode provider: Optional parameter. The user provider suffix.\n " ]
Please provide a description of the function:def get(self, request, provider=None): # if settings.CAS_FEDERATE is not True redirect to the login page if not settings.CAS_FEDERATE: logger.warning("CAS_FEDERATE is False, set it to True to use federation") return redirect("...
[ "\n method called on GET request\n\n :param django.http.HttpRequestself. request: The current request object\n :param unicode provider: Optional parameter. The user provider suffix.\n " ]
Please provide a description of the function:def init_post(self, request): self.request = request self.service = request.POST.get('service') self.renew = bool(request.POST.get('renew') and request.POST['renew'] != "False") self.gateway = request.POST.get('gateway') self....
[ "\n Initialize POST received parameters\n\n :param django.http.HttpRequest request: The current request object\n " ]
Please provide a description of the function:def gen_lt(self): self.request.session['lt'] = self.request.session.get('lt', []) + [utils.gen_lt()] if len(self.request.session['lt']) > 100: self.request.session['lt'] = self.request.session['lt'][-100:]
[ "Generate a new LoginTicket and add it to the list of valid LT for the user" ]
Please provide a description of the function:def check_lt(self): # save LT for later check lt_valid = self.request.session.get('lt', []) lt_send = self.request.POST.get('lt') # generate a new LT (by posting the LT has been consumed) self.gen_lt() # check if send ...
[ "\n Check is the POSTed LoginTicket is valid, if yes invalide it\n\n :return: ``True`` if the LoginTicket is valid, ``False`` otherwise\n :rtype: bool\n " ]
Please provide a description of the function:def post(self, request, *args, **kwargs): # initialize class parameters self.init_post(request) # process the POST request ret = self.process_post() if ret == self.INVALID_LOGIN_TICKET: messages.add_message( ...
[ "\n method called on POST request on this view\n\n :param django.http.HttpRequest request: The current request object\n " ]
Please provide a description of the function:def process_post(self): if not self.check_lt(): self.init_form(self.request.POST) logger.warning("Received an invalid login ticket") return self.INVALID_LOGIN_TICKET elif not self.request.session.get("authenticated...
[ "\n Analyse the POST request:\n\n * check that the LoginTicket is valid\n * check that the user sumited credentials are valid\n\n :return:\n * :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid\n * :attr:`USER_ALREADY...
Please provide a description of the function:def init_get(self, request): self.request = request self.service = request.GET.get('service') self.renew = bool(request.GET.get('renew') and request.GET['renew'] != "False") self.gateway = request.GET.get('gateway') self.metho...
[ "\n Initialize GET received parameters\n\n :param django.http.HttpRequest request: The current request object\n " ]
Please provide a description of the function:def get(self, request, *args, **kwargs): # initialize class parameters self.init_get(request) # process the GET request self.process_get() # call the GET/POST common part return self.common()
[ "\n method called on GET request on this view\n\n :param django.http.HttpRequest request: The current request object\n " ]
Please provide a description of the function:def process_get(self): # generate a new LT self.gen_lt() if not self.request.session.get("authenticated") or self.renew: # authentication will be needed, initialize the form to use self.init_form() return s...
[ "\n Analyse the GET request\n\n :return:\n * :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting\n for authentication renewal\n * :attr:`USER_AUTHENTICATED` if the user is authenticated and is not requesting\n ...
Please provide a description of the function:def init_form(self, values=None): if values: values = values.copy() values['lt'] = self.request.session['lt'][-1] form_initial = { 'service': self.service, 'method': self.method, 'warn': ( ...
[ "\n Initialization of the good form depending of POST and GET parameters\n\n :param django.http.QueryDict values: A POST or GET QueryDict\n " ]
Please provide a description of the function:def service_login(self): try: # is the service allowed service_pattern = ServicePattern.validate(self.service) # is the current user allowed on this service service_pattern.check_user(self.user) # i...
[ "\n Perform login against a service\n\n :return:\n * The rendering of the ``settings.CAS_WARN_TEMPLATE`` if the user asked to be\n warned before ticket emission and has not yep been warned.\n * The redirection to the service URL with a ticket GET ...
Please provide a description of the function:def authenticated(self): # Try to get the current :class:`models.User<cas_server.models.User>` object for the current # session try: self.user = models.User.objects.get( username=self.request.session.get("username"...
[ "\n Processing authenticated users\n\n :return:\n * The returned value of :meth:`service_login` if :attr:`service` is defined\n * The rendering of ``settings.CAS_LOGGED_TEMPLATE`` otherwise\n :rtype: django.http.HttpResponse\n " ]
Please provide a description of the function:def not_authenticated(self): if self.service: try: service_pattern = ServicePattern.validate(self.service) if self.gateway and not self.ajax: # clean messages before leaving django ...
[ "\n Processing non authenticated users\n\n :return:\n * The rendering of ``settings.CAS_LOGIN_TEMPLATE`` with various messages\n depending of GET/POST parameters\n * The redirection to :class:`FederateAuth` if ``settings.CAS_FEDERATE`` is ``True``...
Please provide a description of the function:def common(self): # if authenticated and successfully renewed authentication if needed if self.request.session.get("authenticated") and (not self.renew or self.renewed): return self.authenticated() else: return self.no...
[ "\n Common part execute uppon GET and POST request\n\n :return:\n * The returned value of :meth:`authenticated` if the user is authenticated and\n not requesting for authentication or if the authentication has just been renewed\n * The returned va...
Please provide a description of the function:def post(request): username = request.POST.get('username') password = request.POST.get('password') service = request.POST.get('service') secret = request.POST.get('secret') if not settings.CAS_AUTH_SHARED_SECRET: ...
[ "\n method called on POST request on this view\n\n :param django.http.HttpRequest request: The current request object\n :return: ``HttpResponse(u\"yes\\\\n\")`` if the POSTed tuple (username, password, service)\n if valid (i.e. (username, password) is valid dans usern...
Please provide a description of the function:def get(request): # store wanted GET parameters service = request.GET.get('service') ticket = request.GET.get('ticket') renew = True if request.GET.get('renew') else False # service and ticket parameters are mandatory ...
[ "\n method called on GET request on this view\n\n :param django.http.HttpRequest request: The current request object\n :return:\n * ``HttpResponse(\"yes\\\\nusername\")`` if submited (service, ticket) is valid\n * else ``HttpResponse(\"no\\\\n\")``\n ...
Please provide a description of the function:def get(self, request): # define the class parameters self.request = request self.service = request.GET.get('service') self.ticket = request.GET.get('ticket') self.pgt_url = request.GET.get('pgtUrl') self.renew = True ...
[ "\n method called on GET request on this view\n\n :param django.http.HttpRequest request: The current request object:\n :return: The rendering of ``cas_server/serviceValidate.xml`` if no errors is raised,\n the rendering or ``cas_server/serviceValidateError.xml`` othe...
Please provide a description of the function:def process_ticket(self): try: proxies = [] if self.allow_proxy_ticket: ticket = models.Ticket.get(self.ticket, self.renew) else: ticket = models.ServiceTicket.get(self.ticket, self.renew) ...
[ "\n fetch the ticket against the database and check its validity\n\n :raises ValidateError: if the ticket is not found or not valid, potentially for that\n service\n :returns: A couple (ticket, proxies list)\n :rtype: :obj:`tuple`\n " ]
Please provide a description of the function:def process_pgturl(self, params): try: pattern = ServicePattern.validate(self.pgt_url) if pattern.proxy_callback: proxyid = utils.gen_pgtiou() pticket = ProxyGrantingTicket.objects.create( ...
[ "\n Handle PGT request\n\n :param dict params: A template context dict\n :raises ValidateError: if pgtUrl is invalid or if TLS validation of the pgtUrl fails\n :return: The rendering of ``cas_server/serviceValidate.xml``, using ``params``\n :rtype: django.http....
Please provide a description of the function:def get(self, request): self.request = request self.pgt = request.GET.get('pgt') self.target_service = request.GET.get('targetService') try: # pgt and targetService parameters are mandatory if self.pgt and self...
[ "\n method called on GET request on this view\n\n :param django.http.HttpRequest request: The current request object:\n :return: The returned value of :meth:`process_proxy` if no error is raised,\n else the rendering of ``cas_server/serviceValidateError.xml``.\n ...
Please provide a description of the function:def process_proxy(self): try: # is the target service allowed pattern = ServicePattern.validate(self.target_service) # to get a proxy ticket require that the service allow it if not pattern.proxy: ...
[ "\n handle PT request\n\n :raises ValidateError: if the PGT is not found, or the target service not allowed or\n the user not allowed on the tardet service.\n :return: The rendering of ``cas_server/proxy.xml``\n :rtype: django.http.HttpResponse\n " ]
Please provide a description of the function:def context(self): return { 'code': self.code, 'msg': self.msg, 'IssueInstant': timezone.now().isoformat(), 'ResponseID': utils.gen_saml_id() }
[ "\n :return: A dictionary to contextualize :attr:`template`\n :rtype: dict\n " ]
Please provide a description of the function:def post(self, request): self.request = request self.target = request.GET.get('TARGET') self.root = etree.fromstring(request.body) try: self.ticket = self.process_ticket() expire_instant = (self.ticket.creation...
[ "\n method called on POST request on this view\n\n :param django.http.HttpRequest request: The current request object\n :return: the rendering of ``cas_server/samlValidate.xml`` if no error is raised,\n else the rendering of ``cas_server/samlValidateError.xml``.\n ...
Please provide a description of the function:def process_ticket(self): try: auth_req = self.root.getchildren()[1].getchildren()[0] ticket = auth_req.getchildren()[0].text ticket = models.Ticket.get(ticket) if ticket.service != self.target: ...
[ "\n validate ticket from SAML XML body\n\n :raises: SamlValidateError: if the ticket is not found or not valid, or if we fail\n to parse the posted XML.\n :return: a ticket object\n :rtype: :class:`models.Ticket<cas_server.models.Ticket>`\n " ]
Please provide a description of the function:def main(source): if source is None: click.echo( "You need to supply a file or url to a schema to a swagger schema, for" "the validator to work." ) return 1 try: load(source) click.echo("Validation ...
[ "\n For a given command line supplied argument, negotiate the content, parse\n the schema and then return any issues to stdout or if no schema issues,\n return success exit code.\n " ]
Please provide a description of the function:def host_validator(value, **kwargs): scheme, hostname, port, path = decompose_hostname(value) if len(hostname) > 255: return False if hostname[-1] == ".": hostname = hostname[:-1] # strip exactly one dot from the right, if present allow...
[ "\n From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string\n According to: http://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names\n " ]
Please provide a description of the function:def methodcaller(name, *args): func = operator.methodcaller(name, *args) return lambda obj, **kwargs: func(obj)
[ "\n Upstream bug in python:\n https://bugs.python.org/issue26822\n " ]
Please provide a description of the function:def load_source(source): if isinstance(source, collections.Mapping): return deepcopy(source) elif hasattr(source, 'read') and callable(source.read): raw_source = source.read() elif os.path.exists(os.path.expanduser(str(source))): with...
[ "\n Common entry point for loading some form of raw swagger schema.\n\n Supports:\n - python object (dictionary-like)\n - path to yaml file\n - path to json file\n - file object (json or yaml).\n - json string.\n - yaml string.\n " ]
Please provide a description of the function:def validate(raw_schema, target=None, **kwargs): schema = schema_validator(raw_schema, **kwargs) if target is not None: validate_object(target, schema=schema, **kwargs)
[ "\n Given the python representation of a JSONschema as defined in the swagger\n spec, validate that the schema complies to spec. If `target` is provided,\n that target will be validated against the provided schema.\n " ]
Please provide a description of the function:def validate_api_response(schema, raw_response, request_method='get', raw_request=None): request = None if raw_request is not None: request = normalize_request(raw_request) response = None if raw_response is not None: response = normaliz...
[ "\n Validate the response of an api call against a swagger schema.\n " ]