Exemple #1
0
def auth1_0(request):
    """
    VERSION 1 AUTH -- DEPRECATED
    Authentication is based on the values passed in to the header.
    If successful, the request is passed on to auth_response
    CAS Authentication requires: "x-auth-user" AND "x-auth-cas"
    LDAP Authentication requires: "x-auth-user" AND "x-auth-key"

    NOTE(esteve): Should we just always attempt authentication by cas,
    then we dont send around x-auth-* headers..
    """
    logger.debug("Auth Request")
    if 'HTTP_X_AUTH_USER' in request.META\
            and 'HTTP_X_AUTH_CAS' in request.META:
        username = request.META['HTTP_X_AUTH_USER']
        if cas_validateUser(username):
            del request.META['HTTP_X_AUTH_CAS']
            return auth_response(request)
        else:
            logger.debug("CAS login failed - %s" % username)
            return HttpResponse("401 UNAUTHORIZED", status=401)

    if 'HTTP_X_AUTH_KEY' in request.META\
            and 'HTTP_X_AUTH_USER' in request.META:
        username = request.META['HTTP_X_AUTH_USER']
        x_auth_key = request.META['HTTP_X_AUTH_KEY']
        if ldap_validate(username, x_auth_key):
            return auth_response(request)
        else:
            logger.debug("LDAP login failed - %s" % username)
            return HttpResponse("401 UNAUTHORIZED", status=401)
    else:
        logger.debug("Request did not have User/Key"
                     " or User/CAS in the headers")
        return HttpResponse("401 UNAUTHORIZED", status=401)
Exemple #2
0
def auth1_0(request):
    """
    VERSION 1 AUTH -- DEPRECATED
    Authentication is based on the values passed in to the header.
    If successful, the request is passed on to auth_response
    CAS Authentication requires: "x-auth-user" AND "x-auth-cas"
    LDAP Authentication requires: "x-auth-user" AND "x-auth-key"

    NOTE(esteve): Should we just always attempt authentication by cas,
    then we dont send around x-auth-* headers..
    """
    logger.debug("Auth Request")
    if 'HTTP_X_AUTH_USER' in request.META\
            and 'HTTP_X_AUTH_CAS' in request.META:
        username = request.META['HTTP_X_AUTH_USER']
        if cas_validateUser(username):
            del request.META['HTTP_X_AUTH_CAS']
            return auth_response(request)
        else:
            logger.debug("CAS login failed - %s" % username)
            return HttpResponse("401 UNAUTHORIZED", status=401)

    if 'HTTP_X_AUTH_KEY' in request.META\
            and 'HTTP_X_AUTH_USER' in request.META:
        username = request.META['HTTP_X_AUTH_USER']
        x_auth_key = request.META['HTTP_X_AUTH_KEY']
        if ldap_validate(username, x_auth_key):
            return auth_response(request)
        else:
            logger.debug("LDAP login failed - %s" % username)
            return HttpResponse("401 UNAUTHORIZED", status=401)
    else:
        logger.debug("Request did not have User/Key"
                     " or User/CAS in the headers")
        return HttpResponse("401 UNAUTHORIZED", status=401)
Exemple #3
0
def validate_token(token, request=None):
    """
    Validates the token attached to the request (SessionStorage, GET/POST)
    If token has expired,
    CAS will attempt to reauthenticate the user and refresh token.
    Expired Tokens can be used for GET requests ONLY!
    """

    #Existence test
    try:
        auth_token = AuthToken.objects.get(key=token)
        user = auth_token.user
    except AuthToken.DoesNotExist:
        #logger.info("AuthToken <%s> does not exist." % token)
        return False
    if auth_token.is_expired():
        if request and request.META['REQUEST_METHOD'] == 'POST':
            user_to_auth = request.session.get('emulated_by', user)
            if cas_validateUser(user_to_auth):
                #logger.debug("Reauthenticated user -- Token updated")
                auth_token.update_expiration()
                auth_token.save()
                return True
            else:
                logger.warn("Could not reauthenticate user")
                return False
        else:
            #logger.debug("%s using EXPIRED token to GET data.." % user)
            return True
    else:
        return True
