Code
stringlengths 103
85.9k
| Summary
sequencelengths 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
return False | [
"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):
break
keychain.append(key)
keychain_str = ''.join(f'[{key!r}]' for key in keychain)
key = keys.pop(0)
if not key_exists_in_list_or_dict(key, lst_or_dct):
if not must_exist:
return
raise error.MetainfoError(f"Missing {key!r} in {keychain_str}")
elif not isinstance(lst_or_dct[key], exp_types):
exp_types_str = ' or '.join(t.__name__ for t in exp_types)
type_str = type(lst_or_dct[key]).__name__
raise error.MetainfoError(f"{keychain_str}[{key!r}] must be {exp_types_str}, "
f"not {type_str}: {lst_or_dct[key]!r}")
elif check is not None and not check(lst_or_dct[key]):
raise error.MetainfoError(f"{keychain_str}[{key!r}] is invalid: {lst_or_dct[key]!r}") | [
"\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_exist: Whether to raise MetainfoError if `keys` does not resolve to a\n value\n check: Callable that gets the value specified by `keys` and returns True if\n it OK, False otherwise\n "
] |
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:
line = '{:2d}: {}'.format(index, utf8(entry))
with indent(3):
print_message(line) | [
"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')
continue
break
return output | [
"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:
error_message('Selection out of range')
continue
if output_type:
output = output_type(output)
return output | [
"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) == len(responses)
responses_dic = {
task_id: r.content
for (task_id, _), r in zip(endpoints, responses)
}
return responses_dic | [
"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['name']][name] = action | [
"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, self.token_header) | [
"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_header) | [
"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.\n\n NOTES:\n We don't care about validation here, we demand the responsibility to\n the backend.\n "
] |
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]
)
raise ValueError(msg)
if not response.ok:
utils.error_message_and_exit(None, data)
if post_request and not data['success']:
raise Exception('Asmaster Api Error: [%s]' % data['error'])
return data | [
"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
return wraps | [
"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 selected_data_type == 'All':
selected_data_type = ','.join(self.available_data)
utils.pending_message('Performing fetch data task...')
fetch_data_task = self.client.data(
account=self.account,
data=selected_data_type,
)
# Wait here for result as rest of sample app relies on it.
fetch_data_task.wait_for_result(timeout=self.timeout)
fetch_data_result = json.loads(fetch_data_task.result)
# Write the result to file.
task_id = fetch_data_task.uuid
filepath = utils.get_or_create_filepath('%s.json' % task_id)
with open(filepath, 'w') as out:
json.dump(fetch_data_result, out, indent=2)
utils.info_message('Fetch data successful. Output file: %s.json' % task_id)
return fetch_data_result | [
"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(
account=self.account,
password=self.password
)
if 'error' in login_result:
self.handle_failed_login(login_result)
utils.info_message('Login successful') | [
"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)
self.finish_two_step_login()
else:
utils.error_message_and_exit('\nLogin Failed', 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_task.wait_for_result(timeout=self.timeout)
get_devices_result = json.loads(get_devices_task.result)
self.devices = get_devices_result['devices']
utils.info_message('Get devices successful') | [
"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:
if 'file_id' not in file:
continue
def build_callback(file):
def file_callback(task):
device_name = self.devices[self.device_id]['device_name']
path_chunks = file['file_path'].split('/')
directory = os.path.join('files', device_name, *path_chunks[:-1])
filepath = utils.get_or_create_filepath(file['filename'], directory)
with open(filepath, 'wb') as out:
out.write(task.result)
if settings.getboolean('logging', 'time_profile'):
filepath = utils.append_profile_info(filepath, task.timer)
with indent(4):
utils.print_message(filepath)
return file_callback
self.client.download_file(
account=self.account,
device=self.device_id,
file=file['file_id'],
callback=build_callback(file)
) | [
"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_post_request(self.submit_endpoint, data, self.token_header)
task = Task(uuid=response['task_id'], callback=callback)
self._pending_tasks[task.uuid] = task
return task | [
"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 Error: [%s]' % data['error'])
return data | [
"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)
LAST_VERSION = utils.last_version()
if LAST_VERSION is not None and LAST_VERSION != obj.version:
if utils.decode_version(VERSION) < utils.decode_version(LAST_VERSION):
try:
send_mail(
(
'%sA new version of django-cas-server is available'
) % settings.EMAIL_SUBJECT_PREFIX,
u'''
A new version of the django-cas-server is available.
Your version: %s
New version: %s
Upgrade using:
* pip install -U django-cas-server
* fetching the last release on
https://github.com/nitmir/django-cas-server/ or on
https://pypi.org/project/django-cas-server/
After upgrade, do not forget to run:
* ./manage.py migrate
* ./manage.py collectstatic
and to reload your wsgi server (apache2, uwsgi, gunicord, etc…)
--\u0020
django-cas-server
'''.strip() % (VERSION, LAST_VERSION),
settings.SERVER_EMAIL,
["%s <%s>" % admin for admin in settings.ADMINS],
fail_silently=False,
)
obj.version = LAST_VERSION
obj.save()
except smtplib.SMTPException as error: # pragma: no cover (should not happen)
logger.error("Unable to send new version mail: %s" % error) | [
"\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 = urllib_parse.urlencode(params)
return url + '?' + query | [
"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)
return url | [
"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(
"//cas:proxyTicket",
namespaces={"cas": "http://www.yale.edu/tp/cas"}
)
if len(tickets) == 1:
return tickets[0].text
errors = root.xpath(
"//cas:authenticationFailure",
namespaces={"cas": "http://www.yale.edu/tp/cas"}
)
if len(errors) == 1:
raise CASError(errors[0].attrib['code'], errors[0].text)
raise CASError("Bad http code %s" % response.code) | [
"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_parse.urlencode(params))
page = urllib_request.urlopen(url)
try:
verified = page.readline().strip()
if verified == b'yes':
charset = self.get_page_charset(page, default="ascii")
user = self.u(page.readline().strip(), charset)
return user, None, None
else:
return None, None, None
finally:
page.close() | [
"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_TEMPLATE.format(
request_id=request_id,
timestamp=timestamp,
ticket=ticket,
).encode('utf8') | [
"\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 valid CAS Service Ticket obtained as a response parameter at login.\n "
] |
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,
client_strategy="RESTARTABLE",
auto_bind=True
)
cls._conn = conn
return conn | [
"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.get_fields()
if hasattr(field, "attname")
]
# backward compatibility with django 1.7
except AttributeError: # pragma: no cover (only used by django 1.7)
field_names = self.user._meta.get_all_field_names()
for name in field_names:
attr[name] = getattr(self.user, name)
# unfold user_permissions many to many relation
if 'user_permissions' in attr:
attr['user_permissions'] = [
(
u"%s.%s" % (
perm.content_type.model_class().__module__,
perm.content_type.model_class().__name__
),
perm.codename
) for perm in attr['user_permissions'].filter()
]
# unfold group many to many relation
if 'groups' in attr:
attr['groups'] = [group.name for group in attr['groups'].filter()]
return attr
else:
return {} | [
"\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_VERSION
if LAST_VERSION is not None:
params["upgrade_available"] = decode_version(VERSION) < decode_version(LAST_VERSION)
else:
params["upgrade_available"] = False
if settings.CAS_INFO_MESSAGES_ORDER:
params["CAS_INFO_RENDER"] = []
for msg_name in settings.CAS_INFO_MESSAGES_ORDER:
if msg_name in settings.CAS_INFO_MESSAGES:
if not isinstance(settings.CAS_INFO_MESSAGES[msg_name], dict):
continue
msg = settings.CAS_INFO_MESSAGES[msg_name].copy()
if "message" in msg:
msg["name"] = msg_name
# use info as default infox type
msg["type"] = msg.get("type", "info")
# make box discardable by default
msg["discardable"] = msg.get("discardable", True)
msg_hash = (
six.text_type(msg["message"]).encode("utf-8") +
msg["type"].encode("utf-8")
)
# hash depend of the rendering language
msg["hash"] = hashlib.md5(msg_hash).hexdigest()
params["CAS_INFO_RENDER"].append(msg)
return params | [
"\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 in json\n :rtype: django.http.HttpResponse\n "
] |
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 attribute to import)
if not isinstance(path, six.text_type):
return path
if u"." not in path:
ValueError("%r should be of the form `module.attr` and we just got `attr`" % path)
module, attr = path.rsplit(u'.', 1)
try:
return getattr(import_module(module), attr)
except ImportError:
raise ImportError("Module %r not found" % module)
except AttributeError:
raise AttributeError("Module %r has not attribut %r" % (module, attr)) | [
"\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 ``url_name`` with ``params`` as querystring.\n :rtype: django.http.HttpResponseRedirect\n "
] |
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 :param **kwargs: additional parameters needed to compure the reverse URL\n :return: The computed reverse URL of ``url_name`` with possible querystring from ``params``\n :rtype: unicode\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 params | [
"\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 :return: A copy of get_or_post_params\n :rtype: dict\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,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None
) | [
"\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: the maximum validity age of the cookie\n "
] |
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:
params = copy_params(request.GET, ignore_params)
if params:
service_url += u"?%s" % urlencode(params)
return service_url | [
"\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 omitting some parameters from\n ``ignore_params`` in the querystring.\n :rtype: unicode\n "
] |
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 isinstance(value, bytes):
value = value.encode('utf-8')
params[key] = value
url_parts = list(urlparse(url))
query = dict(parse_qsl(url_parts[4]))
query.update(params)
# make the params order deterministic
query = list(query.items())
query.sort()
url_query = urlencode(query)
if not isinstance(url_query, bytes): # pragma: no cover in python3 urlencode return an unicode
url_query = url_query.encode("utf-8")
url_parts[4] = url_query
return urlunparse(url_parts).decode('utf-8') | [
"\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 querystring\n :rtype: unicode\n "
] |
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:
break
return error | [
"\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' % (prefix, random_part)
else:
return random_part | [
"\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: unicode\n "
] |
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
else:
hashed = crypt.crypt("", salt)
if not hashed or '$' not in hashed[1:]:
return False
else:
return True
else:
return True | [
"\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(charset)
if method == "plain":
return password == hashed_password
elif method == "crypt":
if hashed_password.startswith(b'$'):
salt = b'$'.join(hashed_password.split(b'$', 3)[:-1])
elif hashed_password.startswith(b'_'): # pragma: no cover old BSD format not supported
salt = hashed_password[:9]
else:
salt = hashed_password[:2]
if six.PY3:
password = password.decode(charset)
salt = salt.decode(charset)
hashed_password = hashed_password.decode(charset)
if not crypt_salt_is_valid(salt):
raise ValueError("System crypt implementation do not support the salt %r" % salt)
crypted_password = crypt.crypt(password, salt)
return crypted_password == hashed_password
elif method == "ldap":
scheme = LdapHashUserPassword.get_scheme(hashed_password)
salt = LdapHashUserPassword.get_salt(hashed_password)
return LdapHashUserPassword.hash(scheme, password, salt, charset=charset) == hashed_password
elif (
method.startswith("hex_") and
method[4:] in {"md5", "sha1", "sha224", "sha256", "sha384", "sha512"}
):
return getattr(
hashlib,
method[4:]
)(password).hexdigest().encode("ascii") == hashed_password.lower()
else:
raise ValueError("Unknown password method check %r" % method) | [
"\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\"``, ``\"plain\"``\n :param password: The user inputed password\n :type password: :obj:`str` or :obj:`unicode`\n :param hashed_password: The hashed password as stored in the database\n :type hashed_password: :obj:`str` or :obj:`unicode`\n :param str charset: The used char encoding (also used internally, so it must be valid for\n the charset used by ``password`` when it was initially )\n :return: True if ``password`` match ``hashed_password`` using ``method``,\n ``False`` otherwise\n :rtype: bool\n "
] |
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) < cache_delta:
return version
else:
try:
req = requests.get(settings.CAS_NEW_VERSION_JSON_URL)
data = json.loads(req.text)
version = data["info"]["version"]
last_version._cache = (time.time(), version, True)
return version
except (
KeyError,
ValueError,
requests.exceptions.RequestException
) as error: # pragma: no cover (should not happen unless pypi is not available)
logger.error(
"Unable to fetch %s: %s" % (settings.CAS_NEW_VERSION_JSON_URL, error)
)
last_version._cache = (time.time(), version, False) | [
"\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 :raises LdapHashUserPassword.BadScheme: always\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._test_scheme_salt(scheme)
try:
return scheme + base64.b64encode(
cls._schemes_to_hash[scheme](password + salt).digest() + salt
)
except KeyError:
if six.PY3:
password = password.decode(charset)
salt = salt.decode(charset)
if not crypt_salt_is_valid(salt):
raise cls.BadSalt("System crypt implementation do not support the salt %r" % salt)
hashed_password = crypt.crypt(password, salt)
if six.PY3:
hashed_password = hashed_password.encode(charset)
return scheme + hashed_password | [
"\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 ``scheme`` requires any\n :param str charset: The encoding of ``scheme``, ``password`` and ``salt``\n :return: The hashed password encoded with ``charset``\n :rtype: bytes\n "
] |
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]
scheme = scheme.upper() + b"}"
return scheme | [
"\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'$', 3)[:-1])[len(scheme):]
else:
try:
hashed_passord = base64.b64decode(hashed_passord[len(scheme):])
except (TypeError, binascii.Error) as error:
raise cls.BadHash("Bad base64: %s" % error)
if len(hashed_passord) < cls._schemes_to_len[scheme]:
raise cls.BadHash("Hash too short for the scheme %s" % scheme)
return hashed_passord[cls._schemes_to_len[scheme]:] | [
"\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_passord`` or if the\n hashed password is too short for the scheme found.\n "
] |
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:
attributs = {}
attributs["provider"] = self.provider.suffix
self.username = username
self.attributs = attributs
user = FederatedUser.objects.update_or_create(
username=username,
provider=self.provider,
defaults=dict(attributs=attributs, ticket=ticket)
)[0]
user.save()
self.federated_username = user.federated_username
return True
else:
return False | [
"\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: ``True`` if the validation succeed, else ``False``.\n :rtype: bool\n "
] |
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 cover (ignore if the FederateSLO already exists)
pass | [
"\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: A logged user session_key matching ``username``.\n :param unicode ticket: A ticket used to authentication ``username`` for the session\n ``session_key``.\n "
] |
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 FederateSLO.objects.filter(ticket=slo.text):
logger.info(
"Got an SLO requests for ticket %s, logging out user %s" % (
federate_slo.username,
federate_slo.ticket
)
)
session = SessionStore(session_key=federate_slo.session_key)
session.flush()
try:
user = User.objects.get(
username=federate_slo.username,
session_key=federate_slo.session_key
)
user.logout()
user.delete()
except User.DoesNotExist: # pragma: no cover (should not happen)
pass
federate_slo.delete() | [
"\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 Out\n requests.\n "
] |
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 directives
lang = node['language']
highlight_args['force'] = True
if 'linenos' in node:
linenos = node['linenos']
def warner(msg):
self.builder.warn(msg, (self.builder.current_docname, node.line))
highlighted = self.highlighter.highlight_block(node.rawsource, lang,
warn=warner,
linenos=linenos,
**highlight_args)
starttag = self.starttag(node, 'div', suffix='',
CLASS='highlight-%s snippet' % lang)
self.body.append(starttag)
self.body.append('<div class="snippet-filename">%s</div>\n''' % (fname,))
self.body.append(highlighted)
self.body.append('</div>\n')
raise nodes.SkipNode | [
"\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 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
if 'linenos' in node:
linenos = node['linenos']
def warner(msg):
self.builder.warn(msg, (self.curfilestack[-1], node.line))
hlcode = self.highlighter.highlight_block(code, lang, warn=warner,
linenos=linenos,
**highlight_args)
self.body.append(
'\n{\\colorbox[rgb]{0.9,0.9,0.9}'
'{\\makebox[\\textwidth][l]'
'{\\small\\texttt{%s}}}}\n' % (
# Some filenames have '_', which is special in latex.
fname.replace('_', r'\_'),
)
)
if self.table:
hlcode = hlcode.replace('\\begin{Verbatim}',
'\\begin{OriginalVerbatim}')
self.table.has_problematic = True
self.table.has_verbatim = True
hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim}
hlcode = hlcode.rstrip() + '\n'
self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' %
(self.table and 'Original' or ''))
# Prevent rawsource from appearing in output a second time.
raise nodes.SkipNode | [
"\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)
request = context.get('request')
if request is None:
# Can't work without the request object.
return ''
active = False
views = viewnames.split('||')
for viewname in views:
path = reverse(viewname.strip(), args=args, kwargs=kwargs)
request_path = escape_uri_path(request.path)
if strict:
active = request_path == path
else:
active = request_path.find(path) == 0
if active:
break
if active:
return css_class
return '' | [
"\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 render.\n :param strict: If True, the tag will perform an exact match with the request path.\n :return:\n "
] |
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_password(cleaned_data["password"]):
cleaned_data["username"] = auth.username
else:
raise forms.ValidationError(
_(u"The credentials you provided cannot be determined to be authentic.")
)
return cleaned_data | [
"\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 happed as if the FederatedUser do not exists, super should
# raise before a ValidationError("bad user")
except models.FederatedUser.DoesNotExist: # pragma: no cover (should not happend)
raise forms.ValidationError(
_(u"User not found in the temporary database, please try to reconnect")
)
return cleaned_data | [
"\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 to a :class:`FederatedUser<cas_server.models.FederatedUser>`.\n :return: The cleaned POST data\n :rtype: dict\n "
] |
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 username:
if all_session:
logger.info("Logging out user %s from all sessions." % username)
else:
logger.info("Logging out user %s." % username)
users = []
# try to get the user from the current session
try:
users.append(
models.User.objects.get(
username=username,
session_key=self.request.session.session_key
)
)
except models.User.DoesNotExist:
# if user not found in database, flush the session anyway
self.request.session.flush()
# If all_session is set, search all of the user sessions
if all_session:
users.extend(
models.User.objects.filter(
username=username
).exclude(
session_key=self.request.session.session_key
)
)
# Iterate over all user sessions that have to be logged out
for user in users:
# get the user session
session = SessionStore(session_key=user.session_key)
# flush the session
session.flush()
# send SLO requests
user.logout(self.request)
# delete the user
user.delete()
# increment the destroyed session counter
session_nb += 1
if username:
logger.info("User %s logged out" % username)
return session_nb | [
"\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.CAS_FEDERATE:
try:
user = FederatedUser.get_from_federated_username(
self.request.session.get("username")
)
auth = CASFederateValidateUser(user.provider, service_url="")
except FederatedUser.DoesNotExist:
auth = None
session_nb = self.logout(self.request.GET.get("all"))
# if CAS federation mode is enable, redirect to user CAS logout page, appending the
# current querystring
if settings.CAS_FEDERATE:
if auth is not None:
params = utils.copy_params(request.GET, ignore={"forget_provider"})
url = auth.get_logout_url()
response = HttpResponseRedirect(utils.update_url(url, params))
if request.GET.get("forget_provider"):
response.delete_cookie("remember_provider")
return response
# if service is set, redirect to service after logout
if self.service:
list(messages.get_messages(request)) # clean messages before leaving the django app
return HttpResponseRedirect(self.service)
# if service is not set but url is set, redirect to url after logout
elif self.url:
list(messages.get_messages(request)) # clean messages before leaving the django app
return HttpResponseRedirect(self.url)
else:
# build logout message depending of the number of sessions the user logs out
if session_nb == 1:
logout_msg = mark_safe(_(
"<h3>Logout successful</h3>"
"You have successfully logged out from the Central Authentication Service. "
"For security reasons, close your web browser."
))
elif session_nb > 1:
logout_msg = mark_safe(_(
"<h3>Logout successful</h3>"
"You have successfully logged out from %d sessions of the Central "
"Authentication Service. "
"For security reasons, close your web browser."
) % session_nb)
else:
logout_msg = mark_safe(_(
"<h3>Logout successful</h3>"
"You were already logged out from the Central Authentication Service. "
"For security reasons, close your web browser."
))
# depending of settings, redirect to the login page with a logout message or display
# the logout page. The default is to display tge logout page.
if settings.CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT:
messages.add_message(request, messages.SUCCESS, logout_msg)
if self.ajax:
url = reverse("cas_server:login")
data = {
'status': 'success',
'detail': 'logout',
'url': url,
'session_nb': session_nb
}
return json_response(request, data)
else:
return redirect("cas_server:login")
else:
if self.ajax:
data = {'status': 'success', 'detail': 'logout', 'session_nb': session_nb}
return json_response(request, data)
else:
return render(
request,
settings.CAS_LOGOUT_TEMPLATE,
utils.context({'logout_msg': logout_msg})
) | [
"\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
return CASFederateValidateUser(provider, service_url, renew=renew) | [
"\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: :class:`federate.CASFederateValidateUser\n <cas_server.federate.CASFederateValidateUser>`\n "
] |
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("cas_server:login")
# POST with a provider suffix, this is probably an SLO request. csrf is disabled for
# allowing SLO requests reception
try:
provider = FederatedIendityProvider.objects.get(suffix=provider)
auth = self.get_cas_client(request, provider)
try:
auth.clean_sessions(request.POST['logoutRequest'])
except (KeyError, AttributeError):
pass
return HttpResponse("ok")
# else, a User is trying to log in using an identity provider
except FederatedIendityProvider.DoesNotExist:
# Manually checking for csrf to protect the code below
reason = CsrfViewMiddleware().process_view(request, None, (), {})
if reason is not None: # pragma: no cover (csrf checks are disabled during tests)
return reason # Failed the test, stop here.
form = forms.FederateSelect(request.POST)
if form.is_valid():
params = utils.copy_params(
request.POST,
ignore={"provider", "csrfmiddlewaretoken", "ticket", "lt"}
)
if params.get("renew") == "False":
del params["renew"]
url = utils.reverse_params(
"cas_server:federateAuth",
kwargs=dict(provider=form.cleaned_data["provider"].suffix),
params=params
)
return HttpResponseRedirect(url)
else:
return redirect("cas_server:login") | [
"\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("cas_server:login")
renew = bool(request.GET.get('renew') and request.GET['renew'] != "False")
# Is the user is already authenticated, no need to request authentication to the user
# identity provider.
if self.request.session.get("authenticated") and not renew:
logger.warning("User already authenticated, dropping federated authentication request")
return redirect("cas_server:login")
try:
# get the identity provider from its suffix
provider = FederatedIendityProvider.objects.get(suffix=provider)
# get a CAS client for the user identity provider
auth = self.get_cas_client(request, provider, renew)
# if no ticket submited, redirect to the identity provider CAS login page
if 'ticket' not in request.GET:
logger.info("Trying to authenticate %s again" % auth.provider.server_url)
return HttpResponseRedirect(auth.get_login_url())
else:
ticket = request.GET['ticket']
try:
# if the ticket validation succeed
if auth.verify_ticket(ticket):
logger.info(
"Got a valid ticket for %s from %s" % (
auth.username,
auth.provider.server_url
)
)
params = utils.copy_params(request.GET, ignore={"ticket", "remember"})
request.session["federate_username"] = auth.federated_username
request.session["federate_ticket"] = ticket
auth.register_slo(
auth.federated_username,
request.session.session_key,
ticket
)
# redirect to the the login page for the user to become authenticated
# thanks to the `federate_username` and `federate_ticket` session parameters
url = utils.reverse_params("cas_server:login", params)
response = HttpResponseRedirect(url)
# If the user has checked "remember my identity provider" store it in a
# cookie
if request.GET.get("remember"):
max_age = settings.CAS_FEDERATE_REMEMBER_TIMEOUT
utils.set_cookie(
response,
"remember_provider",
provider.suffix,
max_age
)
return response
# else redirect to the identity provider CAS login page
else:
logger.info(
(
"Got an invalid ticket %s from %s for service %s. "
"Retrying authentication"
) % (
ticket,
auth.provider.server_url,
self.service_url
)
)
return HttpResponseRedirect(auth.get_login_url())
# both xml.etree.ElementTree and lxml.etree exceptions inherit from SyntaxError
except SyntaxError as error:
messages.add_message(
request,
messages.ERROR,
_(
u"Invalid response from your identity provider CAS upon "
u"ticket %(ticket)s validation: %(error)r"
) % {'ticket': ticket, 'error': error}
)
response = redirect("cas_server:login")
response.delete_cookie("remember_provider")
return response
except FederatedIendityProvider.DoesNotExist:
logger.warning("Identity provider suffix %s not found" % provider)
# if the identity provider is not found, redirect to the login page
return redirect("cas_server:login") | [
"\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.method = request.POST.get('method')
self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
if request.POST.get('warned') and request.POST['warned'] != "False":
self.warned = True
self.warn = request.POST.get('warn')
if settings.CAS_FEDERATE:
self.username = request.POST.get('username')
# in federated mode, the valdated indentity provider CAS ticket is used as password
self.ticket = request.POST.get('password') | [
"\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 LT is valid
if lt_send not in lt_valid:
return False
else:
self.request.session['lt'].remove(lt_send)
# we need to redo the affectation for django to detect that the list has changed
# and for its new value to be store in the session
self.request.session['lt'] = self.request.session['lt']
return True | [
"\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(
self.request,
messages.ERROR,
_(u"Invalid login ticket, please try to log in again")
)
elif ret == self.USER_LOGIN_OK:
# On successful login, update the :class:`models.User<cas_server.models.User>` ``date``
# attribute by saving it. (``auto_now=True``)
self.user = models.User.objects.get_or_create(
username=self.request.session['username'],
session_key=self.request.session.session_key
)[0]
self.user.last_login = timezone.now()
self.user.save()
elif ret == self.USER_LOGIN_FAILURE: # bad user login
if settings.CAS_FEDERATE:
self.ticket = None
self.username = None
self.init_form()
# preserve valid LoginTickets from session flush
lt = self.request.session.get('lt', [])
# On login failure, flush the session
self.logout()
# restore valid LoginTickets
self.request.session['lt'] = lt
elif ret == self.USER_ALREADY_LOGGED:
pass
else: # pragma: no cover (should no happen)
raise EnvironmentError("invalid output for LoginView.process_post")
# call the GET/POST common part
response = self.common()
if self.warn:
utils.set_cookie(
response,
"warn",
"on",
10 * 365 * 24 * 3600
)
else:
response.delete_cookie("warn")
return response | [
"\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") or self.renew:
# authentication request receive, initialize the form to use
self.init_form(self.request.POST)
if self.form.is_valid():
self.request.session.set_expiry(0)
self.request.session["username"] = self.form.cleaned_data['username']
self.request.session["warn"] = True if self.form.cleaned_data.get("warn") else False
self.request.session["authenticated"] = True
self.renewed = True
self.warned = True
logger.info("User %s successfully authenticated" % self.request.session["username"])
return self.USER_LOGIN_OK
else:
logger.warning("A login attempt failed")
return self.USER_LOGIN_FAILURE
else:
logger.warning("Received a login attempt for an already-active user")
return self.USER_ALREADY_LOGGED | [
"\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_LOGGED` if the user is already logged and do no request\n reauthentication.\n * :attr:`USER_LOGIN_FAILURE` if the user is not logged or request for\n reauthentication and his credentials are not valid\n * :attr:`USER_LOGIN_OK` if the user is not logged or request for\n reauthentication and his credentials are valid\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.renew = bool(request.GET.get('renew') and request.GET['renew'] != "False")
self.gateway = request.GET.get('gateway')
self.method = request.GET.get('method')
self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
self.warn = request.GET.get('warn')
if settings.CAS_FEDERATE:
# here username and ticket are fetch from the session after a redirection from
# FederateAuth.get
self.username = request.session.get("federate_username")
self.ticket = request.session.get("federate_ticket")
if self.username:
del request.session["federate_username"]
if self.ticket:
del request.session["federate_ticket"] | [
"\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 self.USER_NOT_AUTHENTICATED
return self.USER_AUTHENTICATED | [
"\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 for authentication renewal\n :rtype: int\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': (
self.warn or self.request.session.get("warn") or self.request.COOKIES.get('warn')
),
'lt': self.request.session['lt'][-1],
'renew': self.renew
}
if settings.CAS_FEDERATE:
if self.username and self.ticket:
form_initial['username'] = self.username
form_initial['password'] = self.ticket
form_initial['ticket'] = self.ticket
self.form = forms.FederateUserCredential(
values,
initial=form_initial
)
else:
self.form = forms.FederateSelect(values, initial=form_initial)
else:
self.form = forms.UserCredential(
values,
initial=form_initial
) | [
"\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)
# if the user has asked to be warned before any login to a service
if self.request.session.get("warn", True) and not self.warned:
messages.add_message(
self.request,
messages.WARNING,
_(u"Authentication has been required by service %(name)s (%(url)s)") %
{'name': service_pattern.name, 'url': self.service}
)
if self.ajax:
data = {"status": "error", "detail": "confirmation needed"}
return json_response(self.request, data)
else:
warn_form = forms.WarnForm(initial={
'service': self.service,
'renew': self.renew,
'gateway': self.gateway,
'method': self.method,
'warned': True,
'lt': self.request.session['lt'][-1]
})
return render(
self.request,
settings.CAS_WARN_TEMPLATE,
utils.context({'form': warn_form})
)
else:
# redirect, using method ?
list(messages.get_messages(self.request)) # clean messages before leaving django
redirect_url = self.user.get_service_url(
self.service,
service_pattern,
renew=self.renewed
)
if not self.ajax:
return HttpResponseRedirect(redirect_url)
else:
data = {"status": "success", "detail": "auth", "url": redirect_url}
return json_response(self.request, data)
except ServicePattern.DoesNotExist:
error = 1
messages.add_message(
self.request,
messages.ERROR,
_(u'Service %(url)s not allowed.') % {'url': self.service}
)
except models.BadUsername:
error = 2
messages.add_message(
self.request,
messages.ERROR,
_(u"Username not allowed")
)
except models.BadFilter:
error = 3
messages.add_message(
self.request,
messages.ERROR,
_(u"User characteristics not allowed")
)
except models.UserFieldNotDefined:
error = 4
messages.add_message(
self.request,
messages.ERROR,
_(u"The attribute %(field)s is needed to use"
u" that service") % {'field': service_pattern.user_field}
)
# if gateway is set and auth failed redirect to the service without authentication
if self.gateway and not self.ajax:
list(messages.get_messages(self.request)) # clean messages before leaving django
return HttpResponseRedirect(self.service)
if not self.ajax:
return render(
self.request,
settings.CAS_LOGGED_TEMPLATE,
utils.context({'session': self.request.session})
)
else:
data = {"status": "error", "detail": "auth", "code": error}
return json_response(self.request, data) | [
"\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 parameter\n * The redirection to the service URL without a ticket if ticket generation failed\n and the :attr:`gateway` attribute is set\n * The rendering of the ``settings.CAS_LOGGED_TEMPLATE`` template with some error\n messages if the ticket generation failed (e.g: user not allowed).\n :rtype: django.http.HttpResponse\n "
] |
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"),
session_key=self.request.session.session_key
)
# if not found, flush the session and redirect to the login page
except models.User.DoesNotExist:
logger.warning(
"User %s seems authenticated but is not found in the database." % (
self.request.session.get("username"),
)
)
self.logout()
if self.ajax:
data = {
"status": "error",
"detail": "login required",
"url": utils.reverse_params("cas_server:login", params=self.request.GET)
}
return json_response(self.request, data)
else:
return utils.redirect_params("cas_server:login", params=self.request.GET)
# if login against a service
if self.service:
return self.service_login()
# else display the logged template
else:
if self.ajax:
data = {"status": "success", "detail": "logged"}
return json_response(self.request, data)
else:
return render(
self.request,
settings.CAS_LOGGED_TEMPLATE,
utils.context({'session': self.request.session})
) | [
"\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
list(messages.get_messages(self.request))
return HttpResponseRedirect(self.service)
if settings.CAS_SHOW_SERVICE_MESSAGES:
if self.request.session.get("authenticated") and self.renew:
messages.add_message(
self.request,
messages.WARNING,
_(u"Authentication renewal required by service %(name)s (%(url)s).") %
{'name': service_pattern.name, 'url': self.service}
)
else:
messages.add_message(
self.request,
messages.WARNING,
_(u"Authentication required by service %(name)s (%(url)s).") %
{'name': service_pattern.name, 'url': self.service}
)
except ServicePattern.DoesNotExist:
if settings.CAS_SHOW_SERVICE_MESSAGES:
messages.add_message(
self.request,
messages.ERROR,
_(u'Service %s not allowed') % self.service
)
if self.ajax:
data = {
"status": "error",
"detail": "login required",
"url": utils.reverse_params("cas_server:login", params=self.request.GET)
}
return json_response(self.request, data)
else:
if settings.CAS_FEDERATE:
if self.username and self.ticket:
return render(
self.request,
settings.CAS_LOGIN_TEMPLATE,
utils.context({
'form': self.form,
'auto_submit': True,
'post_url': reverse("cas_server:login")
})
)
else:
if (
self.request.COOKIES.get('remember_provider') and
FederatedIendityProvider.objects.filter(
suffix=self.request.COOKIES['remember_provider']
)
):
params = utils.copy_params(self.request.GET)
url = utils.reverse_params(
"cas_server:federateAuth",
params=params,
kwargs=dict(provider=self.request.COOKIES['remember_provider'])
)
return HttpResponseRedirect(url)
else:
# if user is authenticated and auth renewal is requested, redirect directly
# to the user identity provider
if self.renew and self.request.session.get("authenticated"):
try:
user = FederatedUser.get_from_federated_username(
self.request.session.get("username")
)
params = utils.copy_params(self.request.GET)
url = utils.reverse_params(
"cas_server:federateAuth",
params=params,
kwargs=dict(provider=user.provider.suffix)
)
return HttpResponseRedirect(url)
# Should normally not happen: if the user is logged, it exists in the
# database.
except FederatedUser.DoesNotExist: # pragma: no cover
pass
return render(
self.request,
settings.CAS_LOGIN_TEMPLATE,
utils.context({
'form': self.form,
'post_url': reverse("cas_server:federateAuth")
})
)
else:
return render(
self.request,
settings.CAS_LOGIN_TEMPLATE,
utils.context({'form': self.form})
) | [
"\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``\n and the \"remember my identity provider\" cookie is found\n :rtype: django.http.HttpResponse\n "
] |
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.not_authenticated() | [
"\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 value of :meth:`not_authenticated` otherwise\n :rtype: django.http.HttpResponse\n "
] |
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:
return HttpResponse(
"no\nplease set CAS_AUTH_SHARED_SECRET",
content_type="text/plain; charset=utf-8"
)
if secret != settings.CAS_AUTH_SHARED_SECRET:
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
if not username or not password or not service:
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
form = forms.UserCredential(
request.POST,
initial={
'service': service,
'method': 'POST',
'warn': False
}
)
if form.is_valid():
try:
user = models.User.objects.get_or_create(
username=form.cleaned_data['username'],
session_key=request.session.session_key
)[0]
user.save()
# is the service allowed
service_pattern = ServicePattern.validate(service)
# is the current user allowed on this service
service_pattern.check_user(user)
if not request.session.get("authenticated"):
user.delete()
return HttpResponse(u"yes\n", content_type="text/plain; charset=utf-8")
except (ServicePattern.DoesNotExist, models.ServicePatternException):
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
else:
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8") | [
"\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 username is allowed on service).\n ``HttpResponse(u\"no\\\\n…\")`` otherwise, with possibly an error message on the second\n line.\n :rtype: django.http.HttpResponse\n "
] |
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
if service and ticket:
try:
# search for the ticket, associated at service that is not yet validated but is
# still valid
ticket = ServiceTicket.get(ticket, renew, service)
logger.info(
"Validate: Service ticket %s validated, user %s authenticated on service %s" % (
ticket.value,
ticket.user.username,
ticket.service
)
)
return HttpResponse(
u"yes\n%s\n" % ticket.username(),
content_type="text/plain; charset=utf-8"
)
except ServiceTicket.DoesNotExist:
logger.warning(
(
"Validate: Service ticket %s not found or "
"already validated, auth to %s failed"
) % (
ticket,
service
)
)
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
else:
logger.warning("Validate: service or ticket missing")
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8") | [
"\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 :rtype: django.http.HttpResponse\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 if request.GET.get('renew') else False
# service and ticket parameter are mandatory
if not self.service or not self.ticket:
logger.warning("ValidateService: missing ticket or service")
return ValidateError(
u'INVALID_REQUEST',
u"you must specify a service and a ticket"
).render(request)
else:
try:
# search the ticket in the database
self.ticket, proxies = self.process_ticket()
# prepare template rendering context
params = {
'username': self.ticket.username(),
'attributes': self.ticket.attributs_flat(),
'proxies': proxies,
'auth_date': self.ticket.user.last_login.replace(microsecond=0).isoformat(),
'is_new_login': 'true' if self.ticket.renew else 'false'
}
# if pgtUrl is set, require https or localhost
if self.pgt_url and (
self.pgt_url.startswith("https://") or
re.match(r"^http://(127\.0\.0\.1|localhost)(:[0-9]+)?(/.*)?$", self.pgt_url)
):
return self.process_pgturl(params)
else:
logger.info(
"ValidateService: ticket %s validated for user %s on service %s." % (
self.ticket.value,
self.ticket.user.username,
self.ticket.service
)
)
logger.debug(
"ValidateService: User attributs are:\n%s" % (
pprint.pformat(self.ticket.attributs),
)
)
return render(
request,
"cas_server/serviceValidate.xml",
params,
content_type="text/xml; charset=utf-8"
)
except ValidateError as error:
logger.warning(
"ValidateService: validation error: %s %s" % (error.code, error.msg)
)
return error.render(request) | [
"\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`` otherwise.\n :rtype: django.http.HttpResponse\n "
] |
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)
try:
for prox in ticket.proxies.all():
proxies.append(prox.url)
except AttributeError:
pass
if ticket.service != self.service:
raise ValidateError(u'INVALID_SERVICE', self.service)
return ticket, proxies
except Ticket.DoesNotExist:
raise ValidateError(u'INVALID_TICKET', self.ticket)
except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist):
raise ValidateError(u'INVALID_TICKET', 'ticket not found') | [
"\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(
user=self.ticket.user,
service=self.pgt_url,
service_pattern=pattern,
single_log_out=pattern.single_log_out
)
url = utils.update_url(self.pgt_url, {'pgtIou': proxyid, 'pgtId': pticket.value})
try:
ret = requests.get(url, verify=settings.CAS_PROXY_CA_CERTIFICATE_PATH)
if ret.status_code == 200:
params['proxyGrantingTicket'] = proxyid
else:
pticket.delete()
logger.info(
(
"ValidateService: ticket %s validated for user %s on service %s. "
"Proxy Granting Ticket transmited to %s."
) % (
self.ticket.value,
self.ticket.user.username,
self.ticket.service,
self.pgt_url
)
)
logger.debug(
"ValidateService: User attributs are:\n%s" % (
pprint.pformat(self.ticket.attributs),
)
)
return render(
self.request,
"cas_server/serviceValidate.xml",
params,
content_type="text/xml; charset=utf-8"
)
except requests.exceptions.RequestException as error:
error = utils.unpack_nested_exception(error)
raise ValidateError(
u'INVALID_PROXY_CALLBACK',
u"%s: %s" % (type(error), str(error))
)
else:
raise ValidateError(
u'INVALID_PROXY_CALLBACK',
u"callback url not allowed by configuration"
)
except ServicePattern.DoesNotExist:
raise ValidateError(
u'INVALID_PROXY_CALLBACK',
u'callback url not allowed by configuration'
) | [
"\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.HttpResponse\n "
] |
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.target_service:
return self.process_proxy()
else:
raise ValidateError(
u'INVALID_REQUEST',
u"you must specify and pgt and targetService"
)
except ValidateError as error:
logger.warning("Proxy: validation error: %s %s" % (error.code, error.msg))
return error.render(request) | [
"\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 :rtype: django.http.HttpResponse\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:
raise ValidateError(
u'UNAUTHORIZED_SERVICE',
u'the service %s does not allow proxy tickets' % self.target_service
)
# is the proxy granting ticket valid
ticket = ProxyGrantingTicket.get(self.pgt)
# is the pgt user allowed on the target service
pattern.check_user(ticket.user)
pticket = ticket.user.get_ticket(
ProxyTicket,
self.target_service,
pattern,
renew=False
)
models.Proxy.objects.create(proxy_ticket=pticket, url=ticket.service)
logger.info(
"Proxy ticket created for user %s on service %s." % (
ticket.user.username,
self.target_service
)
)
return render(
self.request,
"cas_server/proxy.xml",
{'ticket': pticket.value},
content_type="text/xml; charset=utf-8"
)
except (Ticket.DoesNotExist, ProxyGrantingTicket.DoesNotExist):
raise ValidateError(u'INVALID_TICKET', u'PGT %s not found' % self.pgt)
except ServicePattern.DoesNotExist:
raise ValidateError(u'UNAUTHORIZED_SERVICE', self.target_service)
except (models.BadUsername, models.BadFilter, models.UserFieldNotDefined):
raise ValidateError(
u'UNAUTHORIZED_USER',
u'User %s not allowed on %s' % (ticket.user.username, self.target_service)
) | [
"\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 +
timedelta(seconds=self.ticket.VALIDITY)).isoformat()
params = {
'IssueInstant': timezone.now().isoformat(),
'expireInstant': expire_instant,
'Recipient': self.target,
'ResponseID': utils.gen_saml_id(),
'username': self.ticket.username(),
'attributes': self.ticket.attributs_flat(),
'auth_date': self.ticket.user.last_login.replace(microsecond=0).isoformat(),
'is_new_login': 'true' if self.ticket.renew else 'false'
}
logger.info(
"SamlValidate: ticket %s validated for user %s on service %s." % (
self.ticket.value,
self.ticket.user.username,
self.ticket.service
)
)
logger.debug(
"SamlValidate: User attributes are:\n%s" % pprint.pformat(self.ticket.attributs)
)
return render(
request,
"cas_server/samlValidate.xml",
params,
content_type="text/xml; charset=utf-8"
)
except SamlValidateError as error:
logger.warning("SamlValidate: validation error: %s %s" % (error.code, error.msg))
return error.render(request) | [
"\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 :rtype: django.http.HttpResponse\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:
raise SamlValidateError(
u'AuthnFailed',
u'TARGET %s does not match ticket service' % self.target
)
return ticket
except (IndexError, KeyError):
raise SamlValidateError(u'VersionMismatch')
except Ticket.DoesNotExist:
raise SamlValidateError(
u'AuthnFailed',
u'ticket %s should begin with PT- or ST-' % ticket
)
except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist):
raise SamlValidateError(u'AuthnFailed', u'ticket %s not found' % ticket) | [
"\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 passed")
return 0
except ValidationError as e:
raise click.ClickException(str(e)) | [
"\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
allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
with ErrorDict() as errors:
if not all(allowed.match(x) for x in hostname.split(".")):
errors.add_error(
'invalid',
MESSAGES['host']['invalid'].format(value),
)
if path:
errors.add_error(
'path',
MESSAGES['host']['may_not_include_path'].format(value),
)
if scheme:
errors.add_error(
'scheme',
MESSAGES['host']['may_not_include_scheme'].format(value),
) | [
"\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 open(os.path.expanduser(str(source)), 'r') as source_file:
raw_source = source_file.read()
elif isinstance(source, six.string_types):
parts = urlparse.urlparse(source)
if parts.scheme and parts.netloc:
response = requests.get(source)
if isinstance(response.content, six.binary_type):
raw_source = six.text_type(response.content, encoding='utf-8')
else:
raw_source = response.content
else:
raw_source = source
try:
try:
return json.loads(raw_source)
except ValueError:
pass
try:
return yaml.safe_load(raw_source)
except (yaml.scanner.ScannerError, yaml.parser.ParserError):
pass
except NameError:
pass
raise ValueError(
"Unable to parse `{0}`. Tried yaml and json.".format(source),
) | [
"\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 = normalize_response(raw_response, request=request)
if response is not None:
validate_response(
response=response,
request_method=request_method,
schema=schema
) | [
"\n Validate the response of an api call against a swagger schema.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.