Beispiel #1
0
    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)
Beispiel #2
0
    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)
Beispiel #3
0
 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
Beispiel #4
0
 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
Beispiel #5
0
 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
Beispiel #6
0
    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()
Beispiel #7
0
 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)
Beispiel #8
0
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()
Beispiel #9
0
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")
Beispiel #10
0
    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)
Beispiel #11
0
    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()
Beispiel #12
0
 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()
Beispiel #13
0
 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()
Beispiel #14
0
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
Beispiel #15
0
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
Beispiel #16
0
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)
Beispiel #17
0
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)
Beispiel #19
0
    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
Beispiel #20
0
    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
Beispiel #21
0
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
Beispiel #22
0
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
Beispiel #23
0
 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()
Beispiel #24
0
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
Beispiel #25
0
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
Beispiel #26
0
 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()
Beispiel #27
0
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
Beispiel #28
0
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
Beispiel #29
0
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
Beispiel #30
0
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
Beispiel #31
0
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)
Beispiel #32
0
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
Beispiel #33
0
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)
Beispiel #34
0
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
Beispiel #35
0
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
Beispiel #36
0
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
Beispiel #37
0
 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()
Beispiel #38
0
 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()
Beispiel #39
0
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
Beispiel #40
0
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()
Beispiel #41
0
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
Beispiel #42
0
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()
Beispiel #43
0
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
Beispiel #44
0
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
Beispiel #45
0
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
Beispiel #47
0
    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
Beispiel #48
0
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()
Beispiel #49
0
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()
Beispiel #50
0
    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
Beispiel #52
0
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")
Beispiel #53
0
 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)
Beispiel #54
0
 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
Beispiel #55
0
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()
Beispiel #56
0
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()
Beispiel #57
0
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()
Beispiel #58
0
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()
Beispiel #59
0
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()