Exemple #4
0
def validate_token(token, request=None):
    """
    Validates the token attached to the request (SessionStorage, GET/POST)
    If token has expired,
    CAS will attempt to reauthenticate the user and refresh token.
    Expired Tokens can be used for GET requests ONLY!
    """

    #Existence test
    try:
        auth_token = AuthToken.objects.get(key=token)
        user = auth_token.user
    except AuthToken.DoesNotExist:
        #logger.info("AuthToken <%s> does not exist." % token)
        return False
    if auth_token.is_expired():
        if request and request.META['REQUEST_METHOD'] == 'POST':
            user_to_auth = request.session.get('emulated_by', user)
            if cas_validateUser(user_to_auth):
                #logger.debug("Reauthenticated user -- Token updated")
                auth_token.update_expiration()
                auth_token.save()
                return True
            else:
                logger.warn("Could not reauthenticate user")
                return False
        else:
            #logger.debug("%s using EXPIRED token to GET data.." % user)
            return True
    else:
        return True
Exemple #5
0
def validate_token(token, request=None):
    """
    Validates the token attached to the request (SessionStorage, GET/POST)
    If token has expired,
    CAS will attempt to reauthenticate the user and refresh token.
    Expired Tokens can be used for GET requests ONLY!
    """

    #Existence test
    try:
        auth_token = AuthToken.objects.get(key=token)
        user = auth_token.user
    except AuthToken.DoesNotExist:
        logger.info("AuthToken Retrieved:%s Does not exist." % (token,))
        return False
    if auth_token.is_expired():
        if request and request.META['REQUEST_METHOD'] == 'POST':
            #See if the user (Or the user who is emulating a user) can be re-authed.
            user_to_auth = request.session.get('emulated_by', user)
            if cas_validateUser(user_to_auth):
                #logger.debug("Reauthenticated user -- Token updated")
                auth_token.update_expiration()
                auth_token.save()
                return True
            else:
                logger.info("Token %s expired, User %s "
                            "could not be reauthenticated in CAS"
                            % (token, user))
                return False
        else:
            logger.debug("Token %s EXPIRED, but allowing User %s to GET data.."
                         % (token, user))
            return True
    else:
        return True
Exemple #6
0
def validate_token1_0(request):
    """
    validates the token attached to the request
    (Opts: in HEADERS || SessionStorage || GET/POST)

    Validate token against the database.
    Check token's time-out to determine authenticity.
    If token has timed out,
    CAS will attempt to reauthenticate the user to renew the token
    Timed out tokens can be used for GET requests ONLY!
    """
    from web import getRequestVars
    request_vars = getRequestVars(request)

    user = request_vars.get('username', None)
    token = request_vars.get('token', None)
    api_server = request_vars.get('api_server', None)
    emulate = request_vars.get('emulate', None)

    if not user or not token:
        #logger.debug("Request Variables missing")
        return False
    try:
        token = AuthToken.objects.get(token=token)
    except AuthToken.DoesNotExist:
        #logger.debug("AuthToken does not exist")
        return False

    tokenExpireTime = timedelta(days=1)
    #Invalid Token
    if token.user != user\
            or token.logout is not None\
            or token.api_server_url != api_server:
        #logger.debug("%s - Token Invalid." % user)
        #logger.debug("%s != %s" % (token.user, user))
        #logger.debug("%s != %s" % (token.api_server_url, api_server))
        #logger.debug("%s is not None" % (token.logout))
        return False

    #Expired Token
    if token.issuedTime + tokenExpireTime < timezone.now():
        if request.META["REQUEST_METHOD"] == "GET":
            #logger.debug("Token Expired - %s requesting GET data OK" % user)
            return True
        #Expired and POSTing data, need to re-authenticate the token
        if emulate:
            user = emulate
        if not cas_validateUser(user):
            #logger.debug("Token Expired - %s was not logged into CAS.")
            return False
        #CAS Reauthentication Success
        #logger.debug("%s reauthenticated with CAS" % user)

    #Valid Token
    token.issuedTime = timezone.now()
    token.save()
    return True
