Exemplo n.º 1
0
def cas_validateTicket(request):
    """
    CAS Login : Phase 2/3 After returning from a CAS Login, this request will contain a ticket
    cas_serviceValidate is called to validate the user's ticket
    and the user is returned to 'sendback' (Authorized) or 'login' (Unauthorized) screen
    (Optional - Phase 3/3 - With the username and proxyTicket, a user can be re-authorized.)
    """
    import caslib
    if not request.GET.has_key('ticket'):
        return False
    caslib.cas_setReturnLocation(request.GET['sendback'])
    cas_response = caslib.cas_serviceValidate(request.GET['ticket'])
    (truth, user, pgtIou) = (cas_response.success, cas_response.map[cas_response.type].get('user',None), cas_response.map[cas_response.type].get('proxyGrantingTicket',""))
    if not truth or not user:
        return False
    return user, pgtIou
Exemplo n.º 2
0
def cas_validateTicket(request):
    """
      Phase 2/3 Call CAS serviceValidate
      Phase 3/3 - Return result and original request
    """
    ticket = request.META["HTTP_X_AUTH_TICKET"] if "HTTP_X_AUTH_TICKET" in request.META else None

    (result, username) = caslib.cas_serviceValidate(ticket)
    if result is True:
        logger.info("Username for CAS Ticket= " + username)
    if "HTTP_X_AUTH_USER" in request.META:
        checkUser = request.META["HTTP_X_AUTH_USER"]
        logger.info("Existing user found in header, checking for match")
        if checkUser != username:
            logger.info("Existing user doesn't match new user")
            return (False, None)
        request.META["HTTP_X_AUTH_USER"] = username
    return (result, request)
Exemplo n.º 3
0
def cas_validateTicket(request):
    """
      Phase 2/3 Call CAS serviceValidate
      Phase 3/3 - Return result and original request
    """
    ticket = request.META['HTTP_X_AUTH_TICKET'] \
        if 'HTTP_X_AUTH_TICKET' in request.META else None

    (result, username) = caslib.cas_serviceValidate(ticket)
    if result is True:
        logger.info("Username for CAS Ticket= " + username)
    if 'HTTP_X_AUTH_USER' in request.META:
        checkUser = request.META['HTTP_X_AUTH_USER']
        logger.info("Existing user found in header, checking for match")
        if checkUser != username:
            logger.info("Existing user doesn't match new user")
            return (False, None)
        request.META['HTTP_X_AUTH_USER'] = username
    return (result, request)
Exemplo 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
    cas_setReturnLocation(sendback)
    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"
                     % (ticket, cas_response))
        return HttpResponseRedirect(redirect_logout_url)
    (user, pgtIou) = parse_cas_response(cas_response)

    if not user:
        logger.debug("User attribute missing from cas response!"
                     "This may require a fix to caslib.py")
        return HttpResponseRedirect(redirect_logout_url)
    if not pgtIou or pgtIou == "":
        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(user, pgtIou)
    if not updated:
        return HttpResponseRedirect(redirect_logout_url)
    logger.info("Updated proxy for <%s> -- Auth success!" % user)

    try:
        auth_token = createAuthToken(user)
    except User.DoesNotExist:
        return HttpResponseRedirect(no_user_url)
    if auth_token is None:
        logger.info("Failed to create AuthToken")
        HttpResponseRedirect(redirect_logout_url)
    createSessionToken(request, auth_token)
    return_to = request.GET['sendback']
    logger.info("Session token created, return to: %s" % return_to)
    return HttpResponseRedirect(return_to)
