예제 #1
0
def cas_proxyCallback(request):
    """
    This is a placeholder for a proxyCallback service
    needed for CAS authentication
    """
    logger.debug("Incoming request to CASPROXY (Proxy Callback):")
    return HttpResponse("I am at a RSA-2 or VeriSigned SSL Cert. website.")
예제 #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
예제 #3
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
예제 #4
0
    def validate_auth_token(decorated_func, *args, **kwargs):
        request = args[0]
        valid_user = validate_request_user(request)
        if not valid_user:
            logger.debug('Unauthorized access by %s - %s - Invalid Token' %
                         (valid_user, request.META.get('REMOTE_ADDR')))
            return Response(
                "Expected header parameter: Authorization Token <TokenID>",
                status=status.HTTP_401_UNAUTHORIZED)

        return func(request, *args, **kwargs)
예제 #5
0
    def validate_auth_token(decorated_func, *args, **kwargs):
        request = args[0]
        valid_user = validate_request_user(request)
        if not valid_user:
            logger.debug('Unauthorized access by %s - %s - Invalid Token' %
                         (valid_user, request.META.get('REMOTE_ADDR')))
            return Response(
                "Expected header parameter: Authorization Token <TokenID>",
                status=status.HTTP_401_UNAUTHORIZED)

        return func(request, *args, **kwargs)
예제 #6
0
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by LDAP.
     Return None otherwise.
     """
     # logger.debug("LDAPBackend-- U:%s P:%s R:%s"
     #              % (username, password, request))
     if not ldap_validate(username, password):
         logger.debug("LDAP Authentication failed - "+username)
         return None
     ldap_attrs = ldap_lookupUser(username)
     attributes = ldap_formatAttrs(ldap_attrs)
     logger.debug("[LDAP] Authentication Success - " + username)
     return get_or_create_user(username, attributes)
예제 #7
0
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by LDAP.
     Return None otherwise.
     """
     # logger.debug("LDAPBackend-- U:%s P:%s R:%s"
     #              % (username, password, request))
     if not ldap_validate(username, password):
         logger.debug("LDAP Authentication failed - " + username)
         return None
     ldap_attrs = ldap_lookupUser(username)
     attributes = ldap_formatAttrs(ldap_attrs)
     logger.debug("[LDAP] Authentication Success - " + username)
     return get_or_create_user(username, attributes)
예제 #8
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)
예제 #9
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)
예제 #10
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
예제 #11
0
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by CAS
     Return None otherwise.
     """
     # logger.debug("SAMLBackend-- U:%s P:%s R:%s"
     #              % (username, password, request))
     if not request:
         logger.debug("SAML Authentication skipped - No request.")
         return None
     # TODO: See if you were the auth backend used to originate the request.
     # TODO: Look at request session for a token and see if its still valid.
     if False:
         logger.debug("SAML Authentication failed - " + username)
         return None
예제 #12
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
예제 #13
0
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by CAS
     Return None otherwise.
     """
     # logger.debug("SAMLBackend-- U:%s P:%s R:%s"
     #              % (username, password, request))
     # logger.debug("U:%s P:%s R:%s" % (username, password, request))
     if not request:
         logger.debug("SAML Authentication skipped - No request.")
         return None
     # TODO: See if you were the auth backend used to originate the request.
     # TODO: Look at request session for a token and see if its still valid.
     if False:
         logger.debug("SAML Authentication failed - " + username)
         return None
예제 #14
0
def get_user_for_token(test_token):
    access_token, _ = generate_access_token(
        open(secrets.OAUTH_PRIVATE_KEY).read(),
        iss=secrets.OAUTH_ISSUE_USER,
        scope=secrets.OAUTH_SCOPE)
    # TODO: TokenAuth here
    response = requests.get(
        '%s/o/oauth2/tokeninfo?access_token=%s'
        % (secrets.GROUPY_SERVER, test_token),
        headers={'Authorization': 'Token %s' % access_token})
    json_obj = response.json()
    logger.debug(json_obj)
    if 'on_behalf' in json_obj:
        username = json_obj['on_behalf']
        expires = datetime.now() + timedelta(seconds=json_obj['expires_in'])
        return username, expires
    return None, None
