Esempio n. 1
0
def verify_proxy_ticket(ticket, service):
    """Verifies CAS 2.0+ XML-based proxy 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 = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' +
           urlencode(params))

    page = urllib2.urlopen(url)

    try:
        response = page.read()
        tree = ElementTree.fromstring(response)
        if tree[0].tag.endswith('authenticationSuccess'):
            username = tree[0][0].text
            proxies = []
            if len(tree[0]) > 1:
                for element in tree[0][1]:
                    proxies.append(element.text)
            return {"username": username, "proxies": proxies}
        else:
            return None
    finally:
        page.close()
Esempio n. 2
0
    def get_proxy_ticket_for(self, service):
        """Verifies CAS 2.0+ XML-based authentication ticket.

        Returns username on success and None on failure.
        """
        if not settings.CAS_PROXY_CALLBACK:
            raise CasConfigException("No proxy callback set in settings")

        try:
            from xml.etree import ElementTree
        except ImportError:
            from elementtree import ElementTree

        params = {'pgt': self.tgt, 'targetService': service}

        url = (urljoin(settings.CAS_SERVER_URL, 'proxy') + '?' +
               urlencode(params))

        page = urllib2.urlopen(url)

        try:
            response = page.read()
            tree = ElementTree.fromstring(response)
            if tree.find(CAS + 'proxySuccess') is not None:
                return tree.find(CAS + 'proxySuccess/' + CAS + 'proxyTicket').text
            else:
                raise CasTicketException("Failed to get proxy ticket")
        finally:
            page.close()
Esempio n. 3
0
    def get_proxy_ticket_for(self, service):
        """Verifies CAS 2.0+ XML-based authentication ticket.

        Returns username on success and None on failure.
        """
        if not settings.CAS_PROXY_CALLBACK:
            raise CasConfigException("No proxy callback set in settings")

        try:
            from xml.etree import ElementTree
        except ImportError:
            from elementtree import ElementTree

        params = {'pgt': self.tgt, 'targetService': service}

        url = (urljoin(settings.CAS_SERVER_URL, 'proxy') + '?' +
               urlencode(params))

        page = urllib2.urlopen(url)

        try:
            response = page.read()
            tree = ElementTree.fromstring(response)
            if tree.find(CAS + 'proxySuccess') is not None:
                return tree.find(CAS + 'proxySuccess/' + CAS +
                                 'proxyTicket').text
            else:
                raise CasTicketException("Failed to get proxy ticket")
        finally:
            page.close()
Esempio n. 4
0
def cas_validate(request, ticket):
    """Validate a ticket through CAS.

    Return netid if valid, else return None."""
    
    url = cas_url_valid + '?' + urlencode({'service':service_url(request), 'ticket':ticket})
    valid = urllib2.urlopen(url).readlines()
    if valid[1].count('<cas:authenticationSuccess>') > 0:
        s = valid[2].partition('<cas:user>')
        t = s[2].partition('</cas:user>')
        return t[0]
    return None
Esempio n. 5
0
def cas_validate(request, ticket):
    """Validate a ticket through CAS.

    Return netid if valid, else return None."""

    url = cas_url_valid + '?' + urlencode({
        'service': service_url(request),
        'ticket': ticket
    })
    valid = urllib2.urlopen(url).readlines()
    if valid[1].count('<cas:authenticationSuccess>') > 0:
        s = valid[2].partition('<cas:user>')
        t = s[2].partition('</cas:user>')
        return t[0]
    return None
Esempio n. 6
0
    def authenticate(self, ticket=None):
        #validate
        html = urllib2.urlopen('%s?service=%s&ticket=%s' % (cas_validate_url,
                                                            cas_ttrade_service_url,
                                                            ticket)).read()
        validated, username, _ = html.split('\n')
        if validated == 'no':
            return None

        defaults = {'is_staff':False,
                    'is_active':True,
                    'is_superuser':False,
                    'email':str(username)+'@princeton.edu',
                    }
        sn = "pr_" + username
        user, _ = User.objects.get_or_create(username=sn, defaults=defaults)
        return user
Esempio n. 7
0
    def authenticate(self, ticket=None):
        #validate
        html = urllib2.urlopen('%s?service=%s&ticket=%s' % (cas_validate_url,
                                                            cas_scg_service_url,
                                                            ticket)).read()
        validated, username, _ = html.split('\n')
        if validated == 'no':
            return None

        defaults = {'is_staff':False,
                    'is_active':True,
                    'is_superuser':False,
                    'email':str(username)+'@princeton.edu',
                    }
        user, _ = User.objects.get_or_create(username=username, defaults=defaults)
        r = RecentDepartments.objects
        user.recent_departments = r.recent_departments(user)
        return user
Esempio n. 8
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 = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
           urlencode(params))
    page = urllib2.urlopen(url)
    try:
        verified = page.readline().strip()
        if verified == 'yes':
            return page.readline().strip(), None
        else:
            return None, None
    finally:
        page.close()
Esempio n. 9
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

    if settings.CAS_PROXY_CALLBACK:
        params = {'ticket': ticket, 'service': service, 'pgtUrl': settings.CAS_PROXY_CALLBACK}
    else:
        params = {'ticket': ticket, 'service': service}

    url = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' +
           urllib.urlencode(params))

    page = urllib2.urlopen(url)
    response = page.read()
    tree = ElementTree.fromstring(response)
    page.close()

    if tree.find(CAS + 'authenticationSuccess') is not None:
        username = tree.find(CAS + 'authenticationSuccess/' + CAS + 'user').text
        pgtIouIdElement = tree.find(CAS + 'authenticationSuccess/' + CAS + 'proxyGrantingTicket');
        pgtIouId = pgtIouIdElement.text if pgtIouIdElement is not None else None

        if pgtIouId:
            pgtIou = PgtIOU.objects.get(pgtIou = pgtIouId)
            try:
                tgt = Tgt.objects.get(username = username)
                tgt.tgt = pgtIou.tgt
                tgt.save()
            except ObjectDoesNotExist:
                Tgt.objects.create(username = username, tgt = pgtIou.tgt)

            pgtIou.delete()
        return username, tree
    else:
        return None, tree
Esempio n. 10
0
def login(request):
	""" Conduct login of user using a CAS system """
	if request.method == 'GET' and 'ticket' in request.GET:
		if request.session.test_cookie_worked():
			request.session.delete_test_cookie()
			try:
				ticket = request.GET.get('ticket', None)
				params = urllib.urlencode({'service':our_site_validate,'ticket':ticket})
				validation = urllib2.urlopen(cas_url+'/validate?'+params).readlines()
				if len(validation) == 2 and re.match('yes', validation[0]) != None:
					netid = validation[1].strip()
					request.session['user_data'] = login_user(netid)
					if not request.session['user_data'].user_last_login:
						request.session['user_data'].set_logged_in()
						MsgMgr.push(request, 'It looks like you\'re new here. Please confirm the information below, and then we\'ll send you along.', 1)
						#Future Feature: For new users, add tips to top of page for first-time visit
						MsgMgr.push(request, 'This page will show you updates.',2,msg_to_page='/user/messages')
						MsgMgr.push(request, 'This page will show you events you\'ve added to your calendar.',2,msg_to_page='/user/events')
						return HttpResponseRedirect('/user?newbie=True')
					request.session['user_data'].set_logged_in()
					MsgMgr.push(request, 'Welcome back, %s!' % (request.session['user_data'].casual_name()), 1)
				else:
					MsgMgr.push(request, 'You could not be logged in.', 0)	
					return HttpResponseRedirect("/")
				if 'login_redirect' in request.session:
					referrer = request.session['login_redirect']
					del request.session['login_redirect']
					return HttpResponseRedirect(referrer)
				else:
					return HttpResponseRedirect(our_site)	
			except:
				MsgMgr.push(request, 'Login failed.', 0)	
				return HttpResponseRedirect(our_site)	
		else:
			return HttpResponseRedirect('/nocookie')
	else:
		return login_redirect(request)
Esempio n. 11
0
def urlopen(url):
    log.debug("Requesting %s" % url)
    return urllib2.urlopen(url)
Esempio n. 12
0
def urlopen(url):
    log.debug("Requesting %s" % url)
    return urllib2.urlopen(url)