Exemple #7
0
def validate_token1_0(request):
    """
    validates the token attached to the request
    (Opts: in HEADERS || SessionStorage || GET/POST)

    Validate token against the database.
    Check token's time-out to determine authenticity.
    If token has timed out,
    CAS will attempt to reauthenticate the user to renew the token
    Timed out tokens can be used for GET requests ONLY!
    """
    from web import getRequestVars
    request_vars = getRequestVars(request)

    user = request_vars.get('username', None)
    token = request_vars.get('token', None)
    api_server = request_vars.get('api_server', None)
    emulate = request_vars.get('emulate', None)

    if not user or not token:
        #logger.debug("Request Variables missing")
        return False
    try:
        token = AuthToken.objects.get(token=token)
    except AuthToken.DoesNotExist:
        #logger.debug("AuthToken does not exist")
        return False

    tokenExpireTime = timedelta(days=1)
    #Invalid Token
    if token.user != user\
            or token.logout is not None\
            or token.api_server_url != api_server:
        #logger.debug("%s - Token Invalid." % user)
        #logger.debug("%s != %s" % (token.user, user))
        #logger.debug("%s != %s" % (token.api_server_url, api_server))
        #logger.debug("%s is not None" % (token.logout))
        return False

    #Expired Token
    if token.issuedTime + tokenExpireTime < timezone.now():
        if request.META["REQUEST_METHOD"] == "GET":
            #logger.debug("Token Expired - %s requesting GET data OK" % user)
            return True
        #Expired and POSTing data, need to re-authenticate the token
        if emulate:
            user = emulate
        if not cas_validateUser(user):
            #logger.debug("Token Expired - %s was not logged into CAS.")
            return False
        #CAS Reauthentication Success
        #logger.debug("%s reauthenticated with CAS" % user)

    #Valid Token
    token.issuedTime = timezone.now()
    token.save()
    return True
Exemple #8
0
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by CAS
     Return None otherwise.
     """
     (success, cas_response) = cas_validateUser(username)
     logger.info("Authenticate by CAS: %s - %s %s"
                 % (username, success, cas_response))
     if not success:
         logger.debug("CAS Authentication failed - "+username)
         return None
     attributes = cas_formatAttrs(cas_response)
     return makeOrCreateUser(username, attributes)
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by CAS
     Return None otherwise.
     """
     (success, cas_response) = cas_validateUser(username)
     logger.info("Authenticate by CAS: %s - %s %s" %
                 (username, success, cas_response))
     if not success:
         logger.debug("CAS Authentication failed - " + username)
         return None
     attributes = cas_formatAttrs(cas_response)
     return makeOrCreateUser(username, attributes)