예제 #15
0
def get_user_for_token(test_token):
    access_token, _ = generate_access_token(open(
        secrets.OAUTH_PRIVATE_KEY).read(),
                                            iss=secrets.OAUTH_ISSUE_USER,
                                            scope=secrets.OAUTH_SCOPE)
    # TODO: TokenAuth here
    response = requests.get(
        '%s/o/oauth2/tokeninfo?access_token=%s' %
        (secrets.GROUPY_SERVER, test_token),
        headers={'Authorization': 'Token %s' % access_token})
    json_obj = response.json()
    logger.debug(json_obj)
    if 'on_behalf' in json_obj:
        username = json_obj['on_behalf']
        expires = datetime.now() + timedelta(seconds=json_obj['expires_in'])
        return username, expires
    return None, None
예제 #16
0
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by CAS
     Return None otherwise.
     """
     # logger.debug("CASBackend -- 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)
예제 #17
0
 def authenticate(self, username=None, password=None, request=None):
     """
     Return user if validated by CAS
     Return None otherwise.
     """
     # logger.debug("CASBackend -- 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)
예제 #18
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
예제 #19
0
 def authenticate(self, username=None, password=None, auth_token=None,
                  request=None):
     """
     Return user if validated by their auth_token
     Return None otherwise.
     """
     try:
         valid_token = Token.objects.get(key=auth_token)
     except Token.DoesNotExist:
         return None
     if valid_token.is_expired():
         logger.debug(
             "[AUTHTOKEN] Token %s is expired. (User:%s)"
             % (valid_token.key, valid_token.user))
         return None
     logger.debug(
         "[AUTHTOKEN] Valid Token %s (User:%s)"
         % (valid_token.key, valid_token.user))
     valid_user = valid_token.user
     return get_or_create_user(valid_user, None)
예제 #20
0
 def authenticate(self, username=None, password=None, auth_token=None,
                  request=None):
     """
     Return user if validated by their auth_token
     Return None otherwise.
     """
     try:
         valid_token = Token.objects.get(key=auth_token)
     except Token.DoesNotExist:
         return None
     if valid_token.is_expired():
         logger.debug(
             "[AUTHTOKEN] Token %s is expired. (User:%s)"
             % (valid_token.key, valid_token.user))
         return None
     logger.debug(
         "[AUTHTOKEN] Valid Token %s (User:%s)"
         % (valid_token.key, valid_token.user))
     valid_user = valid_token.user
     return get_or_create_user(valid_user.username, None)
예제 #21
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'] != 'GET':
            # 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
예제 #22
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
예제 #23
0
def saml_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)

    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 SAML")

    # ReturnLocation set, apply on successful authentication

    saml_client = get_saml_client()
    saml_response = saml_client.saml_serviceValidate(ticket)
    if not saml_response.success:
        logger.debug("CAS Server did NOT validate ticket:%s"
                     " and included this response:%s"
                     % (ticket, saml_response.xml))
        return HttpResponseRedirect(redirect_logout_url)

    try:
        user = User.objects.get(username=saml_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.get('sendback')
    if not return_to:
        return HttpResponse(saml_response.response,
                            content_type="text/xml; charset=utf-8")
    return_to += "?token=%s" % auth_token
    logger.info("Session token created, return to: %s" % return_to)
    return HttpResponseRedirect(return_to)
예제 #24
0
def cas_validateUser(username):
    """
    Because this is a programmatic request
    and CAS requires user input when expired,
    We MUST use CAS Proxy Service,
    and see if we can reauthenticate the user.
    """
    try:
        userProxy = UserProxy.objects.filter(username=username).latest('pk')
        logger.debug("[CAS] Validation Test - %s" % username)
        if userProxy is None:
            logger.debug("User %s does not have a proxy" % username)
            return (False, None)
        proxyTicket = userProxy.proxyTicket
        caslib = get_cas_client()
        (validUser, cas_response) =\
            caslib.reauthenticate(proxyTicket, username=username)
        logger.debug("Valid User: %s Proxy response: %s"
                     % (validUser, cas_response))
        return (validUser, cas_response)
    except Exception:
        logger.exception('Error validating user %s' % username)
        return (False, None)
예제 #25
0
def cas_storeProxyIOU_ID(request):
    """
    Any request to the proxy url will contain the PROXY-TICKET IOU and ID
    IOU and ID are mapped to a DB so they can be used later
    """
    if "pgtIou" in request.GET and "pgtId" in request.GET:
        iou_token = request.GET["pgtIou"]
        proxy_ticket = request.GET["pgtId"]
        logger.debug("PROXY HIT 2 - CAS server sends two IDs: "
                     "1.ProxyIOU (%s) 2. ProxyGrantingTicket (%s)"
                     % (iou_token, proxy_ticket))
        proxy = UserProxy(
            proxyIOU=iou_token,
            proxyTicket=proxy_ticket
        )
        proxy.save()
        logger.debug("Proxy ID has been saved, match ProxyIOU(%s) "
                     "from the proxyIOU returned in service validate."
                     % (proxy.proxyIOU,))
    else:
        logger.debug("Proxy HIT 1 - CAS server tests that this link is HTTPS")

    return HttpResponse("Received proxy request. Thank you.")
예제 #26
0
    def atmo_login(request, *args, **kwargs):
        if not request:
            logger.debug("[NOREQUEST] User is being logged out because request"
                         " is empty")
            logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return HttpResponseRedirect(settings.SERVER_URL + "/logout/")

        if not request.session:
            logger.debug("[NOSESSION] User is being logged out because session"
                         " object does not exist in request")
            logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return HttpResponseRedirect(settings.SERVER_URL + "/logout/")

        if not request.session.get('username'):
            logger.debug("[NOUSER] User is being logged out because session"
                         " did not include a username")
            logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return HttpResponseRedirect(settings.SERVER_URL + "/logout/")

        # logger.info('atmo_login_required session info: %s'
        #             % request.session.__dict__)
        logger.info(
            'atmo_login_required authentication: %s' %
            request.session.get('username', '<Username not in session>'))
        username = request.session.get('username', None)
        token = request.session.get('token', None)
        redirect = kwargs.get('redirect', request.get_full_path())
        emulator = request.session.get('emulated_by', None)

        if emulator:
            # logger.info("%s\n%s\n%s" % (username, redirect, emulator))
            logger.info("Test emulator %s instead of %s" %
                        (emulator, username))
            logger.debug(request.session.__dict__)
            # Authenticate the user (Force a CAS test)
            user = authenticate(username=emulator,
                                password="",
                                auth_token=token,
                                request=request)
            # AUTHORIZED STAFF ONLY
            if not user or not user.is_staff:
                return HttpResponseRedirect(settings.SERVER_URL + "/logout/")
            logger.info("Emulate success - Logging in %s" % user.username)
            django_login(request, user)
            return func(request, *args, **kwargs)

        user = authenticate(username=username,
                            password="",
                            auth_token=token,
                            request=request)
        if not user:
            logger.info("Could not authenticate user %s" % username)
            # logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return cas_loginRedirect(request, redirect)
        django_login(request, user)
        return func(request, *args, **kwargs)
예제 #27
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)

    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 + 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)

    # 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 + 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 + 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)
예제 #28
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)

    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 + 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)

    # 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 + 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 + 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)
예제 #29
0
    def authenticate(self, username=None, password=None, request=None):
        """
        Return user if validated by OAuth.
        Return None otherwise.
        """
        # logger.debug("OAUTHBackend- U:%s P:%s R:%s"
        #              % (username, password, request))
        # First argument, username, should hold the OAuth Token, no password.
        # if 'username' in username, the authentication is meant for CAS
        # if username and password, the authentication is meant for LDAP
        logger.debug("[OAUTH] Authentication Test")
        if not request:
            logger.debug("[OAUTH] Authentication skipped - No Request.")
            return None
        auth = request.META.get('HTTP_AUTHORIZATION', '').split()
        if len(auth) == 2 and auth[0].lower() == "Token":
            oauth_token = auth[1]
        else:
            oauth_token = None
        if not oauth_token:
            logger.debug("[OAUTH] Authentication skipped - No Token.")
            return None
        logger.debug("[OAUTH] OAuth Token - %s " % oauth_token)

        valid_username, _ = get_user_for_token(oauth_token)
        if not valid_username:
            logger.debug("[OAUTH] Token %s invalid, no user found." %
                         oauth_token)
            return None
        logger.debug("[OAUTH] Authorized user %s" % valid_username)
        oauth_attrs = oauth_lookupUser(valid_username)
        attributes = oauth_formatAttrs(oauth_attrs)
        logger.debug("[OAUTH] Authentication Success - " + valid_username)
        return get_or_create_user(valid_username, attributes)
예제 #30
0
    def atmo_login(request, *args, **kwargs):
        if not request:
            logger.debug("[NOREQUEST] User is being logged out because request"
                         " is empty")
            logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return HttpResponseRedirect(settings.SERVER_URL+"/logout/")

        if not request.session:
            logger.debug("[NOSESSION] User is being logged out because session"
                         " object does not exist in request")
            logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return HttpResponseRedirect(settings.SERVER_URL+"/logout/")

        if not request.session.get('username'):
            logger.debug("[NOUSER] User is being logged out because session"
                         " did not include a username")
            logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return HttpResponseRedirect(settings.SERVER_URL+"/logout/")

        # logger.info('atmo_login_required session info: %s'
        #             % request.session.__dict__)
        logger.info('atmo_login_required authentication: %s'
                    % request.session.get('username',
                                          '<Username not in session>'))
        username = request.session.get('username', None)
        token = request.session.get('token', None)
        redirect = kwargs.get('redirect', request.get_full_path())
        emulator = request.session.get('emulated_by', None)

        if emulator:
            # logger.info("%s\n%s\n%s" % (username, redirect, emulator))
            logger.info("Test emulator %s instead of %s" %
                        (emulator, username))
            logger.debug(request.session.__dict__)
            # Authenticate the user (Force a CAS test)
            user = authenticate(username=emulator, password="",
                                auth_token=token, request=request)
            # AUTHORIZED STAFF ONLY
            if not user or not user.is_staff:
                return HttpResponseRedirect(settings.SERVER_URL+"/logout/")
            logger.info("Emulate success - Logging in %s" % user.username)
            django_login(request, user)
            return func(request, *args, **kwargs)

        user = authenticate(username=username, password="", auth_token=token,
                            request=request)
        if not user:
            logger.info("Could not authenticate user %s" % username)
            # logger.debug("%s\n%s\n%s\n%s" % (request, args, kwargs, func))
            return cas_loginRedirect(request, redirect)
        django_login(request, user)
        return func(request, *args, **kwargs)
예제 #31
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)
예제 #32
0
    def authenticate(self, username=None, password=None, request=None):
        """
        Return user if validated by OAuth.
        Return None otherwise.
        """
        # logger.debug("OAUTHBackend- U:%s P:%s R:%s"
        #              % (username, password, request))
        # First argument, username, should hold the OAuth Token, no password.
        # if 'username' in username, the authentication is meant for CAS
        # if username and password, the authentication is meant for LDAP
        logger.debug("[OAUTH] Authentication Test")
        if not request:
            logger.debug("[OAUTH] Authentication skipped - No Request.")
            return None
        auth = request.META.get('HTTP_AUTHORIZATION', '').split()
        if len(auth) == 2 and auth[0].lower() == "Token":
            oauth_token = auth[1]
        else:
            oauth_token = None
        if not oauth_token:
            logger.debug("[OAUTH] Authentication skipped - No Token.")
            return None
        logger.debug("[OAUTH] OAuth Token - %s " % oauth_token)

        valid_username, _ = get_user_for_token(oauth_token)
        if not valid_username:
            logger.debug("[OAUTH] Token %s invalid, no user found."
                         % oauth_token)
            return None
        logger.debug("[OAUTH] Authorized user %s" % valid_username)
        oauth_attrs = oauth_lookupUser(valid_username)
        attributes = oauth_formatAttrs(oauth_attrs)
        logger.debug("[OAUTH] Authentication Success - " + valid_username)
        return get_or_create_user(valid_username, attributes)