Exemplo n.º 5
0
    def authenticate(
                self,
                username = None,#for 'password' and 'ldap'
                password = None,#for 'password' and 'ldap'
                user_id = None,#for 'force'
                provider_name = None,#required with all except email_key
                openid_url = None,
                email_key = None,
                oauth_user_id = None,#used with oauth
                facebook_user_id = None,#user with facebook
                wordpress_url = None, # required for self hosted wordpress
                wp_user_id = None, # required for self hosted wordpress
                cas_ticket = None, # the CAS ticket
                method = None,#requried parameter
            ):
        """this authentication function supports many login methods
        just which method it is going to use it determined
        from the signature of the function call
        """
        login_providers = util.get_enabled_login_providers()
        assoc = None # UserAssociation not needed for ldap
        if method == 'password':
            if login_providers[provider_name]['type'] != 'password':
                raise ImproperlyConfigured('login provider must use password')
            if provider_name == 'local':
                try:
                    user = User.objects.get(username=username)
                    if not user.check_password(password):
                        return None
                except User.DoesNotExist:
                    try:
                        email_address = username
                        user = User.objects.get(email = email_address)
                        if not user.check_password(password):
                            return None
                    except User.DoesNotExist:
                        return None
                    except User.MultipleObjectsReturned:
                        LOG.critical(
                            ('have more than one user with email %s ' +
                            'he/she will not be able to authenticate with ' +
                            'the email address in the place of user name') % email_address
                        )
                        return None
            else:
                if login_providers[provider_name]['check_password'](username, password):
                    try:
                        #if have user associated with this username and provider,
                        #return the user
                        assoc = UserAssociation.objects.get(
                                        openid_url = username + '@' + provider_name,#a hack - par name is bad
                                        provider_name = provider_name
                                    )
                        return assoc.user
                    except UserAssociation.DoesNotExist:
                        #race condition here a user with this name may exist
                        user, created = User.objects.get_or_create(username = username)
                        if created:
                            user.set_password(password)
                            user.save()
                            user_registered.send(None, user = user)
                        else:
                            #have username collision - so make up a more unique user name
                            #bug: - if user already exists with the new username - we are in trouble
                            new_username = '******' % (username, provider_name)
                            user = User.objects.create_user(new_username, '', password)
                            user_registered.send(None, user = user)
                            message = _(
                                'Welcome! Please set email address (important!) in your '
                                'profile and adjust screen name, if necessary.'
                            )
                            user.message_set.create(message = message)
                else:
                    return None

            #this is a catch - make login token a little more unique
            #for the cases when passwords are the same for two users
            #from the same provider
            try:
                assoc = UserAssociation.objects.get(
                                            user = user,
                                            provider_name = provider_name
                                        )
            except UserAssociation.DoesNotExist:
                assoc = UserAssociation(
                                    user = user,
                                    provider_name = provider_name
                                )
            assoc.openid_url = username + '@' + provider_name#has to be this way for external pw logins

        elif method == 'openid':
            try:
                assoc = UserAssociation.objects.get(openid_url=openid_url)
                user = assoc.user
            except UserAssociation.DoesNotExist:
                return None
            except UserAssociation.MultipleObjectsReturned:
                logging.critical(
                    'duplicate openid url in the database!!! %s' % openid_url
                )
                return None
                

        elif method == 'email':
            #with this method we do no use user association
            try:
                #todo: add email_key_timestamp field
                #and check key age
                user = User.objects.get(email_key = email_key)
                user.email_key = None #one time key so delete it
                user.email_isvalid = True
                user.save()
                return user
            except User.DoesNotExist:
                return None

        elif method == 'oauth':
            if login_providers[provider_name]['type'] == 'oauth':
                try:
                    assoc = UserAssociation.objects.get(
                                                openid_url = oauth_user_id,
                                                provider_name = provider_name
                                            )
                    user = assoc.user
                except UserAssociation.DoesNotExist:
                    return None
            else:
                return None

        elif method == 'facebook':
            try:
                #assert(provider_name == 'facebook')
                assoc = UserAssociation.objects.get(
                                            openid_url = facebook_user_id,
                                            provider_name = 'facebook'
                                        )
                user = assoc.user
            except UserAssociation.DoesNotExist:
                return None

        elif method == 'ldap':
            user_info = ldap_authenticate(username, password)
            if user_info['success'] == False:
                # Maybe a user created internally (django admin user)
                try:
                    user = User.objects.get(username__exact=username)
                    if user.check_password(password):
                        return user
                    else:
                        return None
                except User.DoesNotExist:
                    return None 
            else:
                #load user by association or maybe auto-create one
                ldap_username = user_info['ldap_username']
                try:
                    #todo: provider_name is hardcoded - possible conflict
                    assoc = UserAssociation.objects.get(
                                            openid_url = ldap_username + '@ldap',
                                            provider_name = 'ldap'
                                        )
                    user = assoc.user
                except UserAssociation.DoesNotExist:
                    #email address is required
                    if 'email' in user_info and askbot_settings.LDAP_AUTOCREATE_USERS:
                        assoc = ldap_create_user(user_info)
                        user = assoc.user
                    else:
                        return None
        elif method == 'cas':
            import caslib
            cas_response = caslib.cas_serviceValidate(cas_ticket)
            success, _user = cas_response.map[cas_response.type].get('user',None)

            if success:
                try:
                    assoc = UserAssociation.objects.get(
                                            openid_url = _user + '@ldap',
                                            provider_name = 'ldap'
                                            )
                    user = assoc.user
                except UserAssociation.DoesNotExist:
                    user = User()
                    user.username = _user
                    user.set_unusable_password()
                    user.is_staff = False
                    user.is_superuser = False
                    user.is_active = True
                    user.save()
                    user_registered.send(None, user = user)
                    LOG.info('Created New User : [{0}]'.format(_user))
                    
                    assoc = UserAssociation()
                    assoc.user = _user
                    assoc.openid_url = _user + '@ldap'
                    assoc.provider_name = 'ldap'
                    assoc.save()

            else:
                return None

            
        
        elif method == 'wordpress_site':
            try:
                custom_wp_openid_url = '%s?user_id=%s' % (wordpress_url, wp_user_id)
                assoc = UserAssociation.objects.get(
                                            openid_url = custom_wp_openid_url,
                                            provider_name = 'wordpress_site'
                                            )
                user = assoc.user
            except UserAssociation.DoesNotExist:
                return None
        elif method == 'force':
            return self.get_user(user_id)
        else:
            raise TypeError('only openid and password supported')

        if assoc:
            #update last used time
            assoc.last_used_timestamp = datetime.datetime.now()
            assoc.save()
        return user