Exemple #10
0
def validate_token1_0(request):
    """
    validates the token attached to the request
    (Opts: in HEADERS || SessionStorage || GET/POST)

    Validate token against the database.
    Check token's time-out to determine authenticity.
    If token has timed out,
    CAS will attempt to reauthenticate the user to renew the token
    Timed out tokens can be used for GET requests ONLY!
    """
    request_vars = getRequestVars(request)

    user = request_vars.get('username', None)
    token = request_vars.get('token', None)
    api_server = request_vars.get('api_server', None)
    emulate = request_vars.get('emulate', None)

    if not user or not token:
        return False
    try:
        token = AuthToken.objects.get(token=token)
    except AuthToken.DoesNotExist:
        return False

    tokenExpireTime = timedelta(days=1)
    # Invalid Token
    if token.user != user\
            or token.logout is not None\
            or token.api_server_url != api_server:
        return False

    # Expired Token
    if token.issuedTime + tokenExpireTime < timezone.now():
        if request.META["REQUEST_METHOD"] == "GET":
            return True
        # Expired and POSTing data, need to re-authenticate the token
        if emulate:
            user = emulate
        if not cas_validateUser(user):
            return False
        # CAS Reauthentication Success

    # Valid Token
    token.issuedTime = timezone.now()
    token.save()
    return True
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by CAS
     Return None otherwise.
     """
     logger.debug("U:%s P:%s R:%s" % (username, password, request))
     if not username:
         logger.debug("CAS Authentication skipped - No Username.")
         return None
     (success, cas_response) = cas_validateUser(username)
     logger.info("Authenticate by CAS: %s - %s %s"
                 % (username, success, cas_response))
     if not success:
         logger.debug("CAS Authentication failed - "+username)
         return None
     attributes = cas_response.attributes
     return get_or_create_user(username, attributes)
Exemple #12
0
def token_auth(request):
    """
    VERSION 2 AUTH
    Authentication is based on the POST parameters:
    * Username (Required)
    * Password (Not Required if CAS authenticated previously)

    NOTE: This authentication is SEPARATE from
    django model authentication
    Use this to give out tokens to access the API
    """
    logger.info('Request to auth')
    logger.info(request)

    token = request.POST.get('token', None)
    emulate_user = request.POST.get('emulate_user', None)

    username = request.POST.get('username', None)
    #CAS authenticated user already has session data
    #without passing any parameters
    if not username:
        username = request.session.get('username', None)

    password = request.POST.get('password', None)
    #LDAP Authenticate if password provided.
    if username and password:
        if ldap_validate(username, password):
            logger.info("LDAP User %s validated. Creating auth token" % username)
            token = createAuthToken(username)
            expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
            auth_json = {
                'token': token.key,
                'username': token.user.username,
                'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
            }
            return HttpResponse(
                content=json.dumps(auth_json),
                status=status.HTTP_201_CREATED,
                content_type='application/json')
        else:
            logger.debug("[LDAP] Failed to validate %s" % username)
            return HttpResponse("LDAP login failed", status=401)

    #if request.session and request.session.get('token'):
    #    logger.info("User %s already authenticated, renewing token" % username)
    #    token = validateToken(username, request.session.get('token'))

    #ASSERT: Token exists here
    if token:
        expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
        auth_json = {
            'token': token.key,
            'username': token.user.username,
            'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
        }
        return HttpResponse(
            content=json.dumps(auth_json),
            content_type='application/json')

    if not username and not password:
        #The user and password were not found
        #force user to login via CAS
        return cas_loginRedirect(request, '/auth/')

    #CAS Authenticate by Proxy (Password not necessary):
    if cas_validateUser(username):
        logger.info("CAS User %s validated. Creating auth token" % username)
        token = createAuthToken(username)
        expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
        auth_json = {
            'token': token.key,
            'username': token.user.username,
            'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
        }
        return HttpResponse(
            content=json.dumps(auth_json),
            content_type='application/json')
    else:
        logger.debug("[CAS] Failed to validate - %s" % username)
        return HttpResponse("CAS Login Failure", status=401)
Exemple #13
0
def token_auth(request):
    """
    VERSION 2 AUTH
    Authentication is based on the POST parameters:
    * Username (Required)
    * Password (Not Required if CAS authenticated previously)

    NOTE: This authentication is SEPARATE from
    django model authentication
    Use this to give out tokens to access the API
    """
    logger.info('Request to auth')
    logger.info(request)

    token = None

    username = request.POST.get('username', None)
    #CAS authenticated user already has session data
    #without passing any parameters
    if not username:
        username = request.session.get('username', None)

    password = request.POST.get('password', None)
    #LDAP Authenticate if password provided.
    if username and password:
        if ldap_validate(username, password):
            logger.info("LDAP User %s validated. Creating auth token" % username)
            token = createAuthToken(username)
            expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
            auth_json = {
                'token': token.key,
                'username': token.user.username,
                'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
            }
            return HttpResponse(
                content=json.dumps(auth_json),
                status=status.HTTP_201_CREATED,
                content_type='application/json')
        else:
            logger.debug("[LDAP] Failed to validate %s" % username)
            return HttpResponse("LDAP login failed", status=401)

    #if request.session and request.session.get('token'):
    #    logger.info("User %s already authenticated, renewing token" % username)
    #    token = validateToken(username, request.session.get('token'))

    #ASSERT: Token exists here
    if token:
        expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
        auth_json = {
            'token': token.key,
            'username': token.user.username,
            'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
        }
        return HttpResponse(
            content=json.dumps(auth_json),
            content_type='application/json')

    if not username and not password:
        #The user and password were not found
        #force user to login via CAS
        return cas_loginRedirect(request, '/auth/')

    #CAS Authenticate by Proxy (Password not necessary):
    if cas_validateUser(username):
        logger.info("CAS User %s validated. Creating auth token" % username)
        token = createAuthToken(username)
        expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
        auth_json = {
            'token': token.key,
            'username': token.user.username,
            'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
        }
        return HttpResponse(
            content=json.dumps(auth_json),
            content_type='application/json')
    else:
        logger.debug("[CAS] Failed to validate - %s" % username)
        return HttpResponse("CAS Login Failure", status=401)
Exemple #14
0
def token_auth(request):
    """
    VERSION 2 AUTH
    Authentication is based on the POST parameters:
    * Username (Required)
    * Password (Not Required if CAS authenticated previously)

    NOTE: This authentication is SEPARATE from
    django model authentication
    Use this to give out tokens to access the API
    """
    token = request.POST.get("token", None)

    username = request.POST.get("username", None)
    # CAS authenticated user already has session data
    # without passing any parameters
    if not username:
        username = request.session.get("username", None)

    password = request.POST.get("password", None)
    # LDAP Authenticate if password provided.
    if username and password:
        if ldap_validate(username, password):
            token = create_token(username, issuer="API")
            expireTime = token.issuedTime + auth_settings.TOKEN_EXPIRY_TIME
            auth_json = {
                "token": token.key,
                "username": token.user.username,
                "expires": expireTime.strftime("%b %d, %Y %H:%M:%S"),
            }
            return HttpResponse(content=json.dumps(auth_json), status=201, content_type="application/json")
        else:
            logger.debug("[LDAP] Failed to validate %s" % username)
            return HttpResponse("LDAP login failed", status=401)

    #    logger.info("User %s already authenticated, renewing token"
    #                % username)

    # ASSERT: Token exists here
    if token:
        expireTime = token.issuedTime + auth_settings.TOKEN_EXPIRY_TIME
        auth_json = {
            "token": token.key,
            "username": token.user.username,
            "expires": expireTime.strftime("%b %d, %Y %H:%M:%S"),
        }
        return HttpResponse(content=json.dumps(auth_json), content_type="application/json")

    if not username and not password:
        # The user and password were not found
        # force user to login via CAS
        return cas_loginRedirect(request, "/auth/")

    if cas_validateUser(username):
        logger.info("CAS User %s validated. Creating auth token" % username)
        token = createAuthToken(username)
        expireTime = token.issuedTime + auth_settings.TOKEN_EXPIRY_TIME
        auth_json = {
            "token": token.key,
            "username": token.user.username,
            "expires": expireTime.strftime("%b %d, %Y %H:%M:%S"),
        }
        return HttpResponse(content=json.dumps(auth_json), content_type="application/json")
    else:
        logger.debug("[CAS] Failed to validate - %s" % username)
        return HttpResponse("CAS Login Failure", status=401)