Esempio n. 1
0
def cas_callback_authorize(request):
    """
    Authorize a callback (From CAS IdP)
    """
    if "code" not in request.GET:
        # TODO - Maybe: Redirect into a login
        return HttpResponse("")
    oauth_client = get_cas_oauth_client()
    oauth_code = request.GET["code"]
    # Exchange code for ticket
    access_token, expiry_date = oauth_client.get_access_token(oauth_code)
    if not access_token:
        logger.warn("The Code %s is invalid/expired. Attempting another login." % oauth_code)
        return o_login_redirect(request)
    # Exchange token for profile
    user_profile = oauth_client.get_profile(access_token)
    if not user_profile or "id" not in user_profile:
        logger.error(
            "AccessToken is producing an INVALID profile!"
            " Check the CAS server and caslib.py for more"
            " information."
        )
        # NOTE: Make sure this redirects the user OUT of the loop!
        return login(request)
    # ASSERT: A valid OAuth token gave us the Users Profile.
    # Now create an AuthToken and return it
    username = user_profile["id"]
    auth_token = create_token(username, access_token, expiry_date, issuer="CAS+OAuth")
    # Set the username to the user to be emulated
    # to whom the token also belongs
    request.session["username"] = username
    request.session["token"] = auth_token.key
    return HttpResponseRedirect(settings.REDIRECT_URL + "/application/")
Esempio n. 2
0
def updateUserProxy(user, pgtIou, max_try=3):
    attempts = 0
    while attempts < max_try:
        try:
            # If PGTIOU exists, a UserProxy object was created
            # match the user to this ticket.
            userProxy = UserProxy.objects.get(proxyIOU=pgtIou)
            userProxy.username = user
            userProxy.expiresOn = timezone.now() + PROXY_TICKET_EXPIRY
            logger.debug("Found a matching proxy IOU for %s"
                         % userProxy.username)
            userProxy.save()
            return True
        except UserProxy.DoesNotExist:
            logger.error("Could not find UserProxy object!"
                         "ProxyIOU & ID was not saved "
                         "at proxy url endpoint.")
            time.sleep(min(2**attempts, 8))
            attempts += 1
    return False
Esempio n. 3
0
def lookupEmail(userid):
    """
    Grabs email for the user based on LDAP attrs
    """
    try:
        logger.debug(type(userid))
        if isinstance(userid, WSGIRequest):
            raise Exception("WSGIRequest invalid.")
        attr = _search_ldap(userid)
        emailaddr = attr[0][1]['mail'][0]
        return emailaddr
    except Exception as e:
        logger.warn("Error occurred looking up email for user: %s" % userid)
        logger.exception(e)
        import traceback
        import sys
        import inspect
        s = inspect.stack()
        for i in range(0, 4):
            logger.debug(s[i])
        etype, value, tb = sys.exc_info()
        logger.error("TB = %s" % traceback.format_tb(tb))

        return None
Esempio n. 4
0
def cas_validateTicket(request):
    """
    Method expects 2 GET parameters: 'ticket' & 'sendback'
    After a CAS Login:
    Redirects the request based on the GET param 'ticket'
    Unauthorized Users are redirected to '/' In the event of failure.
    Authorized Users are redirected to the GET param 'sendback'
    """

    redirect_logout_url = settings.REDIRECT_URL + "/login/"
    no_user_url = settings.REDIRECT_URL + "/no_user/"
    logger.debug('GET Variables:%s' % request.GET)
    ticket = request.GET.get('ticket', None)
    sendback = request.GET.get('sendback', None)

    if not ticket:
        logger.info("No Ticket received in GET string "
                    "-- Logout user: %s" % redirect_logout_url)
        return HttpResponseRedirect(redirect_logout_url)

    logger.debug("ServiceValidate endpoint includes a ticket."
                 " Ticket must now be validated with CAS")

    # ReturnLocation set, apply on successful authentication

    caslib = get_cas_client()
    caslib.service_url = _set_redirect_url(sendback, request)

    cas_response = caslib.cas_serviceValidate(ticket)
    if not cas_response.success:
        logger.debug("CAS Server did NOT validate ticket:%s"
                     " and included this response:%s (Err:%s)"
                     % (ticket, cas_response.object, cas_response.error_str))
        return HttpResponseRedirect(redirect_logout_url)
    if not cas_response.user:
        logger.debug("User attribute missing from cas response!"
                     "This may require a fix to caslib.py")
        return HttpResponseRedirect(redirect_logout_url)
    if not cas_response.proxy_granting_ticket:
        logger.error("""Proxy Granting Ticket missing!
        Atmosphere requires CAS proxy as a service to authenticate users.
            Possible Causes:
              * ServerName variable is wrong in /etc/apache2/apache2.conf
              * Proxy URL does not exist
              * Proxy URL is not a valid RSA-2/VeriSigned SSL certificate
              * /etc/host and hostname do not match machine.""")
        return HttpResponseRedirect(redirect_logout_url)

    updated = updateUserProxy(
        cas_response.user, cas_response.proxy_granting_ticket)
    if not updated:
        return HttpResponseRedirect(redirect_logout_url)
    logger.info("Updated proxy for <%s> -- Auth success!" % cas_response.user)

    try:
        user = User.objects.get(username=cas_response.user)
    except User.DoesNotExist:
        return HttpResponseRedirect(no_user_url)
    auth_token = create_session_token(None, user, request)
    if auth_token is None:
        logger.info("Failed to create AuthToken")
        HttpResponseRedirect(redirect_logout_url)
    return_to = request.GET['sendback']
    logger.info("Session token created, User logged in, return to: %s"
                % return_to)
    return HttpResponseRedirect(return_to)