Exemple #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/")
Exemple #2
0
def auth_response(request):
    """
    Create a new AuthToken for the user, then return the Token & API URL
    AuthTokens will expire after a predefined time
    (See #/auth/utils.py:settings.TOKEN_EXPIRY_TIME)
    AuthTokens will be re-newed if
    the user is re-authenticated by CAS at expiry-time
    """
    logger.debug("Creating Auth Response")
    api_server_url = API_SERVER_URL
    # login validation
    response = HttpResponse()

    response['Access-Control-Allow-Origin'] = '*'
    response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    response['Access-Control-Max-Age'] = 1000
    response['Access-Control-Allow-Headers'] = '*'

    response['X-Server-Management-Url'] = api_server_url
    response['X-Storage-Url'] = "http://"
    response['X-CDN-Management-Url'] = "http://"
    token = str(uuid.uuid4())
    username = request.META['HTTP_X_AUTH_USER']
    response['X-Auth-Token'] = token
    # New code: If there is an 'emulate_user' parameter:
    if 'HTTP_X_EMULATE_USER' in request.META:
        # AND user has permission to emulate
        if userCanEmulate(username):
            logger.debug("EMULATION REQUEST:"
                         "Generating AuthToken for %s -- %s" %
                         (request.META['HTTP_X_EMULATE_USER'],
                          username))
            response['X-Auth-User'] = request.META['HTTP_X_EMULATE_USER']
            response['X-Emulated-By'] = username
            # then this token is for the emulated user
            auth_user_token = AuthToken(
                user=request.META['HTTP_X_EMULATE_USER'],
                issuedTime=datetime.now(),
                remote_ip=request.META['REMOTE_ADDR'],
                api_server_url=api_server_url
            )
        else:
            logger.warn("EMULATION REQUEST:User deemed Unauthorized : %s" %
                        (username,))
            # This user is unauthorized to emulate users - Don't create a
            # token!
            return HttpResponse("401 UNAUTHORIZED TO EMULATE", status=401)
    else:
        # Normal login, no user to emulate
        response['X-Auth-User'] = username
        auth_user_token = AuthToken(
            user=username,
            issuedTime=datetime.now(),
            remote_ip=request.META['REMOTE_ADDR'],
            api_server_url=api_server_url
        )

    auth_user_token.save()
    return response
 def atmo_validate_token(request, *args, **kwargs):
     # Used for requests that require a valid token
     token_key = request.session.get('token')
     if validate_token(token_key, request):
         return func(request, *args, **kwargs)
     else:
         logger.warn('invalid token used')
         return HttpResponseForbidden("403 Forbidden")
Exemple #4
0
def lookupUser(userid):
    """
    Grabs email for the user based on LDAP attrs
    """
    try:
        attr = _search_ldap(userid)
        user_attrs = attr[0][1]
        return user_attrs
    except Exception as e:
        logger.warn("Error occurred looking up user: %s" % userid)
        logger.exception(e)
        raise
Exemple #5
0
def _search_ldap(userid, conn=None):
    try:
        if not conn:
            conn = ldap_driver.initialize(auth_settings.LDAP_SERVER)
        result = conn.search_s(
            auth_settings.LDAP_SERVER_DN,
            ldap_driver.SCOPE_SUBTREE,
            '(uid=' + userid + ')'
        )
        return result
    except Exception as e:
        logger.warn("Error occurred on ldap search for: %s" % userid)
        logger.exception(e)
        return None
Exemple #6
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)
        raise
Exemple #7
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)
        raise
Exemple #8
0
def obtainOAuthToken(username, token_key, token_expire=None):
    """
    returns a new token for username
    """
    try:
        user = AtmosphereUser.objects.get(username=username)
    except AtmosphereUser.DoesNotExist:
        logger.warn("User %s doesn't exist on the DB. "
                    "OAuth token _NOT_ created" % username)
        return None
    auth_user_token, _ = AuthToken.objects.get_or_create(
        key=token_key, user=user, api_server_url=settings.API_SERVER_URL)
    if token_expire:
        auth_user_token.update_expiration(token_expire)
    auth_user_token.save()
    return auth_user_token
Exemple #9
0
def obtainOAuthToken(username, token_key, token_expire=None):
    """
    returns a new token for username
    """
    try:
        user = AtmosphereUser.objects.get(username=username)
    except AtmosphereUser.DoesNotExist:
        logger.warn("User %s doesn't exist on the DB. "
                    "OAuth token _NOT_ created" % username)
        return None
    auth_user_token, _ = AuthToken.objects.get_or_create(
        key=token_key, user=user, api_server_url=settings.API_SERVER_URL)
    if token_expire:
        auth_user_token.update_expiration(token_expire)
    auth_user_token.save()
    return auth_user_token
Exemple #10
0
def getAllUsers():
    """
    Grabs all users in LDAP
    """
    try:
        conn = ldap_driver.initialize(secrets.LDAP_SERVER)
        user_list = []
        for letter in string.lowercase:
            attr = _search_ldap("%s*" % letter, conn)
            for i in xrange(0, len(attr)):
                user_attrs = attr[i][1]
                user_list.append(user_attrs)
        return user_list
    except Exception as e:
        logger.warn("Error occurred looking up all user")
        logger.exception(e)
        return None
Exemple #11
0
def getAllUsers():
    """
    Grabs all users in LDAP
    """
    try:
        conn = ldap_driver.initialize(auth_settings.LDAP_SERVER)
        user_list = []
        for letter in string.lowercase:
            attr = _search_ldap("%s*" % letter, conn)
            for i in xrange(0, len(attr)):
                user_attrs = attr[i][1]
                user_list.append(user_attrs)
        return user_list
    except Exception as e:
        logger.warn("Error occurred looking up all user")
        logger.exception(e)
        return None
Exemple #12
0
def ldap_validate(username, password):
    """
    ldap_validate
    Using the username and password parameters, test with an LDAP bind.
    If the connection succeeds, the credentials are authentic.
    """
    if not username or not password:
        logger.warn("[LDAP] Skip Test - Username/Password combination missing")
        return

    try:
        ldap_server = secrets.LDAP_SERVER
        ldap_server_dn = secrets.LDAP_SERVER_DN
        logger.warn("[LDAP] Validation Test - %s" % username)
        ldap_conn = ldap_driver.initialize(ldap_server)
        dn = "uid=" + username + "," + ldap_server_dn
        ldap_conn.simple_bind_s(dn, password)
        return True
    except Exception as e:
        logger.exception(e)
        return False
Exemple #13
0
def ldap_validate(username, password):
    """
    ldap_validate
    Using the username and password parameters, test with an LDAP bind.
    If the connection succeeds, the credentials are authentic.
    """
    if not username or not password:
        logger.warn("[LDAP] Skip Test - Username/Password combination missing")
        return

    try:
        ldap_server = auth_settings.LDAP_SERVER
        ldap_server_dn = auth_settings.LDAP_SERVER_DN
        logger.warn("[LDAP] Validation Test - %s" % username)
        ldap_conn = ldap_driver.initialize(ldap_server)
        dn = "uid=" + username + "," + ldap_server_dn
        ldap_conn.simple_bind_s(dn, password)
        return True
    except Exception as e:
        logger.exception(e)
        return False
Exemple #14
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