def process_view(self, request, view_func, view_args, view_kwargs): """Forwards unauthenticated requests to the admin page to the CAS login URL, as well as calls to django.contrib.auth.views.login and logout. """ if view_func == login: return cas_login(request, *view_args, **view_kwargs) elif view_func == logout: return cas_logout(request, *view_args, **view_kwargs) if settings.CAS_ADMIN_PREFIX: if not request.path.startswith(settings.CAS_ADMIN_PREFIX): return None elif not view_func.__module__.startswith('django.contrib.admin.'): return None if request.user.is_authenticated(): if request.user.is_staff: return None else: error = ('<h1>Forbidden</h1><p>You do not have staff ' 'privileges.</p>') return HttpResponseForbidden(error) params = urllib_parse.urlencode( {REDIRECT_FIELD_NAME: request.get_full_path()}) return HttpResponseRedirect(reverse(cas_login) + '?' + params)
def process_view(self, request, view_func, view_args, view_kwargs): """Forwards unauthenticated requests to the admin page to the CAS login URL, as well as calls to django.contrib.auth.views.login and logout. """ if view_func == login: return cas_login(request, *view_args, **view_kwargs) elif view_func == logout: return cas_logout(request, *view_args, **view_kwargs) if view_func in (cas_login, cas_logout): return None if settings.CAS_ADMIN_PREFIX: if not request.path.startswith(settings.CAS_ADMIN_PREFIX): return None elif not view_func.__module__.startswith('django.contrib.admin.'): return None if request.user.is_authenticated(): if request.user.is_staff: return None else: raise PermissionDenied(_('You do not have staff privileges.')) params = urllib_parse.urlencode({REDIRECT_FIELD_NAME: request.get_full_path()}) return HttpResponseRedirect(reverse(cas_login) + '?' + params)
def handle(self, **options): self.mime_type_magic = magic.Magic(mime=True) self.gb_parties, _ = PartySet.objects.get_or_create(slug='gb') self.ni_parties, _ = PartySet.objects.get_or_create(slug='ni') start = 0 per_page = 30 url = 'http://search.electoralcommission.org.uk/api/search/Registrations' params = { 'rows': per_page, 'et': ["pp", "ppm"], 'register': ["gb", "ni", 'none'], 'regStatus': ["registered", "deregistered", "lapsed"], 'period': [ '127', '135', '136', '205', '207', '217', '2508', '2510', '2512', '2514', '281', '289', '301', '303', '305', '3560', '37', '38', '4', '404', '410', '445', '49', '60', '62', '68', '74', ] } with transaction.atomic(): total = None while total is None or start <= total: params['start'] = start resp = requests.get( url + '?' + urlencode(params, doseq=True)).json() if total is None: total = resp['Total'] self.parse_data(resp['Result']) start += per_page
def get_logout_url(self, redirect_url=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(self.server_url, 'logout') if redirect_url: param_name = self._get_logout_redirect_parameter_name() url += '?' + urllib_parse.urlencode({param_name: redirect_url}) return url
def get_logout_url(self, redirect_url=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(self.server_url, 'logout') if redirect_url: param_name = self._get_logout_redirect_parameter_name() url += '?' + urllib_parse.urlencode({param_name: redirect_url}) return url
def verify_ticket(self, ticket): """Verifies CAS 2.0+ XML-based authentication ticket. Returns username on success and None on failure. """ try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree user = None pgtiou = None params = [('ticket', ticket), ('service', self.service_url)] if self.proxy_callback: params.append(('pgtUrl', self.proxy_callback)) url = (urllib_parse.urljoin(self.server_url, 'serviceValidate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('authenticationSuccess'): for element in tree[0]: if element.tag.endswith('user'): user = element.text elif element.tag.endswith('proxyGrantingTicket'): pgtiou = element.text return user, None, pgtiou else: return None, None, None finally: page.close()
def get_proxy_url(self, pgt): """Returns proxy url, given the proxy granting ticket""" params = urllib_parse.urlencode({ 'pgt': pgt, 'targetService': self.get_service_url() }) return "%s/proxy?%s" % (self.server_url, params)
def _verify_cas3(ticket, service): """Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes. Returns username on success and None on failure. """ try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree params = [('ticket', ticket), ('service', service)] url = (urllib_parse.urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: user = None attributes = {} response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('authenticationSuccess'): for element in tree[0]: if element.tag.endswith('user'): user = element.text elif element.tag.endswith('attributes'): for attribute in element: attributes[attribute.tag.split("}").pop()] = attribute.text return user, attributes finally: page.close()
def proxy(request, function=None): target_service = request.GET.get('service') proxy_ticket = request.GET.get('ticket') if target_service: try: proxy_ticket = ProxyGrantingTicket.retrieve_pt(request, target_service) except ProxyError as err: error = "<h1>{0}</h1><p>{1}</p>".format(_('Forbidden'), _(str(err))) return HttpResponseForbidden(error) params = urllib_parse.urlencode({'ticket': proxy_ticket}) if '?' in target_service: proxy_url = target_service + "&" + params else: proxy_url = target_service + "?" + params return HttpResponseRedirect(proxy_url) elif proxy_ticket: service_url = get_service_url(request) user = authenticate(ticket=proxy_ticket, service=service_url, request=request, proxy=True) if user is not None and function is not None: return function(request, user) elif function is None: error = "<h1>{0}</h1><p>{1}</p>".format(_('Error'), _('No proxy function implemented.')) return HttpResponseNotFound(error) else: error = "<h1>{0}</h1><p>{1}</p>".format(_('Forbidden'), _('Proxy failed.')) return HttpResponseForbidden(error) else: return HttpResponse("{0}\n".format(_('Nothing')), content_type="text/plain")
def process_view(self, request, view_func, view_args, view_kwargs): """Forwards unauthenticated requests to the admin page to the CAS login URL, as well as calls to django.contrib.auth.views.login and logout. """ if view_func == login: return cas_login(request, *view_args, **view_kwargs) elif view_func == logout: return cas_logout(request, *view_args, **view_kwargs) if view_func in (cas_login, cas_logout): return None if settings.CAS_ADMIN_PREFIX: if not request.path.startswith(settings.CAS_ADMIN_PREFIX): return None elif not view_func.__module__.startswith('django.contrib.admin.'): return None if view_func.__name__ == 'logout': return HttpResponseRedirect(reverse(settings.CAS_LOGOUT_URL_NAME)) if request.user.is_authenticated: if request.user.is_staff: return None else: raise PermissionDenied(_('You do not have staff privileges.')) params = urllib_parse.urlencode( {REDIRECT_FIELD_NAME: request.get_full_path()}) return HttpResponseRedirect( reverse(settings.CAS_LOGIN_URL_NAME) + '?' + params)
def verify_ticket(self, ticket): """Verifies CAS 2.0+ XML-based authentication ticket.""" try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree user = None pgtiou = None params = [('ticket', ticket), ('service', self.service_url)] if self.proxy_callback: params.append(('pgtUrl', self.proxy_callback)) url = (urllib_parse.urljoin(self.server_url, 'serviceValidate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('authenticationSuccess'): for element in tree[0]: if element.tag.endswith('user'): user = element.text elif element.tag.endswith('proxyGrantingTicket'): pgtiou = element.text return user, None, pgtiou else: return None, None, None finally: page.close()
def get_verification_response(self, ticket): params = [('ticket', ticket), ('service', self.service_url)] if self.proxy_callback: params.append(('pgtUrl', self.proxy_callback)) base_url = urllib_parse.urljoin(self.server_url, 'proxyValidate') url = base_url + '?' + urllib_parse.urlencode(params) page = urlopen(url) return page.read()
def get_verification_response(self, ticket): params = [('ticket', ticket), ('service', self.service_url)] if self.proxy_callback: params.append(('pgtUrl', self.proxy_callback)) base_url = urllib_parse.urljoin(self.server_url, 'proxyValidate') url = base_url + '?' + urllib_parse.urlencode(params) page = urlopen(url) return page.read()
def _verify_cas3_saml(ticket, service): """CAS3 + SAML""" try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree # We do the SAML validation headers = { 'soapaction': 'http://www.oasis-open.org/committees/security', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'accept': 'text/xml', 'connection': 'keep-alive', 'content-type': 'text/xml; ', } params = [('ticket', ticket), ('service', service), ('TARGET', service)] saml_validat_url = urllib_parse.urljoin( settings.CAS_SERVER_URL, 'samlValidate', ) # teste #saml_validat_url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'proxyValidate',) url = Request( saml_validat_url + '?' + urllib_parse.urlencode(params), '', headers, ) print "#############################" print params print urllib_parse.urlencode(params) print url print "SAML" print get_saml_assertion(ticket) print "" from urllib2 import URLError try: print urlopen(url, data=get_saml_assertion(ticket)) except URLError, e: print "um erro::::" print e
def _logout_url(request, next_page=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'logout') if next_page: protocol = ('http://', 'https://')[request.is_secure()] host = request.get_host() url += '?' + urllib_parse.urlencode({'url': protocol + host + next_page}) return url
def _login_url(service): """Generates CAS login URL""" params = {'service': service} if settings.CAS_RENEW: params.update({'renew': 'true'}) if settings.CAS_EXTRA_LOGIN_PARAMS: params.update(settings.CAS_EXTRA_LOGIN_PARAMS) return urllib_parse.urljoin(settings.CAS_SERVER_URL, 'login') + '?' + urllib_parse.urlencode(params)
def _login_url(service): """Generates CAS login URL""" params = {'service': service} if settings.CAS_RENEW: params.update({'renew': 'true'}) if settings.CAS_EXTRA_LOGIN_PARAMS: params.update(settings.CAS_EXTRA_LOGIN_PARAMS) return urllib_parse.urljoin(settings.CAS_SERVER_URL, 'login') + '?' + urllib_parse.urlencode(params)
def get_edit_url(self): data = { 'source': self.object.source, 'num_turnout_reported': self.object.num_turnout_reported, 'num_spoilt_ballots': self.object.num_spoilt_ballots, } for result in self.object.candidate_results.all(): data['memberships_{}'.format( result.membership.person.pk)] = result.num_ballots_reported return urlencode(data)
def get_login_url(self): """Generates CAS login URL""" 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
def get_login_url(self): """Generates CAS login URL""" 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
def _logout_url(request, next_page=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(settings.CAS_SERVER_URL, "logout") if next_page: protocol = get_protocol(request) host = request.get_host() next_page_url = urllib_parse.urlunparse((protocol, host, next_page, "", "", "")) url += "?" + urllib_parse.urlencode({"url": next_page_url}) return url
def _logout_url(request, next_page=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'logout') if next_page: protocol = ('http://', 'https://')[request.is_secure()] host = request.get_host() url += '?' + urllib_parse.urlencode( {'url': protocol + host + next_page}) return url
def get_verification_response(self, ticket): params = [('ticket', ticket), ('service', self.service_url)] if self.proxy_callback: params.append(('pgtUrl', self.proxy_callback)) base_url = urllib_parse.urljoin(self.server_url, self.URL_SUFFIX) url = base_url + '?' + urllib_parse.urlencode(params) page = urlopen(url) try: return page.read() finally: page.close()
def drop_filter_from_current_url(context, name): """Drop a filter from the current URL""" query_parts = [] for qs_name, qs_value in context['request'].GET.items(): if qs_name != name: query_parts.append((qs_name, qs_value)) path = context['request'].path if query_parts: return path + "?" + urlencode(query_parts) else: return path
def drop_filter_from_current_url(context, name): """Drop a filter from the current URL""" query_parts = [] for qs_name, qs_value in context['request'].GET.items(): if qs_name != name: query_parts.append((qs_name, qs_value)) path = context['request'].path if query_parts: return path + "?" + urlencode(query_parts) else: return path
def get_verification_response(self, ticket): params = [('ticket', ticket), ('service', self.service_url)] if self.proxy_callback: params.append(('pgtUrl', self.proxy_callback)) base_url = urllib_parse.urljoin(self.server_url, self.URL_SUFFIX) url = base_url + '?' + urllib_parse.urlencode(params) page = urlopen(url) try: return page.read() finally: page.close()
def _logout_url(request, next_page=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'logout') if next_page: protocol = get_protocol(request) host = request.get_host() next_page_url = urllib_parse.urlunparse( (protocol, host, next_page, '', '', ''), ) url += '?' + urllib_parse.urlencode({'url': next_page_url}) return url
def _login_url(service): """Generates CAS login URL""" params = {"service": service} if settings.CAS_RENEW: params.update({"renew": "true"}) if settings.CAS_EXTRA_LOGIN_PARAMS: params.update(settings.CAS_EXTRA_LOGIN_PARAMS) url = urllib_parse.urljoin(settings.CAS_SERVER_URL, "login") query = urllib_parse.urlencode(params) return url + "?" + query
def _logout_url(request, next_page=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'logout') if next_page: protocol = get_protocol(request) host = request.get_host() next_page_url = urllib_parse.urlunparse( (protocol, host, next_page, '', '', ''), ) url += '?' + urllib_parse.urlencode({'url': next_page_url}) return url
def get_service_url(request, redirect_to=None): """Generates application django service URL for CAS""" protocol = get_protocol(request) host = request.get_host() service = urllib_parse.urlunparse( (protocol, host, request.path, '', '', ''), ) if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode( {REDIRECT_FIELD_NAME: redirect_to or get_redirect_url(request)}) return service
def add_filter_to_current_url(context, name, value): """Add a filter to the current URL""" query_parts = [] added = False for qs_name, qs_value in context['request'].GET.items(): if qs_name == name: added = True query_parts.append((name, value)) else: query_parts.append((qs_name, qs_value)) if not added: query_parts.append((name, value)) return context['request'].path + "?" + urlencode(query_parts)
def _service_url(request, redirect_to=None): """Generates application service URL for CAS""" protocol = ('http://', 'https://')[request.is_secure()] host = request.get_host() service = protocol + host + request.path if redirect_to: if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
def add_filter_to_current_url(context, name, value): """Add a filter to the current URL""" query_parts = [] added = False for qs_name, qs_value in context['request'].GET.items(): if qs_name == name: added = True query_parts.append((name, value)) else: query_parts.append((qs_name, qs_value)) if not added: query_parts.append((name, value)) return context['request'].path + "?" + urlencode(query_parts)
def _service_url(request, redirect_to=None): """Generates application service URL for CAS""" protocol = ('http://', 'https://')[request.is_secure()] host = request.get_host() service = protocol + host + request.path if redirect_to: if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
def _service_url(request, redirect_to=None): """Generates application service URL for CAS""" protocol = get_protocol(request) host = request.get_host() service = urllib_parse.urlunparse((protocol, host, request.path, "", "", "")) if redirect_to: if "?" in service: service += "&" else: service += "?" service += urllib_parse.urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
def get_service_url(request, redirect_to=None): """Generates application django service URL for CAS""" protocol = get_protocol(request) host = request.get_host() service = urllib_parse.urlunparse( (protocol, host, request.path, '', '', ''), ) if redirect_to: if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
def verify_ticket(self, ticket): """Verifies CAS 1.0 authentication ticket.""" params = [('ticket', ticket), ('service', self.service)] url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: verified = page.readline().strip() if verified == 'yes': return page.readline().strip(), None, None else: return None, None, None finally: page.close()
def verify_ticket(self, ticket): """Verifies CAS 1.0 authentication ticket.""" params = [('ticket', ticket), ('service', self.service)] url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: verified = page.readline().strip() if verified == 'yes': return page.readline().strip(), None, None else: return None, None, None finally: page.close()
def get_service_url(request, redirect_to=None): """Generates application django service URL for CAS""" if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'): service = django_settings.CAS_ROOT_PROXIED_AS + '/' + request.path else: protocol = get_protocol(request) host = request.get_host() service = urllib_parse.urlunparse( (protocol, host, request.path, '', '', ''), ) if not django_settings.CAS_STORE_NEXT: if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode( {REDIRECT_FIELD_NAME: redirect_to or get_redirect_url(request)}) return service
def _verify_cas1(ticket, service): """Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure. """ params = [('ticket', ticket), ('service', service)] url = (urllib_parse.urljoin(settings.CAS_SERVER_URL, 'validate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: verified = page.readline().strip() if verified == 'yes': return page.readline().strip(), None else: return None, None finally: page.close()
def get_service_url(request, redirect_to=None): """Generates application django service URL for CAS""" protocol = get_protocol(request) if django_settings.DEBUG: host = request.get_host() else: host = django_settings.SUCC_REDIRECT_URL # print("::::::: ", host) service = urllib_parse.urlunparse( (protocol, host, request.path, '', '', ''), ) if not django_settings.CAS_STORE_NEXT: if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode( {REDIRECT_FIELD_NAME: redirect_to or get_redirect_url(request)}) return service
def _verify_cas1(ticket, service): """Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure. """ params = [('ticket', ticket), ('service', service)] url = (urllib_parse.urljoin(settings.CAS_SERVER_URL, 'validate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: verified = page.readline().strip() if verified == 'yes': return page.readline().strip(), None else: return None, None finally: page.close()
def get_service_url(request, redirect_to=None): """Generates application django service URL for CAS""" if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'): service = django_settings.CAS_ROOT_PROXIED_AS + request.path else: protocol = get_protocol(request) host = request.get_host() service = urllib_parse.urlunparse( (protocol, host, request.path, '', '', ''), ) if not django_settings.CAS_STORE_NEXT: if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode({ REDIRECT_FIELD_NAME: redirect_to or get_redirect_url(request) }) return service
def _service_url(request, redirect_to=None): """Generates application service URL for CAS""" protocol = get_protocol(request) host = request.get_host() ticketless_full_path = request.get_full_path() match = re.search(r"(&ticket=[\w\-\.]+)(?:[&].+|$)(?:$|)", ticketless_full_path) if match: ticketless_full_path = ticketless_full_path.replace(match.group(1), "") service = urllib_parse.urlunparse((protocol, host, ticketless_full_path, "", "", "")) if redirect_to: if "?" in service: service += "&" else: service += "?" service += urllib_parse.urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
def _service_url(request, redirect_to=None): """Generates application service URL for CAS""" protocol = get_protocol(request) host = request.get_host() ticketless_full_path = request.get_full_path() match = re.search(r'(&ticket=[\w\-\.]+)(?:[&].+|$)(?:$|)', ticketless_full_path) if match: ticketless_full_path = ticketless_full_path.replace(match.group(1), "") service = urllib_parse.urlunparse( (protocol, host, ticketless_full_path, '', '', ''), ) if redirect_to: if '?' in service: service += '&' else: service += '?' service += urllib_parse.urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
def handle(self, **options): self.mime_type_magic = magic.Magic(mime=True) self.gb_parties, _ = PartySet.objects.get_or_create(slug='gb') self.ni_parties, _ = PartySet.objects.get_or_create(slug='ni') start = 0 per_page = 50 url = 'http://pefonline.electoralcommission.org.uk/api/search/Registrations' params = { 'rows': per_page, 'et': ["pp", "ppm"], 'register': ["gb", "ni"], 'regStatus': ["registered", "deregistered", "lapsed"], } with transaction.atomic(): total = None while total is None or start <= total: params['start'] = start resp = requests.get(url + '?' + urlencode(params, doseq=True)).json() if total is None: total = resp['Total'] self.parse_data(resp['Result']) start += per_page
def fetch_saml_validation(self, ticket): # We do the SAML validation headers = { 'soapaction': 'http://www.oasis-open.org/committees/security', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'accept': 'text/xml', 'connection': 'keep-alive', 'content-type': 'text/xml; charset=utf-8', } params = [('TARGET', self.service_url)] saml_validate_url = urllib_parse.urljoin( self.server_url, 'samlValidate', ) url = Request( saml_validate_url + '?' + urllib_parse.urlencode(params), '', headers, ) page = urlopen(url, data=self.get_saml_assertion(ticket)) return page
def _verify_cas2(ticket, service): """Verifies CAS 2.0+ XML-based authentication ticket. Returns username on success and None on failure. """ try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree params = [('ticket', ticket), ('service', service)] url = (urllib_parse.urljoin(settings.CAS_SERVER_URL, 'serviceValidate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('authenticationSuccess'): return tree[0][0].text, None else: return None, None finally: page.close()
def _verify_cas2(ticket, service): """Verifies CAS 2.0+ XML-based authentication ticket. Returns username on success and None on failure. """ try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree params = [('ticket', ticket), ('service', service)] url = (urllib_parse.urljoin(settings.CAS_SERVER_URL, 'serviceValidate') + '?' + urllib_parse.urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('authenticationSuccess'): return tree[0][0].text, None else: return None, None finally: page.close()
def fetch_saml_validation(self, ticket): # We do the SAML validation headers = { 'soapaction': 'http://www.oasis-open.org/committees/security', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'accept': 'text/xml', 'connection': 'keep-alive', 'content-type': 'text/xml; charset=utf-8', } params = [('TARGET', self.service_url)] saml_validate_url = urllib_parse.urljoin( self.server_url, 'samlValidate', ) request = Request( saml_validate_url + '?' + urllib_parse.urlencode(params), self.get_saml_assertion(ticket), headers, ) page = urlopen(request) return page
def handle(self, **options): self.mime_type_magic = magic.Magic(mime=True) self.gb_parties, _ = PartySet.objects.get_or_create(slug='gb') self.ni_parties, _ = PartySet.objects.get_or_create(slug='ni') start = 0 per_page = 50 url = 'http://pefonline.electoralcommission.org.uk/api/search/Registrations' params = { 'rows': per_page, 'et': ["pp", "ppm"], 'register': ["gb", "ni"], 'regStatus': ["registered", "deregistered", "lapsed"], } with transaction.atomic(): total = None while total is None or start <= total: params['start'] = start resp = requests.get(url + '?' + urlencode(params, doseq=True)).json() if total is None: total = resp['Total'] self.parse_data(resp['Result']) start += per_page
def proxy(request, function=None): target_service = request.GET.get('service') proxy_ticket = request.GET.get('ticket') if target_service: try: proxy_ticket = ProxyGrantingTicket.retrieve_pt( request, target_service) except ProxyError as err: error = "<h1>{0}</h1><p>{1}</p>".format(_('Forbidden'), _(str(err))) return HttpResponseForbidden(error) params = urllib_parse.urlencode({'ticket': proxy_ticket}) if '?' in target_service: proxy_url = target_service + "&" + params else: proxy_url = target_service + "?" + params return HttpResponseRedirect(proxy_url) elif proxy_ticket: service_url = get_service_url(request) user = authenticate(ticket=proxy_ticket, service=service_url, request=request, proxy=True) if user is not None and function is not None: return function(request, user) elif function is None: error = "<h1>{0}</h1><p>{1}</p>".format( _('Error'), _('No proxy function implemented.')) return HttpResponseNotFound(error) else: error = "<h1>{0}</h1><p>{1}</p>".format(_('Forbidden'), _('Proxy failed.')) return HttpResponseForbidden(error) else: return HttpResponse("{0}\n".format(_('Nothing')), content_type="text/plain")
def get_proxy_url(self, pgt): """Returns proxy url, given the proxy granting ticket""" params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.get_service_url()}) return "%s/proxy?%s" % (self.server_url, params)
def get_logout_url(self, redirect_url=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(self.server_url, 'logout') if redirect_url: url += '?' + urllib_parse.urlencode({'url': redirect_url}) return url
def _verify_cas3_saml(ticket, service): """CAS3 + SAML""" try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree # We do the SAML validation headers = { 'soapaction': 'http://www.oasis-open.org/committees/security', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'accept': 'text/xml', 'connection': 'keep-alive', 'content-type': 'text/xml; charset=utf-8', } params = [('ticket', ticket), ('service', service), ('TARGET', service)] saml_validat_url = urllib_parse.urljoin( settings.CAS_SERVER_URL, 'samlValidate', ) # teste #saml_validat_url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'proxyValidate',) url = Request( saml_validat_url + '?' + urllib_parse.urlencode(params), '', headers, ) page = urlopen(url, data=get_saml_assertion(ticket)) try: user = None attributes = {} response = page.read() #.replace('\n','') #response = response.encode("utf-8") tree = ElementTree.fromstring(response) #print response # Find the authentication status success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode') if success is not None and success.attrib['Value'] == 'saml1p:Success': # User is validated attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute') for at in attrs: attributes[at.attrib['AttributeName']] = at.find( SAML_1_0_ASSERTION_NS + 'AttributeValue').text """ if 'login' in list(at.attrib.values()): user = at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text attributes['login'] = user #user = attributes['idPessoa'] values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue') if len(values) > 1: values_array = [] for v in values: values_array.append(v.text) attributes[at.attrib['AttributeName']] = values_array else: attributes[at.attrib['AttributeName']] = values[0].text """ return attributes['login'], attributes finally: page.close()
def _verify_cas2_saml(ticket, service): """Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes. @date: 2011-11-30 @author: Carlos Gonzalez Vila <*****@*****.**> Returns username and attributes on success and None,None on failure. """ try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree # We do the SAML validation headers = { 'soapaction': 'http://www.oasis-open.org/committees/security', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'accept': 'text/xml', 'connection': 'keep-alive', 'content-type': 'text/xml; charset=utf-8', } params = [('TARGET', service)] saml_validat_url = urllib_parse.urljoin( settings.CAS_SERVER_URL, 'samlValidate', ) url = Request( saml_validat_url + '?' + urllib_parse.urlencode(params), '', headers, ) page = urlopen(url, data=get_saml_assertion(ticket)) try: user = None attributes = {} response = page.read() tree = ElementTree.fromstring(response) # Find the authentication status success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode') if success is not None and success.attrib['Value'] == 'samlp:Success': # User is validated attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute') for at in attrs: if 'uid' in list(at.attrib.values()): user = at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text attributes['uid'] = user values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue') if len(values) > 1: values_array = [] for v in values: values_array.append(v.text) attributes[at.attrib['AttributeName']] = values_array else: attributes[at.attrib['AttributeName']] = values[0].text return user, attributes finally: page.close()
def get_cas3_verification_response(ticket, service): params = [('ticket', ticket), ('service', service)] base_url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'proxyValidate') url = base_url + '?' + urllib_parse.urlencode(params) page = urlopen(url) return page.read()
def get_cas3_verification_response(ticket, service): params = [('ticket', ticket), ('service', service)] base_url = urllib_parse.urljoin(settings.CAS_SERVER_URL, 'proxyValidate') url = base_url + '?' + urllib_parse.urlencode(params) page = urlopen(url) return page.read()
def _verify_cas2_saml(ticket, service): """Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes. @date: 2011-11-30 @author: Carlos Gonzalez Vila <*****@*****.**> Returns username and attributes on success and None,None on failure. """ try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree # We do the SAML validation headers = { 'soapaction': 'http://www.oasis-open.org/committees/security', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'accept': 'text/xml', 'connection': 'keep-alive', 'content-type': 'text/xml; charset=utf-8', } params = [('TARGET', service)] saml_validat_url = urllib_parse.urljoin( settings.CAS_SERVER_URL, 'samlValidate', ) url = Request( saml_validat_url + '?' + urllib_parse.urlencode(params), '', headers, ) page = urlopen(url, data=get_saml_assertion(ticket)) try: user = None attributes = {} response = page.read() tree = ElementTree.fromstring(response) # Find the authentication status success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode') if success is not None and success.attrib['Value'] == 'samlp:Success': # User is validated attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute') for at in attrs: if 'uid' in list(at.attrib.values()): user = at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text attributes['uid'] = user values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue') if len(values) > 1: values_array = [] for v in values: values_array.append(v.text) attributes[at.attrib['AttributeName']] = values_array else: attributes[at.attrib['AttributeName']] = values[0].text return user, attributes finally: